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);
Related
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);
What if I want to console.log only one 1(ANY) javaScript object. Currenly it displays all 1000. Please Look at Php and JS files:
Server.php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array("coordinates" => array());
$sql = "SELECT Lng, Lat, URL FROM results LIMIT 1000";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data["coordinates"][] = $row;
}
}
echo json_encode($data);
Index.js
{
$.ajax({
dataType: "json",
url: 'server.php',
//data: [],
data: {param: ""},
success: function(data)
{
//JSON.parse(data);
console.log(data);
addMarkers(data,map);
}
});
}
It helps to understand the json data structure you are outputting, and how you access certain elements from an object made by that json. In your case, you end up with a single object named data (as defined by the .ajax success callback). That object then contains just one keyname with an array of objects. The keyname is coordinates. Inside each array value, is an object from your database row return.
If you simply wish to show one object from your array of objects, this is all you need:
console.log( data.coordinates[0] );
That would show the first object in the array (arrays start with [0]).
console.log( data.coordinates[999] );
That would show the last object in the array of 1000.
console.log( data.coordinates[ data.coordinates.length-1 ] );
That would show the last object in an array of a variable size, using itself as the determiner.
It's displaying all because you're logging all. You're returning 1000 objects from your db call, which is why it's logging all.
You could find a single object by a key using something like:
data.filter(x => x.myPropValue == "myString");
And log that.
If you want your JavaScript AJAX call to not log all 1000 items, you might want to change your php code ($sql = "SELECT Lng, Lat, URL FROM results LIMIT 1000";) to only send one item per call (e.g. replace 1000 with 1), and then adjust the Server Logic to get the respective next item on a following AJAX call.
This would also make your Server & Client faster, since it's reducing the total data amount, but would still allow 1000 or more items.
You could also try and add a parameter, so that you can tell your php code how many items your JS code needs to get.
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 have a mysql table with image data in.
I want to retrieve the image data and push into a javascript array.
There are two fields that I want to put into the array and they are image_ref, and image_name
I know I need a 2D array for this and I need to retrive the data from the db using ajax and JSON.
I am not sure how to complete this.
I know I need to call the php page with a JSON ajax call
js:
var imagesArray[];
$.getJSON("get_image_data.php")
.done(function(data) {
/*THIS IS WHERE I NEED HELP---*/
});
get_image_data.php page
include("connect.php");
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
while($row=mysql_fetch_array($query){
echo json_encode(array("a" => $row['image_ref'], "b" => $row['image_name']));
}
I have highlighted where I need help in getting the returned data into the stockImages array.
Can anyone show me the light?
thanks in advance
By calling json_encode() multiple times in your loop, you are creating lots of singular bits of JSON. You should aim at creating and transmitting one transfer object, like this:
include("connect.php");
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$images = array();
while($row=mysql_fetch_array($query){
$images[] = array("a" => $row['image_ref'], "b" => $row['image_name']);
}
echo json_encode($images);
This will give you one JSON array, through which you can loop in your client side Javascript.
Actually, it is PHP that is wrong, 'cause on JS you will have the array you need directly in "data".
You PHP code should look like:
$query = mysql_query("SELECT * FROM images WHERE live='1' ORDER BY insertDate DESC");
$result = array();
while($row=mysql_fetch_array($query){
$result[] = array("a" => $row['image_ref'], "b" => $row['image_name']);
}
echo(json_encode($result));
I'm in a team developing an Android application that will rely greatly on the use of a remote database. We are using PhoneGap and Jquery Mobile and have been attempting to connect to our MySQL database using AJAX and JSON calls. Currently, we are having trouble in our testing phase, which is to verify we even have a connection at all by pulling a hard-coded user of "Ted" from mySQL / input via MySQL Workbench.
From what we have gathered, the process of data transmission works as this:
On our html file, we have a
<script type="text/javascript" src="Connect.js"></script>
^ Which should run the Connect.js script, correct? So from there, Connect.js is ran?
Connect.js runs, connecting it to our ServerFile.php that is hosted on an external web service, allowing it to run PHP to connect to the MySQL database and pull information.
//run the following code whenever a new pseudo-page is created
$('#PAGENAME').live('pageshow', function(event)) {
// cache this page for later use (inside the AJAX function)
var $this = $(this);
// make an AJAX call to your PHP script
$.getJSON('http://www.WEBSITENAME.com/ServerFile.php', function (response) {
// create a variable to hold the parsed output from the server
var output = [];
// if the PHP script returned a success
if (response.status == 'success') {
// iterate through the response rows
for (var key in response.items) {
// add each response row to the output variable
output.push('<li>' + response.items[key] + '</li>');
}
// if the PHP script returned an error
} else {
// output an error message
output.push('<li>No Data Found</li>');
}
// append the output to the `data-role="content"` div on this page as a
// listview and trigger the `create` event on its parent to style the
// listview
$this.children('[data-role="content"]').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create');
});
});
Here is ServerFile.php. This should connect to the MySQL Database, make the Select statement, and then send the output to the browser encoded in the JSON format.
<?php
//session_start();
$connection = mysql_connect("csmadison.dhcp.bsu.edu", "clbavender", "changeme");
$db = mysql_select_db("cs397_clbavender", $connection);
//include your database connection code
// include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELECT * FROM Users WHERE Username ='Ted'", $db) or trigger_error(mysql_error());
//create an output array
$output = array();
//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {
//iterate through the results of your query
while ($row = mysql_fetch_assoc($query)) {
//add the results of your query to the output variable
$output[] = $row;
}
//send your output to the browser encoded in the JSON format
echo json_encode(array('status' => 'success', 'items' => $output));
} else {
//if no records were found in the database then output an error message encoded in the JSON format
echo json_encode(array('status' => 'error', 'items' => $output));
}
?>
Yet nothing is showing here. What do we do from here?
First thing first. Try to determine where is the problem come from, server side or client side.
Print out your database query and encoded json can be useful. If you are creating a simple API service, you should be able to enter http://www.WEBSITENAME.com/ServerFile.php using your browser and look how the output is.
Use echo to print things with php.
If all looks ok, time to print out the response you receive from the server in the javascript and see what is off.
Use console.log to print thing with javascript. The logs should appear in the logcat section of eclipse (since you are developing android app)