problem in accesing a variable outside of a function in ajax call - javascript

$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
//$.each(result.response.docs, function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
success: function(result){
$.each(result.spellcheck.suggestions, function(i,item){
newquery=item.suggestion;
});
}
});
}
I posted question related to this problem previously: Problem in accessing a variable's changed value outside of if block in javascript code and i got that i have to make ajax call async. So i did like the above code, but still i am not getting updated newquery outside of if block. still it is showing the old value of newquery.
please suggest where i ma doing wrong
edit
$(document).ready(function(){
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
// get the JSON response from solr server
var newquery=query;
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
//$.each(result.response.docs, function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
dataType: 'json',
success: function(json){
$.each(json.spellcheck.suggestions, function(i,item){
newquery=item.suggestion;
});
}
});
}
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", function(result){
Now as i want to use this updated newquery in $getjosn() if result.response.numFound==0,otherwise newquery will hold the old value

Try this:
$(document).ready(function(){
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
var newquery=query;
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
dataType: 'json',
success: function(json){
$.each(json.spellcheck.suggestions, function(i,item){
newquery=item.suggestion;
});
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", function(result){
}
});
}
}else{
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", function(result){
}

The $.ajax(...) call returns immediatly. The success function is a callback function which means that this function is called when the ajaxrequest completes. If you want to change something with the new values recieved you have to do that in the success function.
A second point is, you overwrite your value for newquery with each loop, so newquery will only hold the last element of your result.speelcheck.suggestions list. Not sure if that is what you want.

You are redefining 'result' in the ajax() success function. Change this, and then work on fixing your problem :)

You want to call the getJSON() function within the success function of the $.ajax() request. The success() event isn't called until the data has been returned, this won't happen straight away, and so the final getJSON() event will fire before this.
Moving the getJSON() function to the end of the $.ajax() success function will resolve your problem.
Ensure it's outside the $.each() statement.

new answer based on answer from michael wright:
$(document).ready(function(){
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
var newquery=query;
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
dataType: 'json',
success: commonSuccess});
}else{
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", commonSuccess);
}
//...
}); //End of $(document).ready(...)
function commonSuccess(json){
//do onSuccess for all queries
}

Related

Ajax inside Ajax somehow strange behaviour

I have a Ajax-Call inside a Ajax-Call, everything "seems" to work fine. In console I can see, both calls are executed and get a return.
But somehow, i can't use the returned result from the second call(?)
$.ajax({
type: "POST",
url: "register/checkEmail/"+email,
success: function(result){
if(result == "TRUE") {
$('#regMsg').html('Ein User mit dieser Email ist bereits registriert!');
$('#regMsg').slideDown();
// NO ERROR - REGISTER USER
} else {
$('#regMsg').slideUp();
var inputs = $('#regForm :input').serializeArray();
alert('ok');
$.ajax({
method: "POST",
url: "register/save",
data: inputs,
dataType: 'json',
success: function(result){
alert('ddok');
}
});
}
}
});
the first alert() is beeing displayed, the secont is not, although the second call is executed correctly(?) why is that?
Simple - the second call's response did not return back to the ajax i.e error/fail.
Add the error handling part after success to find the response.
After success add
,error: function(result){
alert('error');
console.log(result);
}
If this is not the reason, then dataType: 'json', should be the culprit as your response wouldn't be in json format !!

Using JSON data retrieved with AJAX outside success function

I have a problem with storing JSON that I get with AJAX, to an outside variable for further usage. Ive checked this answer (load json into variable) which is really basic, but I'm doing wrong something else. My code is below.
function showZone() {
var data=null;
$.ajax({
url: 'http://localhost/gui/templates/tracking/show_zones.php',
//data: 'userid='+ uid ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
type: "POST",
success: function(json) {
data=json;
$( '#res1' ).html( data[0].swlat );
}
});
return data;
}
function showZones() {
var data=showZone();
$( '#res2' ).html( data[0].swlat );
}
For clearer picture of my problem I have two divs (#res1 & #res2), where I print the data. In #res1 I get the result as wanted, but #res2 doesnt print anything and I get an error 'Uncaught TypeError: Cannot read property '0' of null'. So the data is returned before ajax stores it in a variable. Is this the problem, or should I be storing json to a variable differently?
Any help appreciated :)
You can use callback(). Consider following snippet:
function showZone() {
var data = null;
$.ajax({
url: 'http://localhost/gui/templates/tracking/show_zones.php',
//data: 'userid='+ uid ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
type: "POST",
success: function(json) {
data = json;
showZones(data);//callback
}
});
//return data; No need to return data when we have async ajax
}
showZone(); // call when you want to make ajax call
function showZones(data) { // This function will call after ajax response
$('#res2').html(data[0].swlat);
}
$.ajax returns immediately return data which is executed before the function you passed as success callback was even called.So its return as undefined .Its means you can't return ajax data .
For more example How do I return the response from an asynchronous call?
But why can't you use simply like
success: function(json) {
data=json;
$( '#res1' ).html( data[0].swlat );
$( '#res2' ).html( data[0].swlat );
}

Design to block asynchronous javascript

var flow;
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
}
});
$(".flow").append(flow);
Due to the nature of JS asynchronous design, the append would will be execute before it is being assigned a value in ajax call. What is the best way to tell the script to wait until flow gets assigned in ajax call, then do the append? I do not want to put append right below the success, I would like to keep them separate.
The "best way" is to perform the action in response to the asynchronous action:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
$(".flow").append(response.Version);
}
});
If you want to "keep them separate" then you can define a function to call in the response:
var appendFlow = function (flow) {
$(".flow").append(flow);
};
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
appendFlow(response.Version);
}
});
Separating the code into its own function is simply a matter of organizing your code into re-usable components. Either way, by design the response can't be processed until it's received, so you'd perform your actions in response to the asynchronous call.
Anything wrong with:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
$(".flow").append(flow);
}
});
I have no idea why you don't want to put your success handler in the spot for a success handler, but here's an alternative that may help you.
jQuery returns a Deferred instance when you make AJAX requests. You can use its .done() method to set up a callback later.
var dfd = $.ajax( /* your code here, without the success handler */);
// later on...
dfd.done(function (response) {
$('.flow').append(response.Version);
});
See also:
https://api.jquery.com/deferred.done/
https://api.jquery.com/jquery.deferred/
Or:
var request = $.ajax({
url: "qa/version.json",
dataType: "json"
});
request.done(function(response){
$(".flow").append(response.Version);
});

Enable to send data to servlet using AjAx and post method

function validate (user_value){
var name = user_value;
$.ajax({
url:"ggs.erm.servlet.setup5.AjaxS",
data:{ namee :name},
success:function(){
alert("worked");
}
});
}
This is my Code. Is something wrong with it?? Any kind of syntax or semantics error. Problem:Not able to send parameter to servlet in URL.?????
If you want your servlet's doPost method to handle the request you should add property type with value post.
function validate (user_value){
var name = user_value;
$.ajax({
url:"ggs.erm.servlet.setup5.AjaxS",
data:{ namee :name},
type: 'post',
success:function(){
alert("worked");
}
});
}
This way your Ajax request will be post instead of get (the default one).
It seems that your function is in doc ready handler check this out and see if helps:
function validate (user_value){
var name = user_value;
$.ajax({
url:"ggs.erm.servlet.setup5.AjaxS",
type:'POST', //<-----------------added this
data:{ namee :name},
success:function(data){
if(data){
alert("worked");
}
},
error:function(){
alert('not worked.');
}
});
}
$(document).ready(function(){
// your other code stuff for calling the function
});

Trigger success handler is finished executing, with nested ajax requests

I have many nested ajax requests like below. I have a lot of things going on in the success function below, I need something like success that will trigger when success is complete. complete(jqXHR, textStatus) just seems to fire with success and I don't think .ajaxComplete() works.
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests
},
});
SOLUTION:
A $.ajax() replacement plugin called $.fajax() (finished + ajax) has been created. Please check it out and let me know what you think. https://github.com/reggi/fajax (It's pretty well documented).
You could create a wrapper function for jQuery.ajax to make this a little cleaner:
var started = 0, done = 0;
var globalHandler = function(){
//do stuff when all success handlers are done
}
function handleAjax(args){
var _success = args.success || function(){};
args.success = function(jqXHR, textStatus){
_success(jqXHR, textStatus);
done++;
if(done >= started)
globalHandler();
}
var ajax = $.ajax(args);
started++;
return ajax;
}
usage
handleAjax({
url: 'api/periods.json',
dataType: 'json',
success: function (d1) {
//more nested ajax requests like this:
handleAjax({...});
}
});
This creates a closure so don't do any crazy memory-intensive stuff in there and you should be fine.
I'm not quite totally sure of what you're asking, so forgive me if I'm off-kilter, but I think you might want something like:
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
},
}).done(function(msg){
alert("Every Ajax Call is Complete!");
});
You may want .queue() or .Defered
$("#el").queue("queue_name",function(){
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
//more nested ajax requests
$("#el").dequeue("queue_name"); // tell queue success is complete
},
});
}).queue("queue_name",function(){
//do something you want when success is complete
})
$("#el").dequeue("queue_name"); // start to execute
or $.Deferred()
$.ajax({
url: 'api/periods.json',
dataType: 'json',
success: function(d1){
var start = function(){
var dtd = $.Deferred();
//more nested ajax requests---------------
$.post("xxx",function(){
dtd.resolve(); // when success is complete
});
//----------------------------------------
return dtd.promise();
}
start.apply(this).pipe(function(){
//do something you want when success is complete
});
},
});

Categories

Resources