JSON encoded array, how to use in jQuery - javascript

Ok I've got this code in a file test.php:
<?php
$con = mysqli_connect("localhost", "user", "password", "DB");
if (mysqli_connect_errno()){
echo "failed to connect:" . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM DB");
$cars = array();
while($row = mysqli_fetch_assoc($grab)){
array_push($cars, array("id" => $row["Id"], "name" => $row["Name"], "color" => $row["Color"];
}
echo json.encode($cars);
And I've got the jQuery code on my HTML page:
$.get("test.php", function($cars){
$("itemNameLink1").html($cars.name);
console.log($cars.name);
});
My next question is how do I access the data in my json_encoded array and use it in my jQuery on the HTML page. Right now I only get back undefined in console log. It was only my first try so wasn't disheartened by it. But any advise would be appreciated.

That's because you try to access name property of $cars array instead of name property of each car. You should to iterate through your array first:
for(var car in $cars){
console.log(car.name);
}
or
$cars.forEach(function(e){
console.log(e);
});
if you maintain only modern browsers. Or use $.each method as #StartCoding mentioned.
AND, again as #StartCoding mentioned use $.getJSON instead of $.get or $.parseJSON($cars) if you've got a string in you response (it possible if your server returned wrong MIME-type [text/plain for example instead application/json]).

$.get("test.php", function($cars){
$.each($.parseJSON($cars), function(i, val){
$("itemNameLink1").html(val.name);
console.log(val.name);
});
});

Related

Get data from PHP file using AJAX when it is only single line result

I really thought I would figure this one out but I am stuck.
I only want to get one single result from this PHP file, so I believe it is unescessary to use an array then?
However, I've tried console.log(result) multiple times but I am only recieving "null".
What am I doing wrong?
AJAX:
$.ajax({
url: "includes/getwinner.php",
success: (function (result) {
console.log(result);
})
})
PHP
include("../steamauth/db.php");
$result=mysqli_query($db, "select low_winner from pots");
$row=mysqli_fetch_assoc($result);
echo $row['low_winner'];
Try this:
if ($result = mysqli_query($db, "select low_winner from pots")) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
echo $row["Name"];
}
/* free result set */
mysqli_free_result($result);
}
Use the mysqli_free_result function correctly, docs here.

Array from PHP to Javascript (Using JQuery)

I have some problems trying to redraw some markers (on google maps) from a database, use the form jquery
Index.html:
var map;
var datos;
function updateLocations(){
var post= $.post('php/getLoc.php',{table: "Auto"), function f(data){
datos =[]; //clear array with the last positions
datos = data;
drawAutos(datos); }); }
php/getLoc.php:
$link = mysql_connect("localhost","root","") or die('could not connect: '.mysql_error());
mysql_select_db("database") or die ('could not select db');
$autos= "SELECT * FROM autos ORDER BY auto_id ASC";
$result=mysql_query($autos) or die('query fail'.mysql_error());
$datos= array();
while($row= mysql_fetch_assoc($result)){
$datos[] = array(
0=>$row['taxi_id'],
1=>$row['lat'],
2=>$row['lng'],
3=>$row['availability']);}
$out = array_values($datos);
var_dump(json_encode($out));
mysql_free_result($result);
mysql_close($link);
The query is correct, but I get the information otherwise. there is a way to remove the string () "" (see picture), I have tried using $.parseJSON(data) and $.getJSON(data) but not work for me =(
echo json_encode($out); instead of var_dump($out);. Also, mysql is depreciated. Use mysqli or PDO or something else. The Object Oriented Approach will save you time. Also, you can $mysqli_result->fetch_all(MYSQLI_ASSOC) instead of making your while loop.
Ok, is working now :), thanks to PHPglue, I use
PHP File:
echo json_encode($out)
I also do in Index File:
var obj = $.parseJSON(data);
drawAutos(obj);

use a global javascript variable in ajax php mysql

I have a variable 'user_cache' stored in local storage: Now I am doing a $.getJSON call
<script>
user_data = JSON.parse(localStorage.getItem("user_cache"));
$.getJSON("query.php", { productId: productId}, function(data) { /*do something*/});
</script>
Query.php does a php_mysql database query:
<? php
if( $_REQUEST["productId"] )
{
$productid = $_REQUEST['productId'];
/*Database connection*/
include_once("php_includes/db_conx.php");
$sql = "DELETE FROM USERPRODUCTCOLLECTION WHERE Product_ID = $productid";
if ($db_conx->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$db_conx->close();
}
?>
My question is that I also want to use the object 'user_data' in the query.php file to do that database query but I dont want to pass 'user_data' in $.getJSON. Is it possible to use 'user_data' object inside 'query.php' file without having to pass it in the $.getJSON?
Unfortunately that will not be possible. You must pass the data to the php file in order to utilize it. Are you leaning away from passing the user data because it is passing it as a GET variable (in the URL)? If so, consider using a jQuery.post() call instead. This way the data will be posted instead of in the URL.
See : http://api.jquery.com/jquery.post/

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

jQuery $.each loop and json mysql data

Well i have this php for get the value of mysql.
I get two rows in this query.
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT
accion_inmediata.accion,
accion_inmediata.responsable,
accion_inmediata.peligro,
accion_inmediata.ambiente,
DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion
FROM
accion_inmediata
WHERE
accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = mysql_fetch_array($result);
echo json_encode($array);
and this is my Jquery code
function traerAcciones(pnc){
$.ajax({
url: 'php_ajax/select_acciones.php?pnc='+pnc,
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
alert(this.accion);
});
}
});
}
when i execute this code the alert show me "undefined".
The $.each loop works fine but the value is the problem.
Please help and sorry for my bad English
Try to pass the value and the Index as parameters, this is how it works:
$.each(data, function(index, value) {
alert( value.accion );
});
Might also be a problem with the data object not containing what you think it does, do a
console.log(index, value);
inside your loop and a
console.log(data);
before the loop and you will see what you have and how to handle it.
Hope it helps!
Currently you are returning the array of your first row only. So to retrieve both you might want to do this:
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT accion_inmediata.accion, accion_inmediata.responsable, accion_inmediata.peligro, accion_inmediata.ambiente, DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion FROM accion_inmediata WHERE accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = array();
while($row = mysql_fetch_array()):
$array[] = $row;
endwhile;
echo json_encode($array);
Now your jquery should be able to retrieve the data. Also, please avoid using MYSQL_QUERY it's deprecated.

Categories