jquery.post and variable scope - javascript

I'm new to javascript and have the following problem.
I want to load some json from an api.php and succeed with the returned value to fill my GUI.
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) { json = data; });
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
});
So I wanna click a button, then it fetches via post some data ans save this to the variable data.
As it should be an object (json object?) I thought I just can use it as above...
But that doesn't work. Console say: can't find variable json.
Any hints?

jquery post as default works asynchronously which means that the line:
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
occur before the post request have returned the data.
this how it should be done:
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) {
$('#data1').empty().append( data[0].name + ' | ' + data[1].name );
});
});

You have your appending outside the post callback function. Try this:
$( '#data_button' ).click(function() {
$.post( 'api.php', function( data ) {
json = data;
$('#data1').empty().append( json[0].name + ' | ' + json[1].name );
});
});

Related

How do store API response into object so I can use it later in script?

I am using the Yelp API to get info on businesses. I plan to eventually map the response. So I need to store it somewhere in my script in order to access the lat/long
My Ajax request has worked judging by console.log of response. I cant seem to do the next step where I store yelp response into either a JSON or GeoJSON
$.ajax("/yelp", {
data: {
term: searchEstablishment,
location: selectedGeography
},
//this works:
success: function(response) {
console.log(response)
},
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

How to combine two similar scripts and run it with slight variations

I have the following two scripts:
The first one, on grabs a keyword from input#search and populates a dropdown#search-results with the results from the ajax call for that keyword.
$(document.body).on( 'keyup', '#search', function ( e ) {
//e.preventDefault();
value = $(this).val(); //grab value of input text
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(result, function(k, v) {
$('#search-results').append('<li>' + v['Name'] + '</li>');
});
}
});
});
The second script, grabs the value of the clicked dropdown result, does the same action as the first script only this time the ajax result is used to populate fields located on the page.
$(document.body).on('click','#search-results > li', function ( e ) {
//e.preventDefault();
value = $( this ).text(); //grab text inside element
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(response, function(k, v) {
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
}
});
});
Is there a way to combine the second script into the first one so not to make the second ajax call, but be able to populate the fields on the page with the results from the first ajax call depending on the clicked result in the dropdown list?
If the text you insert from v['Name'] into the list item in the first script is the exact same thing you want to use elsewhere in the page in the second script, you can reduce the code way, way down. After all, if you already have the value you want, there's no need to go search for it again.
//first function, just the relevant bits...
$.each(result, function(k, v) {
var newItem = $('<li>' + v['Name'] + '</li>');
$.data(newItem, "value", v);
$('#search-results').append(newItem);
});
//second function, the whole thing
$(document.body).on('click','#search-results > li', function ( e ) {
e.preventDefault();
var v = $.data($( this ), "value"); //grab object stashed inside element
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
This should let you store the entire result object into the list item, then retrieve it later. If you have some elements in that list that you're not putting there with searches, you'll have to do some more work to get their relevant data too.

Jquery remote completion, li's are not selectable

I'm trying to create a text input with text completion using a remote host.
I've been trying to use the example in the following URL: http://demos.jquerymobile.com/1.4.0/listview-autocomplete-remote/
this is the javascript code from the example:
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
so first of all I changed dataType from jsonp to json which makes the ajax call
return a proper json object and the unordered list is filled properly.
the problem that I encounter is that once I see the text completion (the li elements), I can't select any of the elements.
I tried browsing this example on my Galaxy Note 2 and I encountered the same problem, the elements are not selectable.
any ideas how to resolve the issue?
thanks
update
as to #Omar comment i changed the following line:
html += "<li>" + val + "</li>";
to
html += "<li><a href='#'>" + val + "</a></li>";
now i can click on an item but it doesn't do anything. it supposed to close the list and add to the text field the selected item.
You need to delegate an event to generated list items and then update input with the value.
$("#autocomplete").on("click", "li", function () {
/* text of clicked element */
var value = $(this).text();
/* update value of input */
$("#autocomplete-input").val(value);
/* optional - remove autocomplete result(s) */
$(this).parent().empty();
});
Demo

cannot get the results to be displayed on the page

I cannot display the results which I got from database:
{"results": ["USA", "Canada"]}
{"message":"Could not find any countries."} //else
I got this error from console:
Uncaught TypeError: Cannot read property 'length' of undefined.
Could you please check my code to find out what is my mistake.
Here is my view:
My Travel Plans
<div id="my_div">
<div id="country_list_is_got"></div>
<div id="country_list_is_not_got"></div>
</div>
Controller:
if ($this->my_model->did_get_country_list($user_id)) {
$country["results"]= $this->model_users->did_get_country_list($user_id);
echo json_encode($country);
}
else {
$country = array('message' => "Could not find any countries." );
echo json_encode($country);
}
JS file:
$("#load_country_list").click(function() {
$.post('cont/get_country_list', function (country) {
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});
});
You need to tell jQuery what content type is coming back from the server (json)
It defaults to 'string' and it has no reason to think that's incorrect.
See the documentation for the correct parameter order.
Your .each iterator is trying to loop over a string, and - obviously - failing.
Edit: As a point of pedantry, why are you using POST to GET data? "Get" is literally in your URL.
I think it should be $.get or the $.getJSON shortcut, instead of $.post
$.getJSON("cont/get_country_list", function( data ) {
console.log(data);
// something like this for list construction and append to body
var countries = [];
// maybe you need data.results here, give it a try or see console
$.each( data, function( key, val ) {
countries.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "country-list",
html: countries.join( "" )
}).appendTo( "body" );
});
Live Demotry this, issue is results contain array.but you try to use key,value
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
for(i=0;i<country.results.length;i++){
var item = $('<div>'),
title = $('<h3>');
title.text(country.results[i]);
item.append(title);
item.appendTo($("#country_list_is_got"));
}
}

Adding options to select field using javascript from a json file

var json = $.getJSON("../category.json", function() {
alert(2);
})
.done(function() {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
var1.innerHTML = "<option value='" + key + "'>" + val + "</option>";
alert(var1);
})
.fail(function() {
alert( "error" );
});
I want to values from json file as options to my select field. But my code always shows alert error. Please tell me what is wrong with it ?
You're not setting your key and value parameters. In fact it doesn't look like you're getting your JSON results at all.
Change your done method to
.done(function( data ) { /* do stuff */ }
Now your JSON results will be stored in data.
Then you may need to loop through the results. See the example here
try this
var json = $.getJSON("../category.json", function(data) {
alert(2);
})
.done(function(data) {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
$.each( data, function( key, val ) {
var1.innerHTML += "<option value='" + key + "'>" + val + "</option>";
alert(var1);
});
alert(var1);
})
.fail(function() {
alert( "error" );
});
Your JSON is not valid: You cannot use a number as a JSON key
[
{
"NAME":"chair",
"0":"chair" <-- error
},
{
"NAME":"bed",
"0":"bed" <-- error
},
{
"NAME":"table",
"0":"tabl‌​e" <-- error
},
{
"NAME":"almira",
"0":"almira" <-- error
}
]
Try running your JSON through an online JSON parser and the error will come up.
Alternatively, change your error handler to include more information
.fail(function (jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText) }
});

Categories

Resources