I am sending json object from jquery using ajax post and i want to parse through it using php and send the same object back. The post is successful so my object is going there but I am not getting appropriate response. I am sending first name and last name from the html form but the response json object I get is in my console is:-
response : [object Object]
When i try to see the php side in the browser I get errors like :-
<br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\jsonTest\process.php</b> on line <b>8</b><br />
<br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\jsonTest\process.php</b> on line <b>9</b><br />
{"firstname":null,"lastname":null}
I have seen posts on stackoverflow talking about above error but the scenario was different than mine. And I am indeed sending json object from jquery side so I dont know why am i even getting this error. In "network" console i can see that it successfully sends json object.
Here is my jquery part:-
$("#userDataForm").submit(function(e){
e.preventDefault();
var formData={
fname:$("#fname").val(),
lname:$("#lname").val()
};
$.ajax({
type:'post',
url:'process.php',
dataType:'json',
data:JSON.stringify(formData),
contentType: "application/json",
success:function(response){
var response= $.trim(response);
console.log("response : "+response);
}
});
});
Here is the html form I am using:
<form id="userDataForm">
<input type="text" placeholder="Firstname" name="fname" id="fname" />
<input type="text" placeholder="Lastname" name="lname" id="lname" />
<input type="submit" value="submit" name="submit">
</form>
And this is php part:-
<?php
header('Content-type:application/json');
$request = file_get_contents('php://input');
$input=json_decode($request);
$jsonResponse=array(
'firstname' => $input->fname,
'lastname' => $input->lname
);
echo json_encode($jsonResponse);
?>
I have gone through several stackoverflow posts for my error but so far i havent been able to come across any post where json object is sent from ajax and also recieved from php. Also, I would like to know how isset($_POST) will fit in this scenario of the code since I am sending json object instead of a regular form data.