Reputation: 135
this is how am using the ajax
$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
$this.find(".report").html(data);
and this is my PHP code from where data is coming
<?php
$countresult=0;
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
$result=mysqli_query($dbconnect,$query);
while($rows=mysqli_fetch_array($result))
{
$dbanswer=$rows['answer'];
}
if($dbanswer==$answer)
{
echo "Correct";
$countresult=$countresult+1;
}
else{
echo "Incorrect";
$countresult=$countresult-1;
}
?>
Now previously i was just checking the result is correct or not and displaying tha result but now i want the PHP page to return even the variable that store the counts that is stored in $countresult. I know I have to use json but how to use it in PHP page ,pass the value and get access to that value from another page ,
Upvotes: 2
Views: 86
Reputation: 9082
In your php:
$data = array('countresult' => $countresult);
$str = json_encode($data);
echo $str;
In your js:
$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
alert(data['countresult']);
}, "json");
Document about jQuery.get()
Upvotes: 1
Reputation: 541
Put messages in an array normally:
$server_response['error'] = "something";
$server_response['Success'] = "some other thing";
$sever_response['vars'] = "blah blah";
echo json_encode($server_response);
Then from js if your response variable is ServerResponse, you can access as
ServerResponse.error or
ServerResponse.Success or
ServerResponse.vars
Upvotes: 0
Reputation: 1064
Use json_encode in php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Upvotes: 0