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 ..

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.