Ajax success function firing before java class responds - javascript

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

Related

my ajax post request is called twice

I have some javascript code in my wordpress site that post an ajax request to a php file and then the file generates a pdf with a quote.
It all works, but I don't understand why the second time I submit the request (to create the second quote, basically), the ajax request then is called twice?
the first time is correct, and it's called one time.
from the second time, it's always called twice.
here's the code:
$('#add-to-cart-quote-email-button').on('click', function() {
var statusIcon;
statusIcon = $('#quote-send-spinner');
$('.send-quote-from-cart-page-container').slideToggle();
statusIcon.removeClass('fa fa-check');
statusIcon.removeClass('fa fa-times');
$('#cart-quote-email-send-button').on('click', function(e) {
var data, email, name, quote_type, role;
e.preventDefault();
name = $('.send-quote-from-cart-page-container #name');
email = $('.send-quote-from-cart-page-container #email-address');
role = $('.send-quote-from-cart-page-container #user-role').val();
quote_type = $('.send-quote-from-cart-page-container #quote-type').val();
if (!name.val()) {
console.log("empty name");
name.addClass('invalid');
return;
} else {
if (name.hasClass('invalid')) {
name.removeClass('invalid');
}
}
if (!validateEmail(email.val())) {
console.log("invalid email");
email.addClass('invalid');
return;
} else {
if (email.hasClass('invalid')) {
email.removeClass('invalid');
}
}
console.log("sent! to email " + (email.val()) + " and name " + (name.val()));
data = {
name: name.val(),
email: email.val(),
role: role,
quote_type: quote_type
};
statusIcon.addClass('fa fa-spinner fa-spin fa-fw');
$.ajax({
type: 'post',
dataType: 'json',
url: '/wp-admin/admin-ajax.php',
data: 'cxecrt-success-get-link-url=&cxecrt-saved-cart-name=&cxecrt-landing-page=cart&action=save_cart_and_get_link_ajax',
success: function(response) {
data.cartURL = response.cart_url;
return $.ajax({
method: 'POST',
url: '/wp-content/themes/theme/generate_pdf_quotes/emailQuote.php',
data: data,
success: function() {
console.log("success!");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
statusIcon.addClass('fa fa-check');
return setTimeout(function() {
return $('.send-quote-from-cart-page-container').slideToggle();
}, 2000);
},
fail: function() {
console.log("fail");
statusIcon.removeClass('fa fa-spinner fa-spin fa-fw');
return statusIcon.addClass('fa fa-times');
}
});
}
});
});
});
return;
I need to call the second ajax on success of the first one, as they do two completely different things and the first one is required by the second one, that it's meant to be like that and it's not (i believe) the cause of this issue
I inspected the code but I couldn't see anything wrong in here.
Any thoughts?
thanks
You are defining an eventHandler within the first eventHandler.
On line 1:
$('#add-to-cart-quote-email-button').on('click', function() {
On line 7:
$('#cart-quote-email-send-button').on('click', function(e) {
That's why the second time it is clicked, it calls twice. I bet if you click it a third time it calls 3x ;-)

Global variable not accessible in function - jQuery/ajax

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.

Set the function itself to the url in AJAX?

I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>

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.

Javascript when to show results

This is my Javascript below I want to show records on load and also show new records when added to the database
showrecords(); displays the records in the database where abouts can I put this in my code where it will work correctly.
$(document).ready(function()
{
//showrecords()
function showrecords()
{
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
}
});
}
$(".comment_button").click(function() {
var element = $(this);
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
// $("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
//Function for showing records
//showrecords();
}
});
}
return false;
});
});
Though polluting the global namespace is not recommended. Here is what I would recommend for your code. Move the showRecords() out of Document ready function and refactor the update ajax code to another function 'updateRecords()'. Have only the event bindings inside the document ready function.
You could return the entire comments as response to POST 'demo_insert.php' service and call 'showRecords()' in the update service success callback.
i've pasted below (untested) code that i think should get the job done. in order to call functions you've got to define them in an accessible area, whether in the "global" (can be called from anywhere) namespace as i've done below, or as part of an another object.
you also need to make sure your functions are defined before you try to call them, as everything works in a top down manner.
function showrecords() {
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function (html) {
$("#display").after(html);
$('content').val('');
$("#flash").hide();
}
});
}
function addComment() {
var test = $("#content").val();
var dataString = 'content=' + test;
if (test == '') {
alert("Please Enter Some Text");
}
else {
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function (html) {
//$("#display").after(html);
$('content').val('');
$("#flash").hide();
//Function for showing records
showrecords();
}
});
}
}
$(document).ready(function () {
showrecords()
$(".comment_button").click(function () {
addComment();
return false;
});
});

Categories

Resources