I'm playing with AJAX and PHP.
Description:
I have a HTML page that has some vanilla JS and AJAX.
My AJAX object makes a request to a PHP server. The server returns some JSON object. Which my code takes and processes (creates a Table dynamically and with the data).
What I'm looking for:
However, I would like to have the data (JSON object) stored in global VAR that any function in my JS script can access.
I don't want to do all the processing within the AJAX resquest.
What I've read:
I have read the aspects of asynchronous and synchronous requests, but I'm still confused on how to retrieve the data with the callback functions.Because every time I try to return the data I keep getting a undefine value.
If guys are able to help me return and understand how this part of JS works it would be awesome.
Attached please find my code and an image of what I'm doing (please take into account that the image shows a working system but all the processing is happening inside the AJAX request which is what I to change).
Thank you.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Professor Page - Group 5</title>
<meta charset="utf-8">
<!-- CSS -->
<link type="text/css" href="SORUCE FILE" rel="stylesheet">
<!-- JS
<script src="prof_create_xm_page.js"> </script>
-->
</head>
<body onload="get_questions()">
<section>
<!-- SIDE MENUE -->
<nav>
<ul id="main_manu">
<li> <a href="SORUCE FILE">Home</a></li>
<li>Exams
<ul>
<li> <a href="SORUCE FILE"> Add Questions</a> </li>
<li> <a href="SORUCE FILE">Create Exam</a> </li>
</ul>
</li>
<li>Students
<ul>
<li> <a href="SORUCE FILE">Grading</a></li>
</ul>
</li>
</ul>
</nav>
<article>
<div id="outter_container">
<div id="display_ques" class="innter_pannel">
</div>
<div id="selected_ques" class="innter_pannel">
</div>
<div>
<button id="create_exam" onclick="create_exam()">Create Exam</button>
</div>
</div>
</article>
</section>
<script>
/*--------------------------------------------*/
function contact_server(data){
//Create AJAX object
var xobj = new XMLHttpRequest();
var method = "POST";
var url = "URL TO CONTACT";
//Open Connection
xobj.open(method,url,true);
xobj.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xobj.onreadystatechange = function()
{
if (xobj.readyState == 4 && xobj.status == 200){
var respuesta_ = JSON.parse(xobj.responseText);
console.log("AJAX");
return respuesta_;
}
};
xobj.send(data);
}
/*--------------------------------------------*/
function display_questions(data){
//SOME ACTION
}
/*--------------------------------------------*/
function get_questions(){
var data={
"user":"ucid",
"case":"GetQuestions",
"filter":7
};
data= JSON.stringify(data);
var response = contact_server(data);
display_questions(response);
}
</script>
</body>
</html>
Image