Reputation: 321
I'm try to get data from php web-service through the java-script.In my project error occurred when parse the JSON.
My PHP web service like this
<?php
header("Content-Type:application/json");
try {
if(!empty($_POST['mobile_number']))
{
$number = $_POST['mobile_number'];
$number = $_POST['user_type'];
deliver_response(200, "success", $number);
}
else
{
deliver_response(400, "no parameter", $number);
}
} catch (Exception $e) {
echo("message".$e->getMessage());
}
function deliver_response($status,$status_message,$data)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
//$response['data'] = $data;
$json_response = json_encode($response);
echo $json_response;
}
?>
And Im try to call above webservice like this
function logingAuth(){
var mnumber= $("#uname").val();
var utype= $("#pword").val();
try{
$.post("http://192.168.1.55/rest/signup.php", { mobile_number: mnumber,user_type:utype }, parseResults);
}
catch(err)
{
alert(err.message);
}
function parseResults(json){
var obj = jQuery.parseJSON(json);
alert(obj.status);
}
}
but this one not working because of var obj = jQuery.parseJSON(json);
line.
If I call like this Its working
function parseResults(json){
alert(json.status);
}
What is this problem?
Upvotes: 0
Views: 76
Reputation: 337560
jQuery will automatically recognise the response type for you and act appropriately. In this case it will automatically deserialise the JSON to an object, so your call to parseJSON
will cause an error as you are trying to deserialise an object. Simply remove that line:
function parseResults(json){
alert(json.status);
}
Upvotes: 4