How to use a JSON object received by one JavaScript function in another function?

I wrote a function that returns the JSON format through an ajax call. JSON -

{ "communication": [{ "communication_name": "None", "communication_id": "1" }], "hardware": [{ "hardware_name": "XXXXXXXX", "hardware_id": "6" }], "Sofware": [{ "software_name": "XXXXXX", "software_id": "3" }, { "software_name": "XXXXXXXXXXXXX", "software_id": "4" }] } 

And this is the JavaScript function to get this answer:

 function getModelData(model_id, model_name){ var xmlHttp = createXmlHttpRequestObject(); try { xmlHttp.open("GET", "ajaxmodel_new.php?model_id="+model_id,true); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status==200){ var myJSONObject = JSON.parse(xmlHttp.responseText) //alert(myJSONObject.communication[0].communication_name) } } xmlHttp.send(null); } catch (e){ alert("Can't connect to server:\n" + e.toString()); } } 

He gets the correct answer. And there is another function to get the selected value in the selected drop-down list:

 <div id="selected_options"> <select onchange="test()" id="selected_opt"> <option value="0" selected>-Select-</option> <option value="1">Communication</option> </select></div> function test() { var get_id = document.getElementById('selected_opt'); var result = get_id.options[get_id.selectedIndex].value; alert(result); } 

goal

I need to use a JSON response, i.e. myJSONObject , in the test() function. How can I use this var myJSONObject , which is obtained in the getModelData() function of ajax in the function test() ?

+4
source share
2 answers

I had a different approach in analyzing the JSON object.

On the PHP side, I create an object and store it in a variable, say $JSONvar . Now I am an echo variable.

Then on the client side, this is how I intercept the object.

 var JsonObject = {}; var http = new XMLHttpRequest(); http.open("GET", url, true); //url is the url echoing the jsonString http.onreadystatechange = function () { if (http.readyState == 4 && http.status == 200) { var responseTxt = http.responseText; myJSONObject = eval('(' + responseTxt + ')'); test(myJSONObject); } } http.send(null); 

Your test function should have access to an object like this,

 function test(myJSONObject) { var object = myJSONObject; alert(object); var get_id = document.getElementById('selected_opt'); var result = get_id.options[get_id.selectedIndex].value; alert(result); } 
+4
source

Call test() from the function in xmlHttp.onreadystatechange , passing the decoded object as a parameter.

+2
source

Source: https://habr.com/ru/post/1345189/


All Articles