Posting Data to PHP with Axios - javascript

I am creating a Vue app where I am posting to PHP using Axios. So what I have is:
methods: {
onSubmit () {
axios.post('/wp-content/themes/bones/library/jobsResponse.php',{region: Chicago, jobType: Direct Hire}, {headers: {'X-Requested-With': 'XMLHttpRequest', 'Content-type': 'application/x-www-form-urlencoded'}})
.then(function(response){
console.log(response)
})
.catch(function(error){console.log(error)})
},
}
What that method is doing is when the onSubmit function is ran it will use Axios to POST to a PHP file I created named jobsResponse.php. The data it is posting is 'region: Chicago Region, jobType: Direct Hire'.
Then in that jobsResponse.php PHP file I have:
<?php
$_POST = json_decode(file_get_contents('php://input'), true);
$region = $_POST['region'];
$jobType = $_POST['jobType'];
echo $region;
echo $jobType;
echo ' this is the posted data content';
?>
So that is getting the posted data from Vue using Axios. In Axios I am running a console.log of the response and when I check the console log it shows me the data I posted to the jobsResponse.php
As you can see in the image above the data from my Vue app was posted to the jobsResponse.php file. So that's all fine and well. What I need to do now is take that data I posted to the jobsResponse.php file and use it in my Vue app.
So currently in my Vue app I am recieving a JSON object using PHP like so:
<?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded,externalCategoryID,employmentType,customText12', null, 200, '-dateAdded');?>
What I want to do is use the posted data from Axios in that PHP query. So I would need to take that posted data and insert into that PHP in some fashion like:
<?php echo getBhQuery('search','JobOrder','isOpen:true AND customText12:"'.$region.'"','id,title,categories,dateAdded,externalCategoryID,employmentType,customText12'); ?>
Adding the $region variable to the PHP query would filter the JSON object to only pull back job posts that have the region of whatever that variable is set to.
So I have the needed data posting, which is good. I'm just not sure how to take that data and use it to generate a new JSON object on the fly, like ajaxing it.

Well, $_POST is a superglobal, so I wouldn't be overwriting it as they are handled by PHP automatically and best left alone.
Like a comment mentioned, $post = file_get_contents('php://input') ?? $_POST; will take the incoming POST request and assign it to the variable $post. Then once you've parsed it: $post = json_decode($post, true); this will parse the JSON string into an associated array.
Then get the variables like you mention, $region and $jobType.
You'd then plug these into your database query, or if you are not making this production and can have fixed data: have a static text file or save a list of jobs to a variable.
// get the incoming POST data
$post = file_get_contents('php://input') ?? $_POST;
// decode the JSON data
$post = json_decode($post, true);
// assign the needed data from the POST object
$region = $post['region'];
$jobType = $post['jobType'];
// define how you want to filter the data
function $sortJobs($job) use ($region, $jobType)
{
return ($job['region'] == $region) && ($job['type'] == $jobType);
}
// get your jobs data
$jobs = [[ 'type' => 'x', 'region' => 'minneapolis', 'name' => 'developer'], ['type' => 'y', 'region' => 'chicago', 'name' => 'secretary']];
// filter the jobs data
$filteredJobs = array_filter($jobs, "sortJobs");
// return the filtered data
http_response_code(200);
echo json_encode($filteredJobs);

Related

Trying to pass my WordPress database result to JavaScript and then back through PHP

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?

Pull mySQL data via PHP into an array of Javascript objects

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).

How to parse sql result?

End my sorrow.
I make an ajax request to this file.
I want to get all the posts from database. Then stylise these posts and display it to the user.
But I couldn't figure out how to parse these from js.
...
$result = $conn->query($sql);
//Iterate the rows
while($row = $result->fetch_assoc())
{
//todo
}
...
//jsfile
...
var response = this.responseText;
//get the response but how to parse ?
From your Post, you sound like you want to send some Data obtained from your Database Transactions to the Requesting AJAX Script, right? If that is the case; you may have to do all the usual Processing of your DB Data and (if necessary) build them up as an Array or Object within your PHP File. Afterwards, you encode the resulting Data to JSON using json_encode() and then lastly push the JSON-Encoded Data back to the requesting AJAX Script. To illustrate; here (below) is a Mock example using bits & pieces of the Code you posted:
<?php
// PERFORM SOME DATABASE TRANSACTIONS....
$result = $conn->query($sql);
// IF YOU NEED TO BUILD-UP A SPECIAL DATA STRUCTURE TO MEET WITH
// THE NEEDS OF YOUR APP. YOU MIGHT DO THAT HERE.
// WE CREATE AN ARBITRARY ARRAY: $payload TO HOLD THE ARBITRARY DATA...
$payload = [];
// LOOP THROUGH THE RETURNED RESULT-SET / ROWS OF DATA
while($row = $result->fetch_assoc()) {
// WE PRETEND FOR NOW THAT WE NEED CERTAIN VALUES FOR THE APP
// THAT WILL BE CONSUMED BY THE REQUESTING AJAX SCRIPT
// SO WE BUILD IT HERE:
$tempData = []; //<== TEMPORARY ARRAY TO HOLD A COLLECTION
$tempData[] = $row['firs_name'];
$tempData[] = $row['last_name'];
$tempData[] = $row['address'];
$tempData[] = $row['email'];
$tempData[] = $row['avatar'];
$tempData[] = $row['telephone'];
// NOW PUSH THE COLLECTION OF RELEVANT DATA GATHERED
// FROM THE ITERATION INTO THE PAYLOAD VARIABLE: $payload
$payload[] = $tempData;
}
// OK: WE HAVE OUR PAYLOAD, READY TO BE SENT BACK AS JSON...
// SO WE NOW ENCODE THE PAYLOAD TO JSON DATA STRUCTURE.
$jsonData = json_encode($payload);
// THAT'S ALMOST IT....
// THE NEXT THING WOULD BE TO SHIP THESE DATA TO THE REQUESTING SCRIPT
// WHICH WE SHALL DO HERE WITH A SIMPLY die() STATEMENT LIKE SO:
die($jsonData);

Using jQuery/Javascript to get value from PHP array

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

Jquery Post Empty Even though Sent Variable has data

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

Categories