Looping through AJAX and callbacks in jquery - javascript

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
}

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

Difficulties using AJAX to pass input value to controller

I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}

jquery ajax always results in 'error' even when it works

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

Running AJAX to retrieve logged in users is returning undefined

Hi so I am in the process of learning AJAX and have decided for a better UX on my admin system to have users online, messages, tasks updated and so on updated every 30 seconds or so depending on the load (in the code i have it set to 5 seconds for testing purposes).
The PHP file works fine and outputs the following JSON:
[{"username":"columkelly","time":"2013-12-18 14:13:55"}]
PHP
header('Content-Type: application/json');
if($_GET['function'] === "users_online"){ users_online(); }
function users_online(){
$result=mysql_query("SELECT * FROM sessions");
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
}
The problem comes when I try to output the users that are online... The console log shows that it has picked it up but I am unable to get it to work with the users_online function with the callback. Here is the AJAX:
AJAX
var timer, delay = 5000;
timer = setInterval(function(){
val = $(this).serialize();
$(document).ready(function () {
$.when(
$.ajax({
url: "ajax.php?function=users_online",
dataType: "json",
type: "GET",
data: val,
success: function(data)
{
console.log(data);
}
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})
).then(function (users_online, images) {
$("#users_online").html('');
$.each(users_online, function(data){
$('#users_online').html(data.username +':' + data.time);
}
),
$("#dvImages").html('');
random = Math.floor((Math.random()*3)+1);
$.each(images[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == random) return false;
})
});
});
}, delay);
What i end up getting is 1-4 images appearing from the flicker api (used this as a test base) and undefined:undefined. I know it has to have something to do with the success (i tried putting them into a javascript array but that did not work) and the function to grab the data:
function (users_online, images) {
$("#users_online").html('');
$.each(users_online, function(data){
$('#users_online').html(data.username +':' + data.time);
}
)
Thanks for all the help so far guys. I have searched far and wide but am unable to get anything to work with this.
Colum
EDIT:
This is the finished code that worked:
var timer, delay = 5000;
var users_online = [];
timer = setInterval(function(){
val = $(this).serialize();
$(document).ready(function () {
$.when(
$.ajax({
url: "ajax.php?function=users_online",
dataType: "json",
type: "GET",
data: val,
success: function(data)
{
console.log(data);
users_online = data; // Now call and loop through users_online wherever you need
}
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})
).then(function (users_online, images) {
$("#users_online").html('');
$.each(users_online[0], function (i, item) {
$('#users_online').html(item.username +':' + item.time);
}
),
$("#dvImages").html('');
random = Math.floor((Math.random()*3)+1);
$.each(images[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == random) return false;
})
});
});
}, delay);
Although people would argue how optimal this solution is, it will fix the issue granted you don't overwrite it:
var timer, delay = 5000;
var global_users_online = []; // create a global array
timer = setInterval(function(){
val = $(this).serialize();
$(document).ready(function () {
$.when(
$.ajax({
url: "ajax.php?function=users_online",
dataType: "json",
type: "GET",
data: val,
success: function(data)
{
console.log(data);
global_users_online = data; // Now call and loop through global_users_online wherever you need
}
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})
)

JSONP print all data

So I have a problem with JSONP. I finally managed to load my JSONP data into my html file, but I can't seem to print all the data. I already tried the for loop and $.each, but no succes.
JSONP in php file
<?php echo $_GET["callback"] ?> (
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"indexpit.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"indexso.html"
}
);
Script for calling the JSONP
<script type="text/javascript">
$.ajax({
type: 'GET',
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
url: 'http://mllsdemode.be/Ex-cache/home.php',
success: function(json) {
for (var key in json) {
var el = document.getElementById("home");
el.innerHTML = "<li><div class='dsc'>" + json.expo + "<br><em>" + json.datum + "</em></div></li>";
}
},
error: function() { alert("Error reading jsonP file"); }
});
</script>
Anyone know what I should do to print all the info? At this moment I only get the data for pit, not the data for Space Odessy 2.0.
The JSONP should be:
<?php echo $_GET["callback"] ?> (
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"indexpit.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"indexso.html"
}
]
);
You were missing the [] around the array, so you were passing two arguments to the callback function instead of one array.
After that, your loop is wrong. It's processing a single object, not an array, and replacing the home inner HTML each time instead of appending.
success: function(json) {
var $home = $("#home");
$home.empty();
$.each(json, function(i, el) {
$home.append("<li><div class='dsc'>" + el.expo + "<br><em>" + el.datum + "</em></div></li>");
});
}
<?php echo $_GET["callback"] ?> ([
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"indexpit.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"indexso.html"
}]);
.
$(json).each(function (index, item) {
var el = document.getElementById("home");
el.innerHTML += ("<li><div class='dsc'>" + item.expo + "<br><em>" + item.datum + "</em></div></li>");
});
Try this.
json = $.parseJSON(json);
now you can loop through it like following :
for(i=0; i<json.length; i++)
{
alert(json[i].expo);
}
Your Array must be in this format [{},{}];
Thanks

Categories