jquery - Pass array back to Ajax with php and mysqli -


i working on mini project whereby have 2 mysql database tables (questions , answers). answers table contains questionid. selecting 1 question , 4 related answers using below query in ajax call, works not sure if correct way?

i passing array display on webpage. question being displayed not answers, can see in response in console window values there. i'm thinking maybe because question , answers in same array?

any appreciated.

php/mysqli:

$sql= 'select question questions difficulty = 1 union select answer answers right join questions q on q.id = a.questionid q.difficulty = 1'; $result = $mysqli->query($sql) or die($mysqli->error.__line__);  if($result->num_rows > 0){     $array = array(); // initialize     while($row = $result->fetch_array(mysqli_both)){         $array[] = array(         'question' => $row[0],         'answer' => $row[1],         'answer' => $row[2],         'answer' => $row[3],         'answer' => $row[4]         );       }  } header('content-type: application/json',true); echo json_encode($array);    $result->free(); $mysqli->close(); 

ajax success response:

function response(json){   console.log(json);   var quest = json[0].question;   var ans1 = json[1].question;   var ans2 = json[2].question;   var ans3 = json[3].question;   var ans4 = json[4].question;   $("#questionbox").html('<h2>q: ' + quest);   $("#answerbox").html('<h2>q: ' + ans1); } 

ajax response:

[{"question":"is easy question?","answer":null}, {"question":"yes","answer":null}, {"question":"no","answer":null}, {"question":"maybe","answer":null}, {"question":"who knows","answer":null}] 

response direct browser:

[{"question":"is easy question?","answer":null}, {"question":"yes","answer":null}, {"question":"no","answer":null}, {"question":"maybe","answer":null}, {"question":"who knows","answer":null}] 

var ans1 = json[1].question; 

shouldn't be:

var ans1 = json[0].answer; 

also php code creating array has same answer key 4 times imagine means 1 answer in response though you've set 4 of them. you'll want change to:

  $array[] = array(         'question' => $row[0],         'answer1' => $row[1],         'answer2' => $row[2],         'answer3' => $row[3],         'answer4' => $row[4]         );  

then in javascript:

var ans1 = json[0].answer1; var ans2 = json[0].answer2; 

etc.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -