I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}
Related
Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.
I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here
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);
}
);
I'm currently doing an AJAX call with jquery and callback functions to retrieve a result outside of the AJAX call and I am having trouble in attempting to use a loop to printout more data from my json file (ticker.json) provided here:
{
"test": {
"msgOne": [
"Remote One",
"Remote Two",
"Remote Three"
],
"msgTwo": "Remote2",
"msgThree": "Remote3"
}
}
My code is also below:
<html>
<head>
<title>Weather Data for Emergency Models</title>
<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
<script Language="JavaScript">
function hmm(callback) {
$.ajax({
url : 'ticker.json', // ___ |I want to loop this
dataType: 'json', // | |index as a variable
success: function(response) { // v
result = response['test']['msgOne'][2];
callback(result);
}
});
}
hmm(function(result) {
document.write(result); //currently outputs as "Remote Three"
});
</script>
</body>
</html>
The main problem is that I want to continue as asynchronous using the callback functions and loop through the "msgOne" array in the json file and print out all three results to the webpage sequentially. I have tried introducing a for-loop in multiple places previously, but I keep getting errors. I realize there are other ways to do this, but under the wanted conditions (asynchronous & callback functions because I want to eventually apply this to jsonp for json files found on multiple websites on a list), is there a way to do this? I ultimately want to modify the given code to deal with arrays and more complex code.
Try this -
do this in your success
success: function(response) {
callback(response);
}
and in your function
hmm(function(result) {
$.each(result.test.msgOne,function(i,v){
document.write(v);
});
});
Try this
Assuming response['test']['msgOne'] is an array
success: function(response) {
$.each(response['test']['msgOne'], callback);
}
hmm(function(i, result) {
document.write(result); //currently outputs as "Remote Three"
});
$.ajax({
url : 'ticker.json', // ___ |I want to loop this
dataType: 'json', // | |index as a variable
success: function(response) { // v
var result = response['test']['msgOne'];
$.each(result,callback ).
}
});
function callback(index ,data){
document.write(data);
}
This helped me iterate through div rows, pull their data-id atribute and retrieve data from an ajax call using that data id. There happened to be 40+ ajax calls to itterate through. I have to leave them async true but watterfall the calls so as not to overload the server. I also used PHP to retrieve cached data and converted the PHP cached array to a javascript object:
public static function load_footer_js_css() {
$screen = get_current_screen();
$whitelist = array('post','page');
if(!isset($screen) || !in_array($screen->post_type , $whitelist )) {
return;
}
$transient = get_transient( 'inbound_ga_post_list_cache' );
$js_array = json_encode($transient);
?>
<script type="text/javascript">
<?php
echo "var cache = JSON.parse('". $js_array . "');\n";
?>
function inbound_ga_listings_lookup( cache, post_ids, i , callback , response ) {
if (!post_ids[i]){
return true;
}
if (typeof response == 'object' && response ) {
jQuery('.td-col-impressions[data-post-id="' + post_id + '"]').text(response['impressions']['current']['90']);
jQuery('.td-col-visitors[data-post-id="' + post_id + '"]').text(response['visitors']['current']['90']);
jQuery('.td-col-actions[data-post-id="' + post_id + '"]').text(response['actions']['current']['90']);
}
if (i == 0) {
post_id = post_ids[0];
i++;
} else {
post_id = post_ids[i];
i++;
}
if (typeof cache[post_id] != 'undefined') {
jQuery( '.td-col-impressions[data-post-id="' + post_id + '"]').text( cache[post_id].impressions.current['<?php echo self::$range; ?>'] );
jQuery( '.td-col-visitors[data-post-id="' + post_id + '"]').text(cache[post_id].visitors.current['<?php echo self::$range; ?>']);
jQuery( '.td-col-actions[data-post-id="' + post_id + '"]').text(cache[post_id].actions.current['<?php echo self::$range; ?>']);
} else {
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
action: 'inbound_load_ga_stats',
post_id: post_id
},
dataType: 'json',
async: true,
timeout: 10000,
success: function (response) {
callback(cache, post_ids, i, callback , response);
},
error: function (request, status, err) {
response['totals'] = [];
response['totals']['impressions'] = 0;
response['totals']['visitors'] = 0;
response['totals']['actions'] = 0;
callback(cache, post_ids, i, callback , response);
}
});
}
}
jQuery(document).ready( function($) {
var post_ids = [];
var i = 0
jQuery( jQuery('.td-col-impressions').get() ).each( function( $ ) {
var post_id = jQuery(this).attr('data-post-id');
post_ids[i] = post_id;
i++;
});
inbound_ga_listings_lookup( cache, post_ids, 0 , inbound_ga_listings_lookup , null );
});
</script>
<?php
}
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;
});