2

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 ,

3 Answers 3

1

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()

Sign up to request clarification or add additional context in comments.

2 Comments

when i alert the data array value its showing undefined value what do i do
Sorry for replying your comment so later, I was on a trip. I updated the answer, jQuery.get() should indicate the datatype from server. We use json data format here.
0

Use json_encode in php

 <?php
 $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

 echo json_encode($arr);
 ?>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.