jquery function access local javascript variable - javascript

New to jQuery and having simple yet confusing problem. ha2.
I am writing this normal javascript function with jQuery function reading xml file. How do I assigned value to the prodPrice variable declared on the top? the script keep returning 0 value, but if I alert the value within the jQuery function, I managed to get the value that I wanted.
Thank you guys.
function getPrice(valprodID)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
return false;
}
});
}
})
return prodPrice;
}

That's because $.ajax is performed asynchronously.
And it is a great chance for you to learn how to work with $.Deferred
function getPrice(valprodID)
{
var prodPrice=0;
return jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml"
}).pipe(function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
return jQuery(this).find('prodPrice').text();
}
});
});
}
Now you call your getPrice() function in this way:
getPrice(someid).done(function(prodPrice) {
// do what you need with prodPrice
});
Here is an example on jsfiddle: http://jsfiddle.net/zerkms/9MgsX/1/

you can do asynchronous as reported by #xdazz, as #zerkms indicated with Deferred, or anonymous functions:
function getPrice(valprodID, fn)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
fn(prodPrice);
}
});
}
})
}
getPrice(1, function(prodPrice) {
/* your code */
})

You need to set the async option to false, or you should do your work in the callback function.

Related

reset variable after ajax call is done

i am calling a ajax function to check if the inputted data
already exists in the database.
my ajax code is like this.
$(document).on('change','.lawregno',function(){
/// Your validation logic
var regno = $(this).val();
if(regno)
{
var data = 'regno='+ regno; // this where i add multiple data using ' & '
$.ajax({
type: 'POST',
dataType: "json",
data: data,
url: "{{ URL::to('admin/check_regno_exit') }}",
success: function (response) {
if(response=="1")
{
alert('LawRegNo Already Exists');
return false;
}
}
});
}
else
{
return false;
}
});
how should i make the data reset after alert message is shown.
Based on your comment above:
i want to set $(this).val() to null after ajax call is made
First, capture a reference to this since it will no longer be in the same scope. Any variable will do:
var data = 'regno='+ regno;
var element = this;
$.ajax({
//...
});
Then you can use that element variable in your callback function to set the value of that element:
success: function (response) {
if(response=="1")
{
alert('LawRegNo Already Exists');
$(element).val('');
}
}
you can do it inside the success handler . First you have to set a variable with the reference of $(this) like below
var elm = $(this);
Then you can refer it in the success callback.
success: function (response) {
if(response=="1")
{
alert('LawRegNo Already Exists');
elm.val('');
return false;
}
}

why am I getting undefined at the moment when I click my button?

I want to try to display my notification json through ajax, but however when I try first show me undefined, and then show me my json what am I doing wrong?
$(function (doc, win, $) {
var notification = win.Notification || win.mozNotification || win.webkitNotification;
var $badge = $("#notifications-badge");
var $list = $("#notifications-list");
var $button = $("#notifications-button");
URL_GET_NOTIFICATION = BASE_URL + 'notifications/getNotification';
function check_notifications() {
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
}
});
}
$button.click(function (e) {
alert(check_notifications());
});
}(document, window, jQuery));
All functions return undefined by default when called, unless something else is specified.
You'd get the same with just
function go() {};
alert( go() ); // undefined
And that's basically what you're doing, alerting a function that doesn't return anything.
If you return something from the function, it works
function go() { return 'Hello Kitty' };
alert( go() ); // Hello Kitty
But, as you're using ajax inside the function, you can't really return the result from that, as it's asynchronous and executes some time after the result is returned.
You'd have to use a callback or promise to make it work.
function check_notifications() {
return $.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
//data: { timestamp : timestamp },
dataType: 'json'
});
}
$button.click(function (e) {
check_notifications().done(function(data) {
alert(data);
});
});
As a sidenote, use the console when debugging, not alerts.

Javascript response and ajax request

I have the following:
function wikiAjax (searchURL) {
return Promise.resolve($.ajax({
url: searchURL,
jsonp: "callback",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
},
}));
}
$(".search-form").submit(function() {
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.then(function(data) {
alert(data);
}, function() {
alert("The call has been rejected");
});
});
But i get an answer only if I put a breakpoint somewhere (e.g. at the wikiResponse.then line).
Then it looks like the code is executed before the call returns the result but why? Isn't the promise set properly?
Many thanks in advance.
I think what might be happening here is the browser is executing the default submit event on the form in addition to the ajax call. The result is that the window is unloaded and reloaded.
Try putting:
event.preventDefault();
in the handler.
$(".search-form").submit(function(event) {
event.preventDefault();
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.then(function(data) {
alert(data);
},
function() {
alert("The call has been rejected");
}
);
});
I think Promise.resolve() is an ES6 feature so unless you explicitly make sure you support it it should not work.
But, lucky for you $.ajax() return a promise in the following format:
var promise = $.ajax({
url: "/myServerScript"
});
promise.done(mySuccessFunction);
promise.fail(myErrorFunction);
(and not with then() and catch() like was written in your code)
It's unnecessary to do Promise.resolve here, because the $.ajax call already returns a promise.
Try this:
function wikiAjax (searchURL) {
return $.ajax({
url: searchURL,
jsonp: "callback",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
}
});
}
$(".search-form").submit(function() {
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.done(function(data) {
alert(data);
}).fail(function(err) {
alert("The call has been rejected");
});
});
This is a working (and modified to show) plunker: https://plnkr.co/edit/qyc4Tu1waQO6EspomMYL?p=preview

Passing data from variables in JavaScript

I have created a small JavaScript application with the following function that calls a function to retrieve JSON data:
var months = function getMonths(){
$.getJSON("app/data/Cars/12Months", function (some_data) {
if (some_data == null) {
return false;
}
var months_data = new Array();
var value_data = new Array();
$.each(some_data, function(index, value) {
months_data.push(index);
value_data.push(value);
});
return[months_data,value_data];
});
}
I have then created, in the same file, another function that does something when a specific page is loaded. In this function the variable 'months' is passed to the variable 'result'.
$(document).on('pageshow', '#chartCar', function(){
$(document).ready(function() {
var result = months;
var date = result[0];
var values = result[1];
//more code here...
});
}
the problem is that, based on the debugger, the getMonths() function works fine and produces the expected output, but the 'result' variable in the second function can't obtain the values passed to it by the variable 'months'. Do you know how to solve this issue?
The problem is that you $.getJSON() function is asynchronous, so your data gets loaded later then you read it. There're two workarounds:
1. Replace your $.getJSON with $.ajax and setting async: false;
2. Put your code in $.getJSON callback:
var months = function getMonths(){
$.getJSON("app/data/Cars/12Months", function (some_data) {
if (some_data == null) {
return false;
}
var months_data = new Array();
var value_data = new Array();
$.each(some_data, function(index, value) {
months_data.push(index);
value_data.push(value);
});
var date = months_data;
var values = value_data;
//more code here..
})
}
There must be a syntax error.
replace
});
}
With
});
});
$.getJSON() is a wrapper around $.ajax which is async by default. But you treat it like a sync call.
You can use $.ajaxSetup()
$.ajaxSetup( { "async": false } );
$.getJSON(...)
$.ajaxSetup( { "async": true } );
or use $.ajax with async: false
$.ajax({
type: 'GET',
url: 'app/data/Cars/12Months',
dataType: 'json',
async: false,
success: function(some_data) {
//your code goes here
}
});
or if possible change the behavior of your app so that you process your data in a callback function.

How to create jquery ajax as separate function?

I want to create a separate function to get specific data from Facebook graph JSON.
For example, I have the load() and called getNextFeed() function.
The getNextFeed works correctly. Except that returning value of aString is not successful.
When I pop alert(thisUrl). It said undefined.
Note: I am new to Javascript and Jquery. Please give me more information where I did wrong. Thank you.
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
var thisUrl = getNextFeed(url);
alert(thisUrl); // return undefined
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
return aString;
}
});
}
The problem is that $.ajax() is an ansynchronous function, means, when called, it returns in the same instance, but an ajax call is done in a separate thread. So your return vaule of $.ajax() is always undefined.
You have to use the ajax callback function to do whatever you need to do: Basically you already did it correctly, just that return aString does not return to your original caller function. So what you can do is to call a function within the callback (success()), or implement the logic directly within the success() function.
Example:
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
getNextFeed(url);
alert('Please wait, loading...');
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
do_something_with(aString);
}
});
}

Categories