Global variable not accessible in function - jQuery/ajax - javascript

I have a global variable creditAmount that is populated via an ajax call when a user logs in. I would like to use that variable later on in another function that is called after login. How do I keep the value of creditAmount available for this later function?
This is wherecreditAmount gets defined and populated:
var creditAmount = "";
function getCustomer() {
$(function() {
$("#anId").submit(function(event){
event.preventDefault();
var form = this;
var custEmail = $("anotherId").val();
$.ajax({
url: "/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "json",
complete: function(data) {
creditAmount = data.responseJSON;
form.submit();
},
});
});
});
}
And then this is where I need to use creditAmount:
function getPendingCredit(){
var modal = $("#fresh-credit-iframe");
modal.load(function(){
$(this).contents().find("#fresh-credit-continue-shopping").click(function(data){
var enteredAmount = +($(modal).contents().find("#pending_credit_amount").val());
console.log(creditAmount);
$("#fresh-credit").hide();
});
});
}
Finally, this is how I call both functions, but by the time I get to here creditAmount is blank again
getCustomer();
if(creditAmount != ""){
showModal(closeModal);
getPendingCredit(creditAmount);
}

set a delay or use promises/callback. There is a little time gap between the request which is sent with ajax and the response that is received to populate the variable.

Related

Trying to save the response of AJAX() call to a variable but that variable returns empty string [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I am trying to save the reponse of an AJax() call in a javascript variable but this variable returns empty when I append the value to a div .
here is my script code
<script>
/*<![CDATA[*/
$(document).ready(function(){
$("#abusoForm #enviar").livequery("click",function(e){e.preventDefault();
console.log("Click is working");
var hidden = $('#mensajeAbuso').val();
var category = $('#opcmarcar').val();
var name=$('#nombre').val();
var phone=$('#telefono').val();
var mail=$('#email').val();
var cf_mail=$('#confirma_email').val();
var k="<?php echo $this->config->defaultLanguage?>";
var url="somedomain.com/index.php?param=value";
//url = 'proxy.php?url='+url;
var otro = $('#otro_email').val();
var E=$("#abusoForm #enviar").val();
var alto_height = $(window).height();
alto_height = alto_height/4;
//Ajax call happening here
var vajx =$.ajax({url:url,type:"POST",data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}}).responseText;
//Now I have to use the variable vajx to post a message about the submition of the form ;
if(vajx!=""){
$("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(vajx);
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
})
});
/*]]>*/</script>
As you can see in the above image I am getting the response in the console . But when i try to save the response in the var vajx like mentioned in the script above its empty may I know why .
I am very new to Ajax() so need help
UPDATE
After looking into some examples given below and trying my own here is how I could fix it .
Answer
<script>
/*<![CDATA[*/
$(document).ready(function(){
$("#abusoForm #enviar").livequery("click",function(e){e.preventDefault();
console.log("Click is working");
var hidden = $('#mensajeAbuso').val();
var category = $('#opcmarcar').val();
var name=$('#nombre').val();
var phone=$('#telefono').val();
var mail=$('#email').val();
var cf_mail=$('#confirma_email').val();
var k="<?php echo $this->config->defaultLanguage?>";
var url="http://wstation.inmotico.com/index.php?page=avisoajax&type=spam&im_action=reportAbuse&im_core=showAds";
//url = 'proxy.php?url='+url;
var otro = $('#otro_email').val();
var E=$("#abusoForm #enviar").val();
var alto_height = $(window).height();
alto_height = alto_height/4;
//Ajax call happening here
//var vajx =$.ajax({url:url,type:"POST",data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}}).responseText;
var result = ''; // declare a var here
var vajx = $.ajax({
url: url,
type: "POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false},
success: function(data){
$(".appendcontentAbuso").html(data); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
});
/*vajx.done(function (data) {
result = data; // <-----------change here
});
if(result != ""){ // <---------------change here
// $("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(result); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}*/
console.log(data);
//$('#ajxResponse').html(vajx);
})
});
/*]]>*/</script>
Please notice that now I am initiating the popup inside the success: function
Thank you in advance
var vajx;
$.ajax({
url: url,
type:"POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}
)
.done(function( data ) {
vajx = data;
}
});
Try this:
//Ajax call happening here
var result = ''; // declare a var here
var vajx = $.ajax({
url: url,
type: "POST",
data: {
'h': hidden,
.....
async: false
}
});
vajx.done(function (data) {
result = data; // <-----------change here
});
if(result != ""){ // <---------------change here
$("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(result); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
and then you can change your if check little bit like this:
$.ajax has a success handler which handles the response received from the server. So you could do something like this:
$.ajax({
url:url,
type:"POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E},
async:false,
success:function(ret)
{
//the response received from url will be stored in "ret"
var vajx = ret;
// use your conditions here now
}
});

How to unbind or turn off all jquery function?

I have constructed an app with push state. Everything is working fine. However in some instances my jquery function are fireing multiple times. That is because when I call push state I bind the particular js file for each page I call. Which means that the same js functions are binded many times to the html while I surf in my page.
Tip: I am using documen.on in my jquery funciton because I need my function to get bound to the dynamical printed HTML through Ajax.
I tried to use off in the push state before printing with no success!
Here is my code:
var requests = [];
function replacePage(url) {
var loading = '<div class="push-load"></div>'
$('.content').fadeOut(200);
$('.container').append(loading);
$.each( requests, function( i, v ){
v.abort();
});
requests.push( $.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(data){
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
$('a').off();
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
})
);
}
$(window).bind('popstate', function(){
replacePage(location.pathname);
});
Thanks in advance!
simple bind new function with blank code
$( "#id" ).bind( "click", function() {
//blank
});
or
used
$('#id').unbind();
Try this,
var requests = [];
function replacePage(url) {
var obj = $(this);
obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
var loading = '<div class="push-load"></div>';
$('.content').fadeOut(200);
$('.container').append(loading);
$.each(requests, function (i, v) {
v.abort();
});
requests.push(
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data) {
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
obj.bind("click", replacePage); // binding after successfulurl ajax request
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
}));
}
Hope this helps,Thank you

Ajax success function firing before java class responds

I am creating a login function with ajax and am having an issue where the success function (SuccessLogin) fires before getting an ajax response. I am running the code as google web app from eclipse and I can see when debugging the java class file, that the javascript is throwing an alert for the success response from the class being false before the debugger catches the break point in the class file. I have only been writing code for a couple months now so I am sure its a stupid little error on my part.
$(document).ready(function() {
sessionChecker()
// sign in
$('#signInForm').click(function () {
$().button('loading')
var email = $('#user_username').val();
sessionStorage.email = $('#user_username').val();
var password= $('#user_password').val();
var SignInRequest = {
type: "UserLoginRequest",
email: email,
password: password
}
var data= JSON.stringify(SignInRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/login",
type: "POST",
data: data,
cache: false,
success: successLogin(data)
});
});
//if submit button is clicked
$('#Register').click(function () {
$().button('loading')
var email = $('#email').val();
if ($('#InputPassword').val()== $('#ConfirmPassword').val()) {
var password= $('input[id=InputPassword]').val();
} else {alert("Passwords do not match");
return ;}
var UserRegistrationRequest = {
type: "UserRegistrationRequest",
email: email,
password: password
}
var data= JSON.stringify(UserRegistrationRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/register",
type: "POST",
data: data,
cache: false,
success: function (data) {
if (data.success==true) {
//hide the form
$('form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
} else alert('data.errorReason');
}
});
return false;
});
});
function successLogin (data){
if (data.success) {
sessionStorage.userID= data.userID
var userID = data.userID
sessionChecker(userID);
} else alert(data.errorReason);
}
//session check
function sessionChecker(uid) {
if (sessionStorage.userID!= null){
var userID = sessionStorage.userID
};
if (userID != null){
$('#user').append(userID)
$('#fat-menu_1').fadeOut('slow')
$('#fat-menu_2').append(sessionStorage.email).fadeIn('slow') };
}
success: successLogin(data)
There's a difference between a function call and a function definition:
A function definion uses the function keyword and contains a function body {...}
A function call appends parentheses (argument list) to the function name and actually calls the function to return a value
If you assign a function call to the property, it will return a value and that will be what is stored. To avoid this, if your function does not take any parameters you can use the function name, or if your function does take a parameter, embed your function call in another function's definition:
No parameter: success: successLogin
Has parameter: success: function() { successLogin(data); }
You need to wrap your success in an anonymous function in order for it to execute within the scope of the AJAX call instead of being executed inline (immediately):
success: function() { successLogin(data) }

getting variables into ajax function JQuery

I have an AJAX function triggerd by a click which basically copies one table row into another table.
The problem I am having is that I get the required variables from the original table row before the AJAX request however these variables don't seem to be passed to the success function and they come out as undefined.
Is there anyway to pass the variables to the function ?
$('.addfile_popup').on('click', '.add2_fl', function(){
var file_id1=$(this).data('file');
var id=$('.useri').val();
var file_name1=$(this).closest('tr').children('td:first').text();
var upload_date1=$(this).closest('tr').children('td').eq(1).text();
var upload_desc=$(this).closest('tr').children('td').eq(2).text();
var job_idx=$(this).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data:data,
success:function(html){
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
});
});
$('.addfile_popup').on('click', '.add2_fl', function(){
var file_id1=$(this).data('file');
var id=$('.useri').val();
var file_name1=$(this).closest('tr').children('td:first').text();
var upload_date1=$(this).closest('tr').children('td').eq(1).text();
var upload_desc=$(this).closest('tr').children('td').eq(2).text();
var job_idx=$(this).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
// closure function that wrap your variables
function success(file_id1, file_name1, upload_date1 ... ) {
return function(html) {
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data:data,
success: success(file_id1, file_name1, upload_date1 ...)
});
});
You need to use a closure. You can read about them here: How do JavaScript closures work?
This should work:
$('.addfile_popup').on('click', '.add2_fl', function(){
var me = this;
(function() {
var file_id1=$(me).data('file');
var id=$('.useri').val();
var file_name1=$(me).closest('tr').children('td:first').text();
var upload_date1=$(me).closest('tr').children('td').eq(1).text();
var upload_desc=$(me).closest('tr').children('td').eq(2).text();
var job_idx=$(me).data('jid');
//write to appointment database
var data="job_id="+job_idx+"&file_id="+file_id1+"&user_id="+id;
$.ajax({
type:"POST",
url:"admin_includes/prepend_files.php",
data: {
job_id: job_idx,
file_id: file_id1,
user_id: id
},
success:function(html){
var ups='';
ups+='<tr data-file='+file_id1+'><td width="40%">'+file_name1+'</td><td>'+upload_date1+'</td><td>'+upload_desc+'</td><td>VIEW FILE | DELETE</td></tr>';
$(ups).prependTo('.app_table');
}
});//end ajax
})();
});
Note also I've changed how you pass data to the AJAX call.

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources