I'm new to dynamic data and trying to
read data from a mysql database using PHP
turning this data to JSON
fetching the data through javascript (jQuery)
Inserting it into my page.
As far as I can see, 1) and 2) work fine, 3) seems to kind of work and 4) is where it breaks.
I've set up the database and the table, query & echo the data like so (api.php)
<?php
include 'db.php';
$con = new mysqli($host,$user,$pass,$databaseName);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM $tableName";
$myArray = array();
if ($result = $con->query($query)) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$con->close();
?>
Now I get it through javascript...
jQuery(function($) {
$.ajax({
url: 'php/api.php',
data: "json",
dataType: "",
success: function(data) {
var r = new Array(), j = -1;
for (var key=0, size=data.length; key<size; key++){
r[++j] ="<tr><td>";
r[++j] = data[key][0];
r[++j] = "</td><td>";
r[++j] = data[key][1];
r[++j] = "</td><td>";
r[++j] = data[key][2];
r[++j] = "</td></tr>";
}
var joined = r.join('');
console.log(joined);
$('#maintable tbody').html(joined);
}
});
});
... and throw it in the tbody element of my table.
The result is absolutely not what I expected:
See http://i.imgur.com/hRNrmdC.jpg (sorry for the partly german interface)
The Answer to the GET request is valid JSON, at least in theory (checked by http://jsonlint.com/ ), but to me it seems the data is treated as a string and split into an array of chars (each char a "key" in data[]), therefore "data[key][1] returns nothing.
var json = JSON.stringify(eval("(" + data + ")"));
and continuing with json[key][0] didn't help...
Now I wonder why and especially, what went wrong and how its fixed.
You have mixed up the keys in your ajax call:
data: "json",
dataType: "",
Should be:
dataType: "json",
as you are not sending or using any data at all.
Related
I am trying to retrieve information of BD with ajax.
The thing is when i receive the data from the script php, it send me a json file, but i cant print the values, this is my code.
JS:
$(document).ready(()=>{
$('table').on("click", "p", function(){
let value = $(this).attr('value')
if (value=='true') {
$(this).addClass('disabled')
let data = $(this).attr('data-value')
var info = {
"numSelection":data,
"sort": "97"
}
$.ajax({
data:info,
url:"js/service.php",
type:"post",
beforeSend:function(){
console.log("Estamos en proceso con ajax")// Here we are fine
}
}).done(function(data){
console.log(data)//this print the json file in console
correctly
$.each(data,function(i,item){//here is the error in console
console.log("Index: "+i)
console.log("Item: "+item)
})
})
}
});
});
in this step i receive this error un console:
Uncaught TypeError: Cannot use 'in' operator to search for '957' in + the content of the json file
and this is my php script with the sql
<?php
// var_dump();
// error_reporting(E_ERROR | E_WARNING | E_PARSE);
include('conn.php');
$sql = "SELECT * FROM participantes WHERE sorteos_id=".$_POST['sorteo'].";";
$result = mysqli_query($conn, $sql);
$resultado = mysqli_fetch_array($result);
$enviar = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$enviar[]=$row;
}
} else {
echo "0 results";
}
echo json_encode($enviar);
?>
If I do not send the information in json format, it is sent in an array but with an annoying message
Notice: Array to string conversion in C:\UwAmp\www\testing\js\service.php on line 19
Array
I am new coding so i accept any suggestion
Thank you so much guys for trying to help me with this. But they gave me many ideas, so i found my answer...
My mistake was, dont specify what format i am waiting, just have to add
dataType: "json in the config of $.ajax.
$.ajax({
data: info,
url: "js/service.php",
type: "post",
dataType: "json", //this to receive json
beforeSend: function() {
console.log("Estamos en proceso con ajax")
}
}).done(function(data) {
console.log(data)
$.each(data, function(i, item) {
console.log("Index: " + i)
console.log("Item: " + item)
})
})
php
$result = mysqli_query($conn, $sql);
$resultado = mysqli_fetch_array($result);
$enviar = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$enviar[]=$row;
}
} else {
echo "0 results";
}
echo json_encode($enviar);//this to send json
I have a filter for some devices in a webpage, made of checkbox. Whenever one of the checkbox is clicked, i call a function which add to an object the value of the checkboxes checked. I want to send this object to a php file, via ajax, and use it to perform some MySQL query, then return the results from the php and display them on the page. The problem is, i'm missing something, since i kept getting a parseerror in my js.
Here's my code:
device-filter.js
$(document).ready(function(){
$(".ez-checkbox").click(function() {
console.log("ok");
var re = {Brand: "", Cost: "", OS: ""};
$("#Brand :checkbox:checked").each(function(){
re.Brand += $(this).val()+" & ";
});
$("#Cost :checkbox:checked").each(function(){
re.Cost += $(this).val()+" & ";
});
$("#OS :checkbox:checked").each(function(){
re.OS += $(this).val()+" & ";
});
if(re.lenght==0){
}
else{
$.ajax({
method: "POST",
dataType: "json", //type of data
crossDomain: true,
data: re,
url:"./php/filtered-device-query.php",
success: function(response) {
//display the filtered devices
},
error: function(request,error)
{
console.log(request+":"+error);
}
});
}
});
});
filtere-device-query.php
<?php
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_db");
if (mysqli_connect_errno()) { //verify connection
echo "Error to connect to DBMS: ".mysqli_connect_error(); //notify error
exit(); //do nothing else
}
else {
//echo "Successful connection"; // connection ok
$devices =json_decode($_POST['re']);
echo var_dump($devices)."<br>";
$myArray = array();//create an array
$brand = rtrim($devices["Brand"], " &");
$cost = rtrim($devices["Cost"], " &");
$os = rtrim($devices["OS"], " &");
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND 'Cost' = '$cost' AND 'OS' = '$os' ";
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
//free result
$result->close();
//close connection
$mysqli->close();
}
?>
Thanks in advance for any help!
You have some typos, first in the jQuery:
if(re.lenght==0){
should be:
if(re.length==0){// note the correct spelling of length
Then in your PHP you're using quotes on column names in the query. Those should be removed or better yet, back ticked:
$query = " SELECT * FROM `devices` WHERE `Brand` = '$brand' AND `Cost` = '$cost' AND `OS` = '$os' ";
More importantly...
An object, as you've described it, has no length. It will come back as undefined. In order to find the length you have to count the keys:
if(Object.keys(re).length == 0){...
The object re, as you've declared it, already has 3 keys, a length of 3. Checking for length of 0 is a waste of time.
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
I have an $.ajax call in one of my pages that links to a simple php page.
I am getting my alert for the error: property. I am not getting anything back in the errorThrown variable or in the jqXHR variable. I have never done this kind of thing before and i am not seeing what is wrong with my page.
JQuery $.ajax call :
function jsonSync(json) {
$.ajax({
type: 'POST',
url: 'http://www.cubiclesandwashrooms.com/areaUpdate.php',
dataType: 'json',
data: json,
context: this,
success: function () {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error has occured! \n ERR.INDEX: Sync failed, ' + jqXHR.responseText + ';' + textStatus + ';' + errorThrown.message);
return false;
}
});
And this is my PHP Page :
$JSON = file_get_contents('php://input');
$JSON_Data = json_decode($JSON);
//handle on specific item in JSON Object
$insc_area = $JSON_Data->{'insc_area'};
//mysqlite connection.open() equivilent
$insc_db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($insc_db)) {
die('Could not connect: ' . mysql_error());
echo "Failed to connect to MySql: " . mysqli_connect_error();
//mysqli_close($insc_db);
}
//$insc_area.length equivilent
$insc_area_size = sizeof($insc_area);
//cycle through reult set
for ($i = 0; $i < $insc_area_size; $i++) {
//assign row to DataRow Equivilent
$rec = $insc_area[$i];
//get specific column values
$area = $rec->{'area'};
$id = $rec->{'srecid'};
//sqlcommand equivilent
$query = "SELECT * FROM insc_products WHERE id='$id' LIMIT 1";
$result = mysqli_query($insc_db, $query);
$num = mysqli_num_rows($result);
//dataReader.Read equivilent
while ($row = $result->fetch_array()) {
$query = "UPDATE insc_products SET area='$area' where id = '$id'";
$res = mysqli_query($insc_db, $query);
//checking if update was successful
if ($res) {
// good
error_log('user update done');
echo 'update was successful';
} else {
error_log('user update failed');
echo 'error in update';
}
}
}
echo 'testing php';
dataType: 'json'
means: give me json back. your PHP file isn't returning json formatted data
similar question: jQuery ajax call returns empty error if the content is empty
to buid a json response fill an array in the php file with the return information and use echo json_encode($array); at the end of the file. if you are using dataType:'json' because the code is copy/pasted, and you won't need the response to be in json format, simply remove this option...
Add following line in php file, $JSON_Data encode then it will work.
echo json_encode($JSON_Data);
Using following MySQLi and PHP snippet I can export the result in a numeric array as:
["8","188.396496","7.876766","69885005.45"]
Now I need to have the output in exact numeric format like (removing " " from the items)
[8,188.396496,7.876766,69885005.45]
and here is the code I have in PHP part
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
$json=json_encode($row);
}
}
$con->close();
echo $json;
?>
How can I do that?
Update
var req2 = $.ajax({
type: "POST",
data: data,
dataType: 'json',
url: "assets/tempchart.php"
});
req2.done(function(data) {
var cars = [];
cars.push(data)
console.log(cars[0]);
in this case the out out is [8,188.396496,7.876766,69885005.45] but I need to get ONLY 8 as cars[0] is 8.
if ($results) {
$row = $results->fetch_array(MYSQLI_NUM);
$row = array_map('floatval', $row); // Convert strings to numbers
echo json_encode($row);
}
The Javascript should be:
req2.done(function(data) {
var cars = [];
cars.push(data[0]);
console.log(cars[0]);
});
You just have to cast your results to float before calling json_encode :
$query = "SELECT project, powerline, road, cost FROM `charts_econo_new`" ;
$results = $con->query($query);
if($results) {
while($row = $results->fetch_array(MYSQLI_NUM)) {
// Cast to float
foreach($row as &$item) {
$item = (float) $item;
}
$json=json_encode($row);
}
}
$con->close();
echo $json;
(And you are only getting the last row of your table, because you overwrite the content of $json each time but if you only have one row in your table that can be ok)
Please try to use floatval() function to convert string from DB in float values.
So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]
You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.
you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);