Variable not accesable in ajax response - javascript

I'm having troubles using a global variable in my ajax response.
LastDate is a variable defined in the page I loaded into my second page. (function load_table)
I am able to acces the variable before the ajax call, but I can't seem to acces it in my ajax succes. because it gives undefined. <==== in code
my code:
var dia_date = {};
$(window).load(function()
{
DP("eerste keer")
load_table();
} );
function load_table()
{
DP('load_table');
$.ajax({
type: "POST",
url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID,
success: function (data) {
$("#diagnoses_zelf").html('');
$("#diagnoses_zelf").append(data).trigger('create');
//initialize_table();
update_table();
},
error: function(){
alert('error');
}
});
return false;
}
function update_table()
{
if(LastDate > Datum)
{
alert("LasteDate" + LasteDate);
}
else
{
alert("Datum" + Datum);
}
alert('gast .... ' + LastDate); // <========== this is promted on the screen so there is no problem
$.ajax({
type: "POST",
url: "/refresh_diagnose/" + DosierID,
dataType: "json",
data : JSON.stringify(dia_date),
success: function (data) {
var DataDate = new Date(data.Year, data.Month, data.Day, data.Hour, data.Minute, data.Second);
alert('lastdate :'+ LastDate + 'date.date :' + DataDate);
//<============ BUT HERE HE GIVES LastDate AS UNDEFINED
},
error: function(data){
alert(data);
}
});
return false;
}
I can't see what I'm doing wrong. Can annyone help me plaese ? Thanks in advance.

You can try making a function.
var lastDate = #;
function getLastDate(){return lastDate;}
ajax.blablabla.success :{getLastDate();}

Related

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

How to display a progress bar during an ajax request (jquery/php)

I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.

Youtube Search js function

While i was searching at stackoverflow, i found the code below :
$(document).ready(function () {
$("#show").click(function () {
getYoutube($("#Search").val());
});
});
function getYoutube(title) {
$.ajax({
type: "GET",
url: yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + title + '&format=5&max-results=1&v=2&alt=jsonc',
dataType: "jsonp",
success: function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_id = data.id;
var video_title = data.title;
var video_viewCount = data.viewCount;
$("#result").html(video_id);
});
} else {
$("#result").html('false');
}
}
});
}
How can i edit the code to keep only the function?
I want to be able to use it like that : getYoutube(my_keywords);
Also, how can i save the function output to variable? something like :
var_name = getYoutube(my_keywords);
would be ok?
Thnx! ;)
yes, you can use it as without $(document).ready. No, function does not return anything
To "return" value from Ajax:
$.ajax({
...
success: function(dataFromServer) {
processServerOutput(dataFromServer);
}
});
function processServerOutput(someString) {
alert(someString);
}

How do you stop a user from repeatedly clicking a jQuery AJAX call?

I have a web-page with the following script
Javascript
function LinkClicked() {
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
}
});
}
How do I stop the user from repeatedly clicking whilst the query is running? The call is from a cell in a grid and can't easily be disabled. Ideally, I'd like a way of doing it in the script without disabling the link on the DOM.
Here I clicked five times, and you can see five AJAX requests are sent. The page should disable the same call being repeatedly invoked whilst it is already running.
Thanks in advance.
You could have an external variable tracking the state
var linkEnabled = true;
function LinkClicked() {
if(!linkEnabled){
return;
}
linkEnabled = false;
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
linkEnabled =true;
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
linkEnabled = true;
}
});
}
This also has the advantage that you can choose to enable other effects of this function if you want, and only prevent the repeat ajax calls.
(Note that ideally you would want to stick the external variable in a closure or a namespace rather than making it a global).
Disable a button when user clicks it, and set disabled to false when you get response from ajax.
Declare a variable outside of the function with an initial value of false:
var pending = false;
When you make the request, you'd do:
if (pending == true) {return;}
pending = true;
This makes it stop if you're already running, and when the request is done:
pending = false;
Now even without a button, the request won't fire multiple times.
As a side note, your data doesn't need to be a string. You can just do:
data: {stage: stage, stop: stop, nDays: nDays}
you can just check use this
var ajax_stat = false
function doing_ajax(){
if(ajax_stat) return;
ajax_stat = true;
var xmlRequest = $.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
ajax_stat = false;
}
});
}
Use below code. it will not make multiple ajax calls.
function LinkClicked() {
if($(window).data("ajaxRUnning")){
return;
}
$(window).data("ajaxRUnning",true);
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
$(window).data("ajaxRUnning",false);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
$(window).data("ajaxRUnning",false);
}
});
}

updating to separate DIVs via ajax

I have 2 elements on my page that I am trying to reload via ajax - however I can only ever seem to update one. Below is my code,
$('#messages_send').live('click', function() {
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
success: function(data) {
sending_message();
var x = jQuery.parseJSON(data);
if(x) {
if(x.gp_id==80)
{
$('#spn_ucredit').load(base_url + 'ajax/userdata/credits');
$('#overlay_credits').load(base_url + 'ajax/userdata/credits');
}
}
//$('#spn_ucredit').html($('#ncd_id').val());
//tmp_cost = $('#spn_ucredit').html()-$('#ncd_id').val();
//$('#ncd_id').val($('#ncd_id').val()-tmp_cost);
//alert(data);
setTimeout(message_sent, 2000);
setTimeout(remove_modal_box, 3000);
setTimeout(message_revert, 3500);
$("#saved_messages").load(base_url + 'messages #saved_messages > form');
$("#messages_content").load(base_url + 'messages #messages_content > form');
}
});
return false;
});
Am I doing something wrong?
sico,
There's a number of things you can do to debug/improve the code, chief amongst which is to reduce the number of HTTP requests. With $.get() instead of .load(), it should be possible to use the HTTP responses twice each.
Something like this :
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
dataType: 'json',
success: function(data) {
var creditsPromise, messagesPromise;//vars that allow .when() later.
if(data.gp_id == 80) {
creditsPromise = $.get(base_url + 'ajax/userdata/credits', function(data) {
$('spn_ucredit').html(data);
$('#overlay_credits').html(data);
});
}
else {
creditsPromise = (new $.Deferred()).resolve().promise();
}
messagesPromise = $.get(base_url + 'messages', function(data) {
var $data = $(data);
$("#saved_messages").empty().append($data.find('#saved_messages > form'));
$("#messages_content").empty().append($data.find('#messages_content > form'));
});
$.when(creditsPromise, messagesPromise).done(function() {//fires when both $.get()s have successfully responded
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
});
}
});
return false;
});
This reduces the number of HTTP requests from five to three.
You could further reduce the number of HTTP requests to one, though you would need to write a server-side script to perform everything currently performed by ...ajax/send_message, ...ajax/userdata/credits and ...messages, and json-encode a composite response.
The client-side code could then simplify to something like this:
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: $("#messages form").serialize(),//assumed
dataType: 'json',
success: function(data) {
if(data.gp_id == 80) {
$('#spn_ucredit').html(data.credits);
$('#overlay_credits').html(data.credits);
}
$("#saved_messages").html(data.saved_messages);
$("#messages_content").html(data.messages_content);
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
}
});
return false;
});

Categories