Update MySQL database with AJAX - javascript

I have a form with a submit button and a close button. If a user enters something and hits the submit button, an answer will be posted and saved inside the database. If a user clicks the close button, inside the database an entry will be updated with the current timestamp.
Everything is working fine but now I would like to make those changes if someone clicks the close button with AJAX so that I do not have to reload the page.
The code for my submit button is:
<input type='submit' id='setclosed' value='Close Ticket' name='setclosed' class='btn btn-warning' />
Now if someone clicks the submit button, the followin code will be activated inside my current file (so no external file for php processing):
if (isset ($_POST['setclosed'])) { // Setze Status auf Closed
$updatecontent_success=array('stamp_closed'=>$localtime);
updateContractTicket($show_details,$updatecontent_success);
}
What do I have to do so that the database entry will be updated, but the page does not reload?

Here is a quick AJAX example to get you going. You should separate you PHP and Javascript/HTML code. I'll write out the two files.
In your HTML file you'll have the html code and the javascript that will make the request, and then alert the user that the request went through. Make sure that your form doesn't submit anything.
-HTML
<button type='button' id='setclosed' name='setclosed' class='btn btn-warning'>Close Ticket</button>
-Javascript
$('#setclosed').click(function() {
$.post('ajax.php',
{ cmd: 'setclosed' },
function(data) {
alert('AJAX request was made');
}, 'json'
);
});
The ajax sends a POST variable read by the PHP as $_POST["cmd"]. This will let your php execute the necessary code for that command, echo back a status, and then exit the php file.
-PHP
if ($_POST["cmd"]=='setclosed') {
$updatecontent_success=array('stamp_closed'=>$localtime);
$updateContractTicket($show_details,$updatecontent_success);
echo json_encode(array('Status' => 'Ok'));
exit(0);
}
Let me know if anything is unclear.

Related

How can I make a JS send data to PHP on Button Click/Dropdown opening?

I'm developing a Notification System on my web application and I'm new to JS/Ajax. What I need to do is to send a variable to my PHP which runs a Update code on my server to set the notifications as read, ideally, when the user opens the Notification Dropdown.
I've tried to use OnClick functions, however, the button didn't seem to activate the Ajax as no data was updated. Currently I'm also trying to use a 'data-role' on my a tag + $(document).on('click','a[data-role=...) on the dropdown a tag, and yet the ajax doesn't seem to activate. I've look around and I didn't seem to find anything related to such a thing. I don't know if since the a tag is already toggling the dropdown it's unable to also toggle the ajax?
Disclaimer: This is my first question here, so sorry if I oversimplify/overcomplicate things.
Ajax Code
$(document).ready(function(){
$(document).on('click','a[data-role=update]',function(){
var read = 'Y';
$.ajax({
url : 'Notification.php',
method : 'post',
data : {read : read},
success : function(response){
// now update user record in table
alert("Ajax sent the info!");
}
});
});
});
Which should be activated when user clicks on the dropdown toggle
<a href="#" class="m-nav__link m-dropdown__toggle" data-role="update">
<span class="m-nav__link-badge badge badge-square badge-danger">
<?php echo $count; ?>
//This var is just a badge w/ a number of notifications
</span>
<span class="m-nav__link-icon">
<i class="flaticon-music-2"></i>
</span>
</a>
My Notification.php has the following code.
include_once("../app_config.php");
$read = $_POST['read'];
if ($read='Y') {
$conexaon = new Connection();
$sqlu = "UPDATE tbl_prinotificacao SET pn_unread = 'N' ORDER BY pn_datetime desc";
$resultu = $conexaon->consulta($sqlu);
if($resultu){
echo 'data updated';
}
}
I expect to ajax to send the var via post for the PHP when the user opens the dropdown and when the user changes pages, the notifications should be gone. I tested the PHP alone and it does updates the data on the table. However, nothing ajax related happens when I open the dropdown, it only opens the dropdown normally and doesn't activate the ajax.
Thanks to #NicoHaase's Suggestion of the Network debugging, I was able to find the problem. the ajax url was incorrect. I corrected the url and the code worked.
I had to change the url to get the correct path to Notification.php
$(document).ready(function(){
$(document).on('click','a[data-role=update]',function(){
var read = 'Y';
$.ajax({
url : '../../resource/include/Notification.php',
method : 'post',
data : {read : read},
success : function(response){
// now update user record in table
alert("Ajax sent the info!");
}
});
});
});
The problem seemed to happen since even though the Notification.php was on the same folder as the Menu file that I was using the a tag, it was being imported on the index file on another folder, so I had to adapt to that path. Thank you Nico Hasse.

How do I append html to another page from the current page?

I am making an interactive ticket system. I have two pages: ticket.php and myaccount.php.
On the 'myaccount' page is a ticket management system where a admin can assign themselves tickets. What I want to do is when an admin views the ticket and makes a response and updates the status of the ticket on ticket.php, I want myaccount.php to reflect the update of the status (without refreshing the page of course).
As of now, my ajax call works and it gets the POST value from another page. However, I want to update the div in myaccount.php FROM ticket.php.
Here is the ajax which is stored in a file called action.js, this function is being called in ticket.php and I want it to update a div in myaccount.php:
function current_ticket() {
$.ajax({
type: "POST",
url: '../user/phpfunc/ajax.php',
data:{current_ticket: 'current_ticket_list'},
success:function(html) {
alert(html);
//This function is called in ticket.php. I want it to update a div
//in myaccount.php
}
});}
Here is the button being pressed that calls current_ticket() in ticket.php:
<input type="submit" name="submit" value="submit" onclick="current_ticket();">
Here is ajax.php as requested:
if(isset($_POST['current_ticket'])) {
echo 'test';}
I have looked for an answer and I can only find code which gets content FROM a div, but I want to send content TO a div in another file. Help is appreciated, thank you!!
$("#div").append(YOUR_RETURN_HTML); would do the job.
Moreover, you have set the type='submit' and you have added an event onclick as well.
Either disable the default submission or change the type to button.

How can I confirm something in JavaScript and then use

I have a form and when you submit it, a JavaScript message appears.
$message = "Want to insert?";
echo "<script type='text/javascript'>window.confirm('$message');</script>";
And what I want to do is, if the person clicks 'OK' it inserts values in the database, if not it cancels it.
$titulo = $_POST['titulo'];
$mensagem = $_POST['mensagem'];
$ano = $_POST['ano'];
$mes = $_POST['mes'];
$dia = $_POST['dia'];
$link = " ";
Use <form> tag, and handle the onsubmit event. once he clicked 'OK' on message box submit the form.
Once the form gets submitted, In server side (PHP) write a code to get the data ( either by GET/POST which ever way you are sending) and insert into the table.
In simple words, PHP executes first, and then client side JavaScript executes. If you want it to be interactive, you must use AJAX, which will allow you to send PHP command controlled by JavaScript.
If I were you, I would do this way:
if (confirm("Are you sure?"))
$.post("path/to/php.php", {data: you_need_to_send}, function (response) {
if (response == "OK")
alert("All Done!");
});
else
alert("You cancelled the insertion.");
Note: Here, $.post() is a jQuery implementation of AJAX POST method. Just for ease of explanation I gave this. Please don't shout at me for answering a jQuery way for a JavaScript question.
Update
You can use onsubmit of the form to make this possible. Make sure you give a return inside the event:
<form method="post" action="http://example.com/" onsubmit="return confirm('Are you sure?');">
<input />
<input type="submit" value="Send" />
</form>
Run the above snippet and check it out.
You need to pass data using a request to your server. You cannot use JavaScript to write in you database directly since you already use PHP
But to confirm the user before you send your request or you can use this in your JavaScript code before you send your request.
if (confirm('Your Message')) {
// User click OK
// Send your data to server using a Request
} else {
// User click cancel
}

Trouble passing a variable from javascript page to php page

I want to send a string from one php page to another via a JavaScript page.
The string is sent through upon the push of a button. The name of the
button is changed each time it is displayed and the name of the button is
the one that is sent through. The problem is, it is not getting displayed in
next php page but the alert() function outputs the string as required. What
is wrong with the code?
Here is the php code in the first page
echo "<form method = 'post' action = 'passer.php'>
<input type = 'submit' value = 'play' name = '$ball'></input>
</form>";
Here's the javascript code
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
console.log(cat);
$.post("studSport.php",{input: cat}, function(data){
});
});
And the php code in the next page
{
$receiver = "";
if(isset($_POST['input'])){
$receiver = $_POST['input'];
echo $receiver;
} else{
echo " it is empty";
}
}
The output is always "it is empty" even though the alert() displays the right variable. What is wrong with the code, why wont $receiver be displayed?
Your Ajax request never runs. When you click the input you trigger it… but the input is a submit button so the Ajax request is canceled, the form submits, and a new page is loaded.
Since your form doesn't have an input named input, you'll always failed the test if(isset($_POST['input'])). (The Ajax request, which gets canceled, does input input, but you never make that request).
To stop the form submitting you need to capture the event object and prevent the default behaviour that the event would normally trigger.
$(':input').click(function(evt){
evt.preventDefault();
Note, however, that your success handler function:
function(data){
}
… does nothing, so you won't be able to see the result without inspecting the HTTP response using your browser's developer tools.
It is possible that your goal isn't to use Ajax, but is to load a new page - just with additional data in the form.
To do that, you need to modify the controls in the form instead.
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
$(this).append(
$("<input type='hidden' name='input'/>").val(cat)
});
});
But if you just want to tell which submit button was pressed then don't involve JavaScript at all. Just use a submit button with the name and value you want.
<form method='post' action='passer.php'>
<button name="input" value="<? echo htmlspecialchars($ball); ?>'>
play
</button>
</form>

How does "Add Comment" javascript/AJAX work on stackoverflow?

I was just looking at the code in firebug and I can't follow it. I can't figure out how clicking "add comment" calls the jquery function that shows the comment form. On my site I am trying to mimic this behavior. I have a registration form and I want a link such as "Fill in my data" which then displays a text input below the link where they enter a code, and then a submit button that through AJAX populates the fields. I am new to js and AJAX, but am a quick learner so I was hoping to get some clarity here on the details of implementation. Seems to me the displaying of the input field should not be AJAX, but just js. And then submit would trigger the AJAX function. I know AJAX is fairly involved, in terms of having to create an xml that describes the server side data that needs to be collected and then somehow submit button will trigger call to server side php script or something. Conceptually I understand, but mechanically I don't... Thanks! Brian
I just tried implementing as described, but the url is not triggering the js. Here is what I have:
<script type="text/javascript">
$(function(){
$(".previousreg-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".previousreg-form-container").show(); // Show the form parent
});
$(".previousreg-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
</script>
<a href=# class=previousreg-link>Use previous registration data</a>
<div class="previousreg-form-container dno">
<form>
<textarea name=previousreg></textarea>
<input type=submit>
</form>
</div>
Because my site already loads jquery I didn't add the script declaration for jquery. Is anything above obviously wrong? Thanks.
Here in StackOverflow, the form is already present, but hidden initially (to save valuable space).
(StackOverflow uses a .dno class to hide elements.)
The click on the add a comment button does simply:
hide the clicked add a comment button
show the DIV holding the form
A simple way to do it:
$(function(){
$(".comments-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".comment-form-container").show(); // Show the form parent
});
$(".comment-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
.dno{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href=# class=comments-link>add a comment</a>
<div class="comment-form-container dno">
<form>
<textarea name=comment></textarea>
<input type=submit>
</form>
</div>
Regarding the $.ajax
since by submitting the form we don't want the page to refresh, AJAX is used to POST data to a PHP (let'ssay: saveComment.php page) which than stores to database. AJAX returns than a message response from the PHP code:
$.ajax({
type : "POST",
url : "saveComment.php",
data : $(this).serialize(), // `this` is our form
success : function( response ) { // Response is the PHP echo
alert("PHP says: "+ response);
// Using jQuery append the message to
}
});
The PHP stuff
in the code above AJAX will POST a serialized data to PHP like:
comment=Please, show what you tried!
The saveComment.php than might look like:
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit; // Don't allow anything but POST
$response = "";
if ( isset($_POST["comment"]) ) {
$commment = htmlspecialchars( $_POST["comment"] );
// TODO: $userId = retrieve here the user ID from the session;
// Sanitize(!!!!!) and save to database $comment and $userId
$response = $commment;
} else {
$response = "Please, enter a comment";
}
echo $response; // This will be sent/returned to AJAX
exit;
above, whatever you put in the echo, it will be returned by AJAX into the response argument.

Categories