Using JSON data retrieved with AJAX outside success function - javascript

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 );
}

Related

Laravel 5.2 Ajax Returns me undefined value, im doing an edit modal using ajax

i need to show the values depending on the id, here is my button trigger for the edit, the jquery returns me a result when i console.log(result) it gives me data, but when i do console.log(result.company_name) and console.log(result[0].company_name) it gives me undefined, i tried many ways but still not working pls help, im trying to put the value in the modal input field
<button onclick="editClient({{$v->id}})" data-toggle="modal" data-
target="#editClientModal"></button>
here is my jquery ajax
function editClient(id){
var client_id = id;
$.ajax({
url: "{!!URL::to('/clients/edit')!!}/"+client_id,
success: function( result ) {
console.log(result.company_name);
$("#company_name").val(result.company_name);
}
});
}
here is my edit function in the controller
function getEditClient($id){
$data = DB::table('clients')->find($id);
return json_encode($data);
}
in your ajax request just add dataType: "JSON",
function editClient(id){
var client_id = id;
$.ajax({
url: "{!!URL::to('/clients/edit')!!}/"+client_id,
dataType: "JSON",
success: function( result ) {
console.log(result.company_name);
$("#company_name").val(result.company_name);
}
});
}
or if u dont include the dataType, in your success result should add JSON.parse(variable)
JSON.parse(result)['company_name']

How to use variable for url parameter in jquery ajax call?

$.ajax({
type:"POST",
url:"hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table,
contentType: "application/json; charset=utf-8",
crossDomain:true,
dataType:'jsonp',
success:function statusReturn(data)
{
alert("in success");
var parsedata=JSON.parse(JSON.stringify(data));
var stats=parsedata["Status"];
if("1"==stats)
{
alert("success");
}
else
{
alert("failed");
}
}
});
How can I display the contents of the "url" parameter in an alertbox to check what the parameter is containing?
It does not even enter in the "success" parameter. Please suggest me how can I do that.
You can put you url parameter in a variable like so:
var targetUrl = "hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table";
//log your output
console.log(targetUrl, str_table);
Then use it in your ajax call:
$.ajax({
type:"POST",
url: targetUrl,
...
See this fiddle for full example
Try this.url if need to access within event of ajax call. All parameters of ajax call can be accessed via this object. So final statement will be
alter(this.url);
You can see your request parameter in firbug plugin of chrom or firefox

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);
});

Getting JSON response from the server but can't display as HTML with Jquery

I'm building a mobile app and i build a PHP API that renders data from a mysql db and encode it as JSON
i call this api with Jquery ajax to get to display the records from the json output as JSONP and render it in my document in the success function.
so far i get the JSON correctly when i do the request via $.ajax and i can see the data in the Response in my firebug but in the other side the ajax function fires the ERROR not the Success.
i have a demo code in here :jsfidle
this is my $.ajax Call:
$(document).on("pageinit","#myPage", function() {
$("#autocomplete").on("listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
var dataString = 'keyword='+value;
if (value.length > 2 ) {
$.mobile.loading("show");
$.ajax({
type: "GET",
url: "http://example.com/search.php",
dataType: "jsonp",
jsonpCallback: 'jsonpCallback',
cache:true,
data: dataString,
success: function(data) {
$.mobile.loading("hide");
alert(data);
}
})
}
});
});
if you check the net panel you 'll find it successful and there is data coming.
Kindly Advise.
Thanks A lot
Your response is not including the callback jsonpCallback() in the response, the response I'm seeing is simply
({"name": ... })

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

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

Categories

Resources