creating 2D javascript array from ajax php call - javascript

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

Related

How to echo and retrive multiple rows with php

First off all hello to you all. The problem is I am making an ajax call from javascript to php file. And in that php file there is a prepared statement which returns 15 rows. I need to json_encode() these rows and send back to the javascript file so that I can use all of these information in each row which are info about users' profile. What's wrong with my code? I call fetch_assoc() constantly until all of the rows are processed yet when I display it on the console it only shows one row.
This is get_info.php:
// Get the profile info
$stmt = $conn->prepare("SELECT teachers.fname, teachers.lname, profile.img_url, profile.gender, profile.introduction, profile.city, profile.preference, profile.keyword FROM profile INNER JOIN teachers ON profile.user_id = teachers.id WHERE profile.keyword=? ORDER BY RAND() LIMIT 15");
$stmt->bind_param("s", $keyword);
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$resultArray = [];
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
$resultArray = $row;
}
$result = json_encode($resultArray);
echo $result;
}
And this is the javascript file where the ajax request is:
$(document).ready(function()
{
$.getJSON("get_info.php", function(result)
{
console.log(result);
}
)})
You keep overwriting $resultArray every time you loop, so you'll only ever see the last row returned by the query.
You need to make assign $row to a new element of $resultArray each time you loop - then adds rows to the array, instead of overwriting the variable with a single row.
It's very simple to do that:
$resultArray[] = $row;
You may also want to read https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying to refresh your memory of this key bit of PHP syntax.

How do I dynamically add to a JSON array in PHP

So I have the following JSON:
[{"username":"User1","password":"Password"},
{"username":"User5","password":"passWord"},]
Generated from:
<?php $username = $_POST["username"]; ?><br>
<?php $password = $_POST["password"]; ?><br>
<?php
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
$extra = array(
'username' => $username,
'password' => $password
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
print("working");
}
?>
After the user logs in they have the ability to make a post, how would I go about creating a post array for each user and how would I add to it dynamically ?
This is all I have and I have tried many different ways, but cant seem to figure out how to make it dynamic.
<?php
$urlText = $_REQUEST["urlText"];
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
//for loop
$array_data[i]['Posts'] = $urlText;
//end for loop
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
}
?>
In this situation though, posts is not an array, it just simply overwrites what already there.
[{"username":"User1","password":"Password","Posts:{"This is a post"}},
{"username":"User5","password":"passWord"},"Posts:{"This is a post2"}}]
Therefore, how do I add a posts array and how do I add to it dynamically ? I have not been able to figure such a simple thing out for a very long time
File get contents from like "posts/useridhere.txt", or allposts.txt
You will also need to use unique post IDs.
Json decode your posts JSON
Add post content to array
Json encode array
Write new json to the users post file
Ultimately I do not recommend this. If you want a paid internship I'll teach you how to use MySQL. We make websites :) but if you want to do it this way, you'll need a JSON file to store unique post IDs or even store all posts in one file. The problem is that you'll have a limit of how many posts can be stored in that single JSON array. I hope this answer is enough to help you. It's all the steps needed
$posts = file_get_contents($postsFile);
$posts = json_decode($posts);
$newPost = array(
"user"=>$user,
"postTitle"=>$string,
"text"=>$content
);
$posts[] = $newPost;
$newPostID = count($posts); // will not work properly (for linking posts) once you delete a post - you need unique post ids generated!
$posts = json_encode($posts);
// Overwrite your posts file with $posts. It will have all posts you need :)

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

Php script to fetch database value in array to see in Drop down list

I want to display a drop-down list which pull out database values. My actual code working fine, but here I have to provide the list in the array itself. What i required is, without editing the code, i needed to pull out values from database to this array("state1","state2"....); which is equal to something like this array("$states");
$sql = "SELECT * FROM `States`";
$result = $conn->query($sql);
$i=0;
while($row = $result->fetch_assoc()) {
$t=$row['statename'];
$t[$i]=$row['statenname'];
$i++;
}
$countryArr = array( "INDIA" => array("$t"));
I tried the above code but its listing only one value from database.
Remove this line
$t=$row['statename'];
just keep it to be
$t[$i]=$row['statenname'];

Dynamically insert new row using javascript, but how to save these multiple row in php/mysql

I have create multiple row by using javascript. Now how to save these row in mysql. I already using some type of code, its not working. here my code is
[http://jsfiddle.net/bb2pJ/]
and php code for adding these value.
`
include "config.php";
if(isset($_POST['submit']))
{
foreach ($_POST['code1'] as $key => $value)
{
$code1 = $_POST["code1"][$key];
$product1 = $_POST["product_name1"][$key];
$qty = $_POST["quantity1"][$key];
$rate = $_POST["amount_name1"][$key];
$total = $_POST["total_name1"][$key];
$sql = mysql_query("insert into testing(code,product,qty,rate,total)values('$code1','$product1','$qty1','$rate1','$total1')")or die(mysql_error());
}
}
?>`
From you Js fiddle code, you are trying to post array of values for each field (ie code, proddname, ...).
How are submitting these values? If not passing through ajax post, then you need to declare fields names like code[], product_name[] ... as array for all fields so they will be submitted as array.
Rest code you have writtten above should work by using proper field name like code for code[] ... .
Please put proper spacing between your keywords and values/fieldname in your insert into.. statement.

Categories