How to save $ .getJSON return value in jQuery

I am making an application using jQuery and Cakephp.

In this I use, as shown below, to get values ​​from my controller

var getformid;
$.getJSON("http://localhost/FormBuilder/index.php/forms/getFormEntry", function(json) {
  getformid=json.forms[0]["id"];
  alert("Form id inside "+getformid);
});//json 

alert("Form id ouside "+getformid);

In the above code, the internal warning that is inside $ .getJSON gives me the correct value as 75 But the external warning shows me an error since getformid is not defined. Why is that? Could we use getformid available outside of $ .getJSON. Please suggest me.SInce, I want to use this value to save the field ..

Edit: IF I try to use code like

var getformid;    
$.getJSON("http://localhost/FormBuilder/index.php/forms/getFormEntry", myCallback);

function myCallback (json) {
  getformid = json.forms[0]["id"];

  // You can work with the response here
}

I get an error since myCallback is not defined. WHy so ?? Also I have to use the getformid value outside myCallback () function

+3
3

, $.getJSON , . , :

var test;
$.getJSON('url', function(data) {
    test = data;
});

alert(test); // you will get undefined here

undefined, JS , $.getJSON (AJAX ), , .

, , , "" - $.getJSON.

var test;
$.getJSON('url', function(data) {
    test = data;
    showAlert(); // this call will display actual value
});

function showAlert() {
    alert(test);
}
+6

, $.getJSON .

, , ,

var getformid;

$.ajax({
    async: false, // This will make call synchronous
    url: "http://localhost/FormBuilder/index.php/forms/getFormEntry",
    dataType: "json",
    success:  function(json) {
        getformid=json.forms[0]["id"];
        alert("Form id inside "+getformid);
        }
 });//json 

alert("Form id ouside "+getformid);

. script, , , , .

+2

The getJSON callback is executed asynchronously, when the request ends, you must work with the value in the callback, if you do not like to have the callback function inside the getJSON call, you can declare the function and process your logic there:

$.getJSON("http://localhost/FormBuilder/index.php/forms/getFormEntry", myCallback);

function myCallback (json) {
  var formId = json.forms[0]["id"];
  // You can work with the response here
}
0
source

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


All Articles