Hi,

i am doing an application which make use of JQuery and Cakephp .

In this i am using like the following to retrieve the values from my controller side

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 inner alert that is inside $.getJSON gives me the correct value as 75 But the outer alert showing me the error as getformid not defined..Why so??Can't we make use of the getformid available outside $.getJSON .Please suggest me.SInce i want to make use of that value for saving the Field ..

Dani AI

Generated

For : the outer alert is happening before the AJAX callback completes, so the variable hasn't been set yet. correctly called this a race condition, and correctly noted that code which needs the JSON must be invoked from the request's completion (or otherwise sequenced). Declaring a variable outside the callback does not guarantee it will hold the response value by the time outer code runs.

Practical patterns that work reliably:

  • Put follow-up logic inside the success callback (or a function called from it).
  • Return the request as a promise and chain .then() / .done() so later code runs after the response.
  • Use async/await if available to write linear-looking code.

Example (returns a promise and uses it):

function fetchFormId() {
  return $.getJSON('/forms/getFormEntry').then(function(json) {
    return json && json.forms && json.forms[0] && json.forms[0].id;
  });
}

fetchFormId().then(function(id) {
  if (id == null) {
    // handle missing id
    return;
  }
  // save field using id here
});

Troubleshooting notes: if the console reports "ReferenceError: getformid is not defined" (not just undefined), the var declaration is not in the same scope as the alert or there is a typo. Use the browser devtools Network tab to confirm the JSON arrives and the Console for errors. Avoid synchronous XHR; sequence work with callbacks/promises or trigger a custom event from the success handler.

Recommended Answers

All 2 Replies

Hi,

i am doing an application which make use of JQuery and Cakephp .

In this i am using like the following to retrieve the values from my controller side

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 inner alert that is inside $.getJSON gives me the correct value as 75 But the outer alert showing me the error as getformid not defined..Why so??Can't we make use of the getformid available outside $.getJSON .Please suggest me.SInce i want to make use of that value for saving the Field ..

The most likely case is what's called a race-condition. Your outside alert is actually happening before your inside alert because the AJAX call hasn't finished yet and the variable hasn't been set.

aJasmine,

Shawn is right, and the jQuery Documentation for jQuery.getJson confirms it : "Note: Keep in mind, that lines after this function will be executed before callback."

Hence, if you want to do something, reliably, with the Json response, then it needs to be stimutated (or enabled) within jQuery.getJson's callback function.

Statements outside the callback function may use data from the Json response but such statements need to be written in such a way that they are safe - ie. they don't give errors if the data has not yet been delivered.

If you followed that, then it should be clear that (when execution gets past the safety traps) external statements will access the last data delivered, which will not necessarily be the last data requested. If you need to guarantee that your code is working on the response from the latest request, then (until you really really know what you are doing and even then avoid it) work within the callback function.

You are now programming in an asynchronous environment and this is the reality of asynchronicity.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.