At start of page load I get all my products (posts) with a database query and print the first results on the page like this:
$posts_from_query = $wpdb->get_results($SQL, ARRAY_A);
$output = $CORE->create_output($posts_from_query, 1);
<div id="currentPageSearchResults"><?php echo $output ; ?></div>
Then I send it to a JS init function when the page is fully loaded:
initSearchJavascript(<?php echo json_encode($posts_from_query);?>);
And here is a simplified version of the JS file:
var postsFromCurrentQuery;
function initSearchJavascript(postsFromQueryInit){
postsFromCurrentQuery = postsFromQueryInit;
}
When alerting postsFromCurrentQuery I get [object Object],[object Object],... 258 times since I have 258 products, all good so far.
Now when I click on page 2 (I show 50 products per page) I call a JS function that through an AJAX call sends postsFromCurrentQuery back to PHP to create the output for page 2:
jQuery.ajax({
type: "POST",
url: ajax_site_url,
dataType: 'json',
data: {
action: "change_search_page",
clickedPage: currentPage,
postsFromCurrentQuery: postsFromCurrentQuery,
},
});
And on the PHP side I unpack it like this:
case "change_search_page": {
// Unpack variables
$postsFromCurrentQuery = $_POST['postsFromCurrentQuery'];
$clickedPage = $_POST['clickedPage'];
// Retrieve output
$output = $CORE->create_output($postsFromCurrentQuery, $clickedPage);
// Send back to JS for printing on page
header('Content-type: application/json; charset=utf-8');
die(json_encode(array(
"status" => "ok",
"output" => $output,
"count" => count($postsFromCurrentQuery),
)));
} break;
Problem
When I print the length of postsFromCurrentQuery before the AJAX call it is 258 as expected. But when I print it after (or in the PHP) it instead says 231. For some reason information is lost when sending from JS to PHP via AJAX.
What I tried
I can see that some information on the last (231th) product is missing and some is not. It shows the correct title, image etc but then fails on location which comes later in the string. This makes me think that there is some limit to how much data can be sent over AJAX? It has been working fine when I had 20 products or so.
I also tried to make it into a string with JSON.stringify before sending it over AJAX and then json_decode on the PHP side. This fails however for some reason. It seems like I have a JSON structure with nested {} which makes it fail, since it works if I remove the attribute with the extra {}.
Questions
Is there a limit to how much data AJAX can handle?
If not, why is my approach failing?
i am trying in pull my data from mySQL and convert it to a format I can then pass to google.maps API. I am thinking mySQL -> php -> javascript -> google.maps makes the most sense but am deffinitly open to other suggestions.
So far I have connected to and successfully queried my data into an array
<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');
//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}
//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";
if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}
//initialize an array to store data
$rows = array();
while ($data = $results->fetch_assoc()) {
$rows[] = $data;
echo "<br><br>Loop rotation: ";
var_dump($data);
}
echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>
Now I just need to convert this data into something usable I can pass to google.maps.
Before I was pulling JSON from a text file, which worked, but I want to flexibility and stability of a database. It was easy to parse into and array of Javascript Objects. Then I could just call the index and the property that I needed as you can see from this function I was using.
function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){
//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};
//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}
Thank you for any light you can help shed on my issue.
It sounds like you already found your answer but I'll post for completeness.
Simply change your the var_dump($rows) line to json_encode($rows).
Read more about json_encode in the php docs.
You probably want to have two php files:
api.php file that emits Content-type: application/json
index.php file that emits Content-type: text/html and calls api.php
On the index page, you can make an AJAX call to your API endpoint and then use JSON.parse(response).
I've got a PHP array...
<?php
$tweets = array(
'1' => array(
"title" => "title",
"challenge" => "challenge",
"answer" => "answer",
"type" => "type",
"class" => "class",
),
/* .... */
)
?>
That I need to go fetch data from using AJAX and for the life of me, I can't get the data that I need.
What I've got right now is...
var challenge = 10;
var tweets = <?php echo json_encode($tweets); ?>;
$('.cur_race_title').html(tweets[challenge]['title']);
$('.cur_race_challenge').html(tweets[challenge]['challenge']).addClass(tweets[challenge]['class']);
$('.cur_race_answer').html(tweets[challenge]['answer']);
$('.tweet-submission').addClass(tweets[challenge]['type']);
(Note: the challenge number is a variable that changes)
Using PHP's json_encode, I get an array of all of the values in the PHP file (which is included earlier on the file) and then use the challenge ID to populate the data.
The downside is that this shows the data for the entire array - I'd like to only show the data for the single challenge defined by the ID above.
Any help would be greatly appreciated.
Thanks!
I wouldn't recommend generating JavaScript variables with PHP tags.
Use: http://api.jquery.com/jquery.getjson/
$.getJSON("myurl.php", function(JSON){
//do something
});
PHP Side: Returning JSON from PHP to JavaScript?
header('Content-type: application/json');
echo json_encode( $myArray[ $myId ] );
The console.log on the first line returns a large array of values. And the Console.log(Data) at the end is displaying the plain text response from the server, but the $_POST variable on the server is empty.
The JS:
console.log(topost);
$.post(url,topost,function ( data ){
console.log(data);
});
The console.log(topost);
["DiscontentDisciple","illuminatedwax","S2S2S2S2S2","bechus","syncretic","davidreiss666","Skuld","soupyhands","AutoModerator","imluckytometyou","Lord_Arioc","IIdsandsII","Kylnas","alanpugh","langis_on","TheBigDickedBandit","long_wang_big_balls","arnoldlol","SBringer","ExoticCarMan","HaidiMontag","10FootPenis","SupriseRape","AManHasSpoken","ComedicCounterpart","Suddenly_Something","agenthex","GenerallySpecific","WelcomeToTarget","brainswho","Gooflactus","alcakd","Stingray88","TossTime","yolfer","biskits1","Evarg","phishroom","BuccoBruce","LookingForAlaska","getDense","lewisthemusician","tmotom","tha_ape","spankymuffin","Dashing_Pony","RuafaolGaiscioch","BeaverManiac","Careless_Con","Texas_","i_am_sad","The_helpful_idiot","Kon-chezz","bombdailer","frezik","Galifreyan2012","metalshadow","lightpollutionguy","b3mus3d","crazdave","merpes","naked_guy_says","GoodGuyAnusDestroyer","Bibliophobia","Internet_Lynch_Mob","photo","adkoe","ZeitTaicho","movie_man","iamkush","sired_tick","jyjjy","WhipIash","rred82","E_Diddyyy","CYBERPENISATTACK","MJYTR","TheBaconHasLanded","quarktheduck","heroic_trig","sleevieb","Burrow","myhousemateisabitch","promethephile","msm008","daskrip","jonnie123","Legendman3","Makes_Sad_Faces","anxiousalpaca","crankykong","IamDa5id","CocoSavege","iamsofuckedseriously","EvTheSmev","Briscotti","MarkieMarkl","CornishCucumber","BearsStillSuck","government_shill","Ihaveafatcat","gh5046","Sayum","henryponco","bolaxao","mrbriancomputer","PsychicNinja_","poopslooshed","REDDIT-","IVI4tt","spleendor","ngmcs8203","deadbeatbum","vegibowl","workingalot","Black_Apalachi","Incongruity7","rdeari1","ihahp","im_0n_toilet","Andynack","photokeith","Alpha17x","5NL70","AtticusFinch1962","clayvn","anonymau5","coplay","gnarbucketz","BukkRogerrs","teusz16","digital_evolution","theredcheck","empw","OrigamiRock","lumptoast","alphanovember","Nahtanos","som13","rstyknf","jmadden287","patchworkpavements","Computer-Blue","Miltage","bwaxxlo","aussiegolfer","coaltown","ThePickleMan","mpm96","Ilyanep","merreborn","Theemuts","wufoo2","thunderbar","blindado9","ntorotn","CatrickSwayze","HankSinatra","redditbots","Word_Inventor","catbeef","SoLongSidekick","Elefaze","Jinksywinksy","Mordy2011","thatusernameisal","Kanin","inthekeyofbflat","buckygrad","DeaD_bAU5","Toe_Fat","wsright987","Pachi2Sexy","woprdotmil","AmmoBradley","pokelord13","kroutonz","mattoftheD","WipeMyAssWith100s","ShuckBeam","dookyface","XLR8Sam","your_backpack"]
The response I get:
{"postyn":"YES"}
The PHP:
foreach ($_POST as $key => $value){
$data[$key] = $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$data['postyn'] = 'YES';
}
I don't understand why the $_POST variable is empty?
$.post(url,{**NAMEME**: topost} ,function ( data ){
console.log(data);
});
You're trying to pass post data as an array it appears. It needs to either be a string or an object.
Description of data property for jQuery.post():
data A map or string that is sent to the server with the request.
From http://api.jquery.com/jQuery.post/
My guess here based on what you're trying to do is an object. Which brings up the next problem, both an object and your PHP script are expecting both keys and values, but you're only passing values.
You data object should look something like:
topost = {
somekey1: "DiscontentDisciple",
somekey2: "illuminatedwax",
somekey3: "S2S2S2S2S2",
// etc etc etc
};