how to pass the java script array to the php - javascript

Can you please show me ,how to pass the java script array to the
php . is it this way.
$.post("php_mysql_write.php", {datageo: shapes});
and after ur php script .. but php say's
Warning: mysqli::prepare()
[mysqli.prepare]: Couldn't fetch mysqli in
C:\xampp\htdocs\blitz-gmap-editor-master\php_mysql_write.php on line
25
Fatal error: Call to a member function bind_param() on a non-object
in C:\xampp\htdocs\blitz-gmap-editor-master\php_mysql_write.php on
line 26 please.
i used ur code
<?php $mysqli = new mysqli(/*args*/); $stmt =
$mysqli->prepare('INSERT INTO `tableName`(`columnName`) VALUES
(?)'); $stmt->bind_param('s', $json);
foreach($_POST['shapes'] as $value){ $json = json_encode($value);
$stmt->execute(); } ?>
Dr.molle's answer on
How to save a Google maps overlay shape in the database?

You should:
JSON.stringify(array);
to encode your JavaScript array, then use:
$array=json_decode($_POST['jsondata']);
in your PHP script to get the array.
Good luck!

Related

D3 get data from database - php sends the data but on javascript null

I am using D3.js to create graphs. I have used d3.json function to get my data. But it is showing null on the Javascript side.
This is my code from HTML page:
<script type="text/javascript">
var id=[];
d3.json("dataread.php", function(data)
{
console.log(data);
});
</script>
On the console it displays null.
The php file code is as follows:
<?php
$user="report";
$pass="report";
$dbh = new PDO('mysql:host=127.0.0.1;dbname=report', $user, $pass);
$query = $dbh->prepare('SELECT run_id from run');
$query->execute();
$data=$query->fetchAll();
$dbh=null;
echo "Hi";
echo json_encode($data);
?>
When the page is loaded, I am getting the php data. I have attached an image showing it.
Please guide where am I going wrong?enter image description here
Try removing the
echo "Hi"
from your code

Create JavaScript Array From MSSQL Query

I am attempting to create a JavaScript array from a MSSQL query results. Below is my syntax that I attempt to use, but the array is not created. How should this be set-up so that the JavaScript array is properly assigned?
<?php
$mssql = new mssql("localhost", "user", "password", "testdb");
$data=mssql_query($mssql,"SELECT * FROM test");
?>
<script>
var firstNames=[<?php
while($info=mssql_fetch_array($data))
echo $info['f_name'].',';
?>];
<?php
$data=mssql_query($mssql,"SELECT * FROM test");
?>
var lastNames=[<?php
while($info=myssql_fetch_array($data))
echo '"'.$info['l_name'].'",';
?>];
</script>
<?php
$mysqli->close();
?>
A good approach here would be to get the query (after correcting the deficiencies in the code as noted below your post, then casting the whole array to JSON using json_encode($data); and then echo $data in to your javascript.
This is not the only way to do it. I'm sure others will suggest other things.
Look at this page: https://www.w3schools.com/jquery/ajax_ajax.asp
I know, W3 Schools isn't the best, but it's okay.
You can do that with jQuery easy, just google a bit and you need php knowledge for creating an array out of a mysql query.

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

JavaScript cannot find JSON data from PHP json_encode

The idea here is to automatically load (or load at all) my index page with some products out of a MySQL database table.
Firstly, my PHP.
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
echo json_encode($itemsJSON);
}
This seems to be working great, and gives me two properly encoded JSON objects of my Item class.
{"name":"Slippers","quantity":"3","cost":"4.00"}
{"name":"Gloves","quantity":"5","cost":"9.00"}
My JavaScript looks like this(and many other similar variations)
$(document).ready(function () {
$.post( "productloader.php", function( data ) {
$( "#result" ).html( data );
});
});
I'm not sure why it is not working. I did not want to use $.getJSON() because there is no query string to work with, so I'd assume I would need $.post().
It seems like this is a pretty common issue, but I've not found a solution yet. Any help would be appreciated. Thank you.
You can't json_encode() each item separately. The data you're sending to the browser is not valid JSON, just many little chunks of valid JSON one after the other. Build an array inside your loop and then encode the whole thing. See also http://jsonlint.com/
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON[] = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
}
echo json_encode($itemsJSON);
In your method of AJAX, you're outputting multiple JSON strings while the js side is expecting 1 string (data). Try removing your for loop to just:
echo json_encode($items);
You are creating JSON for each row, so you are getting separate JSON objects for each row in front end.
You should put all row in to and array and create the JSON object outside the loop, and echo the encoded JSON string.
<?php
$allitem = $db->getRows('SELECT * FROM products');
$itemArr=array();
foreach($allitem as $item){
array_push( $itemArr , new Item($item->product_name, $item->product_quantity, $item->product_cost) );
}
echo json_encode($itemArr);
?>
or
$allitem = $db->getRows('SELECT * FROM products');
echo json_encode($allitem );

PHP json_encode then getJSON issue in javascript

Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.

Categories