Rajeet Rajeet - 7 months ago 13
Javascript Question

JSON returns null

I am facing the problem in getting the variable value through getJSON. Here is the code the i am trying!

display.php

<html>
<body>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$.ajax({
type:"POST",
url:"code.php",
cache:false,
data: {id:102},
success: function(result){
alert(result); // this alert shows the proper result included the values of id.
$.getJSON("code.php", function(data) {
alert("Value for 'a': " + data.first + "\nValue for 'b': " + data.last);
});
}
});
</script>

</body>
</html>


code.php

<?php
$var1=$_REQUEST['id'];
$var2="Some hard codded text";
$output = array('first'=>$var1,
'last'=>$var2);
echo json_encode($output,JSON_PRETTY_PRINT);
?>


I am using alert(result) as well as the getJSON to check the value of the variable, alert(result) shows both the values but the getJSON returns "null" for ID value.

Answer

The data parameter needs to be sent while calling $.getJSON Use add data parameter as shown below code:

 $.getJSON("code.php", data, function(data) {
  alert("Value for 'a': " + data.first + "\nValue for 'b': " + data.last);
});