Looping through jsonp object - javascript

I've been looking for a week now and I can't find an answer for this situation.
I request data through jsonp.
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
sync: true,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
In my server side i sent info like this:
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$html = array("Appfeed".$af."" => array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("\r\n",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
array_push($jarr, $html);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
And it returns the data:
jQuery21007744578921701759_1395250905357({
"Appfeed0":
{
"cnty":"MEXICO",
"feed":"text",
"feedId":"201",
"nickname":"chaparra",
"state":"Tamaulipas",
"date":"27\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed1":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"198",
"nickname":"estudiante",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed2":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"197",
"nickname":"el roger",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
But when I try to loop through this in java script It just shows the last feed (Appfeed2). Also in when I print the data in console.log(). It looks like just received the last feed too.
Object {Appfeed2: Object}
1. Appfeed2: Object
1. state: "Tamaulipas"
2. date: "26/02/14"
3. feed: "Ayer fui a sacar mi licencia, sin saber manejar, no hice fila y solo me costo 200 pesos mas. Creo que sere taxista "
4. feedId: "197"
5. nickname: "el roger"
6. cnty: "MEXICO"
7. __proto__: Object
2. __proto__: Object
Any ideas? I was thinking about the way jsonp is returning the data, so I tried with square brackets, with and w/o the get callback, but it fails.
Thank you so much for your help!

You need to make sure that in your PHP code, you are only echoing out the JSON(P) once after the loop finishes. You need to build the array you want then echo it out at the end.
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$jarr["Appfeed".$af] = array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("\r\n",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
P.S. Your AJAX call has a few too many options:
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
success: function(data) {
$.each(data, function(i, v){
console.log(i);
console.log(v);
});
}
});

Related

Get tag, custom taxonomy and attachment data from get_pages function

I currently have some code which retrieves all pages submitted by the currently logged in author using the get_pages function. I am then passing the result to Javascript via Ajax. Everything works as expected, and I'm retrieving the pages that I should be.
My issue is, the object does not have any data for the tags, other custom taxonomies and attachments on this page.
Is there a way to attach this data to the returned object?
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxpages = get_pages($args);
echo json_encode($ajaxpages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
}
});
At this point, each entry will return something like:
ID: 100
comment_count: "0"
comment_status: "open"
filter: "raw"
guid: "https://example.com/?page_id=100"
menu_order: 0
ping_status: "closed"
pinged: ""
post_author: "1"
post_content: "This is the post content"
post_content_filtered: ""
post_date: "2021-06-18 10:00:00"
post_date_gmt: "0000-00-00 00:00:00"
post_excerpt: "This is the excerpt"
post_mime_type: ""
post_modified: "2021-06-18 10:00:00"
post_modified_gmt: "0000-00-00 00:00:00"
post_name: ""
post_parent: 19
post_password: ""
post_status: "pending"
post_title: "Example page"
post_type: "page"
to_ping: ""
I would like it to also include data along the lines of:
tags: "example, test"
myCustomTaxonomy: "extra information, more data"
attachments: "https://example.com/wp-content/uploads/2021/06/myImage.png"
Is this possible?
In case it's useful, this is the solution I came up with. It certainly may not be efficient but it appears to suit my purposes at least.
What I ended up doing was populating a select list with each of the pages found in the first AJAX call. Selecting a page in this list then calls the second function which gets the various extra metadata for that page.
functions.php:
function get_ajax_pages()
{
// Query Arguments
$args = array(
'authors' => $author,
'post_type' => 'page',
'post_status' => array('publish', 'pending'),
'hierarchical' => 0
);
// The Query
$ajaxPages = get_pages($args);
echo json_encode($ajaxPages);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_pages', 'get_ajax_pages');
add_action('wp_ajax_nopriv_get_ajax_pages', 'get_ajax_pages');
function get_ajax_meta()
{
$editId = $_POST['editId'];
$meta = [];
$editTags = get_the_tags($editId);
$editCustomTaxonomy1 = get_the_terms($editId, 'CustomTaxonomy1');
$editCustomTaxonomy2 = get_the_terms($editId, 'CustomTaxonomy2');
$media = get_attached_media('', $editId);
array_push($meta, (object)[
'tags' => $editTags,
'customTaxonomy1' => $customTaxonomy1,
'customTaxonomy1' => $customTaxonomy2,
'media' => $media
]);
echo json_encode($meta);
exit;
}
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_meta', 'get_ajax_meta');
add_action('wp_ajax_nopriv_get_ajax_meta', 'get_ajax_meta');
Javascript:
var adminAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
// the list of pages by the current author
var pageList = [];
// get an array of the current author's pages
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { action: 'get_ajax_pages' },
success: function (response) {
pageList = response;
// populate the dropdown with the pages
if (pageList.length > 0) {
for (var i = 0; i < pageList.length; i++) {
$("select[name=edit-page]").append("<option value='" + pageList[i].ID + "'>" + pageList[i].post_title + "</option>");
}
}
}
});
$("body").on("change", "select[name=edit-page]", function () {
editId = $(this).val();
// get the meta information of the selected page (tags, custom taxonomies, attached files)
$.ajax({
type: 'POST',
url: adminAjaxUrl,
dataType: "json",
data: { "editId": editId, action: "get_ajax_meta" },
success: function (response) {
pageMeta = response;
// get the tags
console.log(pageMeta[0].tags[i].name)
// get custom taxonomy 1 data
console.log(pageMeta[0].customTaxonomy1[i].name)
// get custom taxonomy 2 data
console.log(pageMeta[0].customTaxonomy2[i].name)
// get attached file data
if (Object.keys(pageMeta[0].media).length > 0) {
for (var i = 0; i < Object.keys(pageMeta[0].media).length; i++) {
console.log(pageMeta[0].media[Object.keys(pageMeta[i].media)[0]]);
}
}
}
});
});

cannot receive json from server through php

i cannot get the json from php on sever
the javascript code is:
$.ajax({
type: "POST",
url: "doingSQL.php",
data: label,
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
the job of doingSQL.php is selecting bookName from SQL database and convert the data to json. it look like this:
/* the server connecting code is omitted */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$label = $_POST["label"];
}
$sql = "SELECT * FROM book WHERE ower = '". $label."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Arr = array("id" => $row["book_id"],
"bookName" => $row["bookName"]);
$bookDetail[] = array( "book".$i => $Arr);
}}
}
mysqli_close($conn);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json
but the result i got in the html console is "[ ]" or array[0].
the json is valid json format, it is look like:
{
"mybook":[
{
"book0":{
"id":"0",
"bookName":"bookA"
}
},
{
"book1":{
"id":"1",
"bookName":"bookB"
}
}
]
}
however, if the code is outside the SQL connection in php. the json returning will success.
it is look like:
/* the server connecting code is omitted */
mysqli_close($conn);
// if outside the SQL connection
$ArrA = array("id" => "0", "bookName" => "bookA");
$ArrB = array("id" => "1", "bookName" => "bookB");
$bookDetail[] = array( "book0" => $ArrA);
$bookDetail[] = array( "book0" => $ArrB);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json success
any idea?
Just pass your ajax data as :
data: {label:label}
The data property of the ajax settings can be type of PlainObject or String or Array. For more reference see this http://api.jquery.com/jquery.ajax.
So your javascript code would be like this :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label},
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
You need to pass the label value in a variable. Now since on the PHP page you are using $_POST['label'], so pass the variable like this :
data: {label: label},
So your complete ajax code would look like :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label}, // changed here
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});

Getting error while using each loop under ajax

When i am trying each loop under Ajax call, i am getting error as:
TypeError: invalid 'in' operand e
Below is my Ajax call code
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue['ID'] + '">'+ arrValue['CenterName'] +'</option>');
});
}
});
Response which i am getting back from server is :
Array (
[0] => Array
(
[ID] => 4
[CenterName] => test2
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
[1] => Array
(
[ID] => 8
[CenterName] => test21
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
)
I am using PHP as backend, whose code is :
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
print_r($arrCenter[0]);
die();
Use json_encode() in PHP to return response. And your JS code should be like:
PHP:
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();
JQuery:
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
dataType: 'json',
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue.ID + '">'+ arrValue.CenterName +'</option>');
});
}
});
Try to echo out your object using json_encode instead:
<?php
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();

Why is this object parse returning undefined?

Sorry about this nth version of object grabbing, but I just don't see it.
I am returning a JSON object from a db to my Javascript, and I see the returned object (below) just fine in the console. But the moment I attempt to put a child in the console I get "undefined". I should be able to see result.bills, or result["bills"] and just to be sure I've tried result[0].bills, etc. all of which are undefined. This seems so basic but I can't see why I can't make this work.
My PHP (after db stuff):
if ($result) {
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[bills] = $r;
}
echo json_encode($rows);
} else {
echo "Unknown Error";
}
//all done
My AJAX:
$.ajax({
type: 'get',
url: 'GetBills.php',
success: function(result) {
var thebills = result.bills;
console.log(thebills);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
and I get back:
{
"bills": {
"ID": "3",
"State": "MD",
"Title": "Maryland Android Project Act (S.1196 H.2057)",
"HouseNum": "H 2057",
"SenateNum": "",
"Session": "189th"
}
}
You're getting undefined because jQuery doesn't know that it's actually receiving JSON back. It is detected and automatically parsed if you send JSON headers with your php file, OR if you set the dataType to 'json'.
So, currently you're accessing a string:
var result = '{"bills":{"ID":"3","State":"MD","Title":"Maryland Android Project Act (S.1196 H.2057)","HouseNum":"H 2057","SenateNum":"","Session":"189th"}}'
BUT you're attempting to access STRING functions (specifically bills which is undefined).
If you choose to not change the dataType or add headers, you could also do result = JSON.parse(result) which would also give you the same thing.
Doing one of the three above solutions will give you the object you're looking for, and access its children:
//Javascript
result = JSON.parse(result);
//In Console
Object {bills: Object}
bills:
ObjectHouseNum: "H 2057"
ID: "3"
SenateNum: ""
Session: "189th"
State: "MD"
Title: "Maryland Android Project Act (S.1196 H.2057)"
__proto__: Object
__proto__: Object
add dataType to your ajax request object:
...
type: 'get',
url: 'GetBills.php',
dataType: 'json',
...
You can either force the content type to be JSON in your AJAX call, or even better, set the correct content type in your PHP and let jQuery detect it automatically. Imagine accessing your data from another tool different from jQuery, e.g. a mobile app or some REST-tool. If you set your Content Type properly, most tools/languages will detect it automatically and you don't have to parse it manually over and over again.
// Set the content type correctly
header('Content-Type: application/json');
if ($result) {
$rows = array();
while ($r = mysqli_fetch_assoc($result))
{
$rows[] = $r; // Notice how to append the row to the array
}
http_response_code(200); // PHP >= 5.4
echo json_encode([
'success' => true,
'bills' => $rows
]);
}
else {
http_response_code(500); // Your status code here
echo json_encode([
'success' => false,
'message' => 'Something went wrong',
]);
}
And your JavaScript:
$.ajax({
type: 'get',
url: 'GetBills.php',
success: function(result) {
var thebills = result.bills;
console.log(thebills);
},
error: function(response) {
console.log('Error', response.message);
}
});

Send multidimentional array from JQuery AJAX to PHP

i want to send a multidimensional array to PHP from JQuery AJAX, but it is receiving in PHP like this
Array
(
[recordid] => 38
[locations] => [object Object],[object Object]
)
i must be doing some stupid mistake. here is the code.
it gets records from a table and send to PHP
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
locations = locations.toString();
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: { recordid: recordid,locations:locations },
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
and this is the PHP function where i am receiving the data:
function saveSearchedLocations(){
print_r($_POST);
}
Use JSON.stringify() instead of toString() like so:
Change your AJAX call to this:
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
ajaxData = { recordid : recordid,locations : locations }
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: JSON.stringify(ajaxData),
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
JSON.stringify() converts your array to an actual json string as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.
Take this answer as a reference:
I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.
jQuery:
var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);
$.post('serive.php', { DTO: JSON.stringify(selectedData) },
function(data){ /* handle response, */ });
service.php:
header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');
$foo = json_decode($_POST['DTO']);
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data
echo json_encode($arr);
This should get you started. In your ajax reponse, alert(data.a) would be alerting "1"
sendAjax = function() {
var data = {
foo: 123,
bar: 456,
rows: [{
column1: 'hello',
column2: 'hola',
column3: 'bonjour',
}, {
column1: 'goodbye',
column2: 'hasta luego',
column3: 'au revoir',
}, ],
test1: {
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
}
When the button is clicked, the following structured data shows up in PHP's $_POST variable:
Array
(
[foo] => 123[bar] => 456[rows] => Array(
[0] => Array(
[column1] => hello[column2] => hola[column3] => bonjour
)
[1] => Array(
[column1] => goodbye[column2] => hasta luego[column3] => au revoir
)
)
[test1] => Array(
[test2] => Array(
[test3] => baz
)
)
)
This will only work with jQuery 1.4.0+. Otherwise jQuery simply calls .toString() on the nested array at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object
here is the link u can check here
https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/
Put your data in a form and send form data with serializeArray()

Categories

Resources