I have written this code to call a php function from javascript, the php function simply prints the arguments it receives, but this code is giving no output and nothing is printed, I am using google chrome browser, kindly help.
index.html file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
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);
}
}
});
</script>
</head>
</html>
save.php file
<?php
header('Content-Type: application/json');
if( $_POST['functionname'] == 'saveUser' ) {
echo json_encode(Array(
result => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
));
}
?>
output enter image description here
asked Dec 27, 2015 at 9:39
Ali Salman
691 gold badge1 silver badge6 bronze badges
2 Answers 2
There is a typo. you are missing to quote the array key
try this
echo json_encode(Array(
'result' => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
^ ^
));
answered Dec 27, 2015 at 9:51
Nouphal.M
6,3281 gold badge20 silver badges28 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You have a syntax error in your save.php file. Enclose the result index by string quotes. Fix it first
if( $_POST['functionname'] == 'saveUser' ) {
echo json_encode(Array(
'result' => $_POST['arguments'][0] . ' ' . $_POST['arguments'][1]
/*^^^^*/
));
}
And in index.html just add below the codes in ajax success.
success: function (obj, textstatus) {
if( !('error' in obj) ) {
document.write(obj.result); //This line
alert(obj.result);
}
else {
console.log(obj.error);
}
}
Comments
default
functionnamedeclared which you are sending via POST method?error_reporting(E_ALL); ini_set('display_errors', 1);Ctrl+U?