I want to call a PHP function from JavaScript.
I am calling the PHP function by passing two arguments and I want that PHP function to simply echo those arguments. For that, I have written the following code but it is not working, meaning that the code prints nothing. Please help.
JavaScript
jQuery.ajax(
{
type: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:[username, password]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
PHP
<?php
header('Content-Type: application/json');
$aResult="done";
if( $_POST['functionname'] == 'saveUser' ) {
echo $_POST['arguments'][0] +" "+ $_POST['arguments'][1];
echo json_encode($aResult);
}
?>
json_encode($aResult);? PHP file is not sending validjsoneither..echo $_POST['arguments'][0] +" "+ $_POST['arguments'][1]; echo json_encode($aResult);will not return valid json I suppose. Onlyecho json_encode($aResult);would do..+is being used to concatenate.. Use... If you'd like, I can remove my answer so you can post that as an answer. (I don't do PHP much, was off figuring out why it wasn't working.)