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
Related
I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).
I have this php
include_once($preUrl . "openDatabase.php");
$sql = 'SELECT * FROM dish';
$query = mysqli_query($con,$sql);
$nRows = mysqli_num_rows($query);
if($nRows > 0){
$dishes = array();
while($row = $query->fetch_assoc()) {
$dishes[] = $row;
}
}else{
$dishes = "cyke";
}
echo json_encode($dishes , JSON_FORCE_OBJECT);
and this ajax (in framework7)
myApp.onPageInit('dailyMenu',function() {
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.log(data);
});
});
What i get in the ajax data is
{"0":{"idC":"2","title":"helloWorld1","subtitle":"hellsubWorld","price":"16.5","img":"img/testeImg.jpg","soldout":"0"},"1":{"idC":"3","title":"helloworld2","subtitle":"hellosubWorld2","price":"20.5","img":"img/testeImg.jpg","soldout":"1"}}
I already tried data.[0]; data.['0']; data.0; data0 when i use data["0"] just gives me the '{'.
I want to acess the title and the rest inside that 0. to do a cicle for where i will print multiple divs where i only change the array position in a html page.
Exemple
for(...){
innerhtml += <div clas="">
<div class""> data(position i).title </div>
<div> data(position i) subtitle</div>
</div>
}
try this one (after callback add type: json)
$$.post('url', {}, function (data) {
var obj = JSON.parse(data);
console.log(obj);
alert(obj["1"].title);
});
or maybe you can use JSON.parse(data);
Since you are receiving a json data as response, you should use this:
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.dir(data);
},'json');
Pay attention to },'json');on end of the code, now the $$.post is reading the response as a JSON.
If you aren't doing any update to data base, you could use:
$$.getJSON('http://theIP/eatsServer/dailyMenu.php',{}, function (data) {
console.dir(data);
});
This is the way with $$.ajax:
$$.ajax({
url: "url_here",
method: "POST",
dataType:"json",
data: {},
success: function(r){
// response r.
}, error: function(error){
//error
}
});
I have following code to execute a query on the Database. it returns a list of objects, one for each row result from the query:
function getcontent()
{
var data = {
"id": "<?php echo $stournid; ?>"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(response) {
//**************************** HERE!!!!
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
return false;
}
The response.php file contains this:
<?php
$id = "";
if (is_ajax()) {
if (isset($_POST["id"]) && !empty($_POST["id"])) { //Checks if action value exists
$id = $_POST["id"];
querydata($id);
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function querydata($id){
require_once('dbconfig.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_error) {
die('Errore di connessione (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$myArray = array();
if ($games = $mysqli->query("my query is here.. pretty long but working correctly.")){
while($row = $games->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
?>
here is the returned data:
[{"id":"1435","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|6|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":"57","id_gamer2":"55","called":"2","callreadytime":"13:08:07","starttime":"22:12:19","endtime":"22:20:03","id_winner":"57","id_loser":"55","playsequence":"00001","tabsequence":"A00010001","dest_winner":"B00010001-1","dest_loser":"C00010001-1","connectionname":"","p1name":"Calamante Lorenzo","p2name":"Badiali Maurizio"},
{"id":"1436","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|4|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":null,"id_gamer2":null,"called":"0","callreadytime":"00:00:00","starttime":"00:00:00","endtime":"00:00:00","id_winner":"0","id_loser":"0","playsequence":"00015","tabsequence":"W00010001","dest_winner":"","dest_loser":"1","connectionname":"","p1name":null,"p2name":null}]
What I would like to do, is in the Javascript, go through all the returned lines one by one and updated some div's accordingly. I am having difficulties on how to iterate the returned lines.
Any help appreciated.
Thanks
success: function(response) {
// redponse is an array of objects (so lets loop through it using forEach)
response.forEach(function(row) {
// row is a row (object) from the array
var id = row.id;
var location = row.location;
var date = row.date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
Note: Array.prototype.forEach is like a loop but better. Check the docs.
Don't want to use forEach?
If you don't want to use forEach, you can use an old for like this:
success: function(response) {
// using for is not very pretty, hein?
for(var i = 0; i < response.length; i++) {
// response[i] is the i-th row of the array
var id = response[i].id;
var location = response[i].location;
var date = response[i].date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.
this is my ajax function
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'json',
success: function(msg){
//var content = data.substr(0, data.indexOf('<'));
populateMessages(msg);
},
error: function(){
alert("ERROR");
}
});
}
and this is the relevant code for the php file
$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['user_name'];
$message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
// is that not valid json notation???
}
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);
UPDATE:
Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'html',
success:function(msg){
var content = msg.substr(0, msg.indexOf('<'));
msg = JSON.parse(content);
populateMessages(msg);
},
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
alert(xhr);
}
});
}
function populateMessages(data){
var out = '';
var json;
for (var i in data){
var my_string = JSON.stringify(data[i],null,0);
json = JSON.parse(my_string);
alert(json.Hash);
out += i + ': ' + my_string + '\n';
}
alert(out);
}
You need to set the header as json type before your echo in PHP:
header('Content-Type: application/json');
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
}