Harry12345 Harry12345 - 20 days ago 5
jQuery Question

PHP Ajax function not posting data

I'm trying to use Jquery to call an ajax function, which updates an MySQL database. I have several other Ajax requests in the same file and they work fine. For some reason the getinvoices value is not being passed to the PHP file. I'm calling the function on click of a button, below is the code I'm using.

Javascript



$( "#updatexero" ).button().on( "click", function(event) {
$.ajax({
type:'post',
url: 'invoices.php',
data: { getinvoices: 1 },
success: function(){
$( "#sql-confirm" ).dialog({
modal: true,
buttons: {
OK: function() {
$( this ).dialog( "close" );
}
}
});
}
});
});


PHP - invoices.php



if ( isset($_REQUEST['getinvoices'])) {
//Code to do stuff
}


If I do
echo $_POST['getinvoices'];
, it says undefined index, as no value has been passed. I can't see why this shouldn't work, what am I doing wrong?

Edit: I have solved the issue now, the problem was another
if
statement in
invoices.php
that wasn't getting called, so nothing to do with the Ajax query. The firebug extension proved handy for debugging though.

Answer

Your code is correctly written. I adopted your code "as is" and put it on my own server.

In invoices.php I simply put:

<?php 
    print_r( $_POST );
?>

This is the result I got when checking in the debug console:

enter image description here

I would advise you to use this debug console to check your AJAX request. It's included in both Chrome and FireFox. In chrome you need to install the extension Firebug Lite however. You'll see in my picture that getinvoices is both included in the AJAX post and received by the invoices.php script.

The debug console will also alert you if there is a syntax error in your JavaScript code.

However.. you can change the following code:

$( "#updatexero" ).button().on( "click", function(event) {

to

$("#updatexero").click(function(event){