Hi i'm trying to retrieve response after passing some variables from javascript to php using jquery ajax functions.
This is the jquery ajax code:
$(document).ready(function() {
$("#invoice_submit_button").click(function() {
var action = $("invoice_form").attr('action');
$.ajax({
type: "POST",
url: action,
data: $('form#invoice_form').serialize(),
dataType: "json",
success: function(response) {
if (response.error == 'none') {
$("#ajax_response").html("<p>" + response.msg + "</p>");
}
else {
$("#ajax_response").html("<p>" + response.msg + "</p>");
}
}
});
return false;
});
});
(ofc there will be different outputs depending on the response.error when get it to work, it's just an example)
This is the php code:
$msg="Bla bla";
$error="form_err";
$result = array('msg' => $msg, 'error' => $error);
$result_json = json_encode($result);
echo $result_json;
Debugging using firebug shows that there're not issues with the posting part but it looks like the script can't get a response from php(and print it into the target div). I'm missing something, i used the same method for other scripts and it has always worked. Thanks
Have you tried to set the content type to application/json in your PHP script?
header('Content-type: application/json');
action
is empty as jQuery cannot find an element invoice_form
.
$("invoice_form").attr('action');
should be $("#invoice_form").attr('action');
.
Are you sure the request is sent to the correct URL?