I execute a simple AJAX Request, where i select some data from a mysql database. When i pass my Array back to Javascript, it always converts all Values in my Array into String, doesn't matter if its datatype was integer or boolean in my database.
EDIT:
I just found out, that MySQLi always converts datatypes to string, so I guess thats the problem. json_encode works fine.. https://stackoverflow.com/a/5323169/4720149
SQL Statement
function getAll()
{
// Get all buildings
$db = new db();
$sql = "SELECT * FROM building";
$result = $db->runQuery($sql);
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
PHP Controller File
function getBuildings(){
$bu_db = new Building_Model();
$buildings = $bu_db->getAll();
echo json_encode($buildings);
}
Javascript file
var data = {
action: "getBuildings"
};
$.ajax({
type: "POST",
dataType: "json",
url: "controller/Building.php",
data: data,
success: function(data) {
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error in AJAX Request: " + textStatus + ", " + errorThrown);
}
});
Instead of keeping the original datatypes from the database, it turns all values into Strings:
Output
[Object, Object, Object, Object, Obje...]
>0: Object
>1: Object
>2: Object
>3: Object
ActiveCost: "20"
BuildEfc: "0"
BuildSfx: "0"
BuildingEfc: "0"
BuildingID: "1"
Name: "Vogtei I"
ResidentLvLNeeded: "0"
...
Does anybody know this problem?
Thanks in Advance.
What PHP version do you use?
Try:
echo json_encode($buildings, JSON_NUMERIC_CHECK );
Javascript has dynamic data types. So there is no specific data type for int string etc. same var object can hold all the data types. It will dynamically identify the type based on the operations you do on those variables.
Related
I am making post request with ajax and sending data with json format.Then I am fetching json with php and decode it into an array.When I print out whole array there is no problem. I can see the key value pairs.But when I try to print out this array's one of index value it returns null.What could be the problem?Here is my ajax request
$(function() {
$("#del").click(function() {
var file_id = 32
var file_update = 1321321
var obj = {
file_id: file_id,
file_update: file_update
};
$.ajax({
type: "post",
url: "config/ajax.php",
data: {
"file_update": JSON.stringify(obj)
},
success: function(response) {
alert(response);
}
})
})
})
Here is my php code
if (isset($_POST["file_update"])) {
$file_update = json_decode($_POST["file_update"], true);
$x = $file_update[0];
var_dump($x);
var_dump($file_update);
}
The $file_update array is associative, therefore it doesn't have integer keys, its keys are strings.
$file_update[0] does not exist and this statement should throw an error given you have proper error reporting configured.
If you want to access specific array values use:
$file_update['file_id'];
$file_update['file_update'];
If you want to access the first element of an associative array you can use the following:
$key = array_keys($file_update)[0];
$value = $file_update[$key];
To try and be as short and sweet, yet as descriptive as possible i am having issues grabbing a PHP Object through Jquery Ajax.
I am a semi-new PHP developer and i have created an object containing some strings and variables as shown here:
calculation.php
$return = new stdClass;
$return->success = true;
$return->errorMessage = "Oops, something went wrong!";
$return->Score = number_format($scoreFromSheet,1);
$return->roi = number_format($roiFromSheet,1);
$return->dvScoreAnalysis = $scoreAnalysis;
$return->className = $className;
$json = json_encode($return);
echo $json;
I have constructed a very crude Ajax call to the PHP file to try to access the json_encoded object. As shown here:
finalPage.php
$(document).ready(function(){
var data;
$.ajax({
dataType: "json",
url: './dvs_calculation/calculation.php',
data: {data:data},
success: function (json) {
alert('working');
console.log(json[0].Score);
},
error: function(xhr, textStatus, errorThrown) {
alert( "Request failed: " + textStatus );
}
});
});
I have echo'd the object to the DOM to display the output of my object, and it looks pretty solid:
$json output
{
"success":true,
"errorMessage":"Oops, something must've gone wrong!",
"Score":"65.5",
"roi":"25.8",
"ScoreAnalysis":"High Deal Viability"
}
When using the Ajax function i receive a parse error and it prints out nothing from the success function. Not sure where i am going wrong. Any help or reference greatly appreciated.
Access the Score value from the json response as
json.Score //gives you the value of Score key from json
Also according to the code provided, you aren't passing anything to the php side as the data variable is just defined
How can I assign results from Ajax call into a variable?
I have a drop down list. when user make a choice. I want ajax to call a PHP page to find related data from server and auto fill that into an input field.
See below code
$(document).on('change','#dropdownchoiceid', function(){
$id = 1; // passing in some variable for php to use
$.ajax({
url: "../folder/getdata.php",
type: "POST",
data: {
'id' : $id
},
success:function(data){
$result = data;
console.log($result);
$('#inputid').val($result.column1);
$('#inputid2').val($result.column2);
}
});
The php is working. I get the result in a object that look like this
array(1) {
[0]=>
object(stdClass)#5 (4) {
["id"]=>
string(1) "2"
["column1"]=>
string(7) "20.0000"
["column2"]=>
string(14) "someinfo"
["column3"]=>
string(1) "1"
}
So I am trying to change the input field value with the datas I got from the server. but I get blanks in the console.log. I dont quite understand the code below. I tried it because I see this answer on stackoverflow for similar questions
success:function(data){
$result = data;
}
the PHP is
<?php
//Create class Object
$mProduct = new mProduct;
$id = $_POST['id'];
$result= $mProduct->getData($id);
the model PHP page is
public function getData($id){
$this->db->query("
SELECT
*
FROM rebate
WHERE id= :id
");
//bind
$this->db->bind(':id', $id);
//Assign Result Set
$result = $this->db->resultset();
return $result;
}
I hard-coded an array to match what your db methods returned, according to your var_dump,
in your PHP page:
$arr=(object) [ "id"=> "2", "column1"=>"20.0000", "column2"=>"someinfo", column3"=>"1" ];
$arr=array($arr);
//var_dump($arr);
echo json_encode($arr, JSON_FORCE_OBJECT);
Also, I suggest that use echo instead of print_r because
print_r will also show protected and private properties of objects with PHP 5.
See PHP Manual print_r
Initialize your $result variable and since it is an array with a single element
you must reference it that way:
$.ajax({
url: "getData.php",
type: "POST",
data: {
'id' : $id
},
dataType: "json",
success:function(data){
var $result = data; // var initialize
console.log($result);
$('#inputid').val($result[0].column1); //$result is an array
$('#inputid2').val($result[0].column2);
},
error:function(data){
window.alert("Something went wrong"+data.error);
}
});
You ask:
(Quote)...is the word data supposed to match the $result from my PHP page?
..data is the variable on the client side that the server response gets stored in
To receive data on front end, the PHP page has to print something, preferably in JSON format. Try this:
<?php
//Create class Object
$mProduct = new mProduct;
$id = $_POST['id'];
$result= $mProduct->getData($id);
print_r(json_encode($result));
I am OP answering my own question.
Get data from php array - AJAX - jQuery
after checking above post. here is the answer
so the final working code look like this
$(document).on('change','#dropdownchoiceid', function(){
$id = 1; // passing in some variable for php to use
$.ajax({
url: "../folder/getdata.php",
type: "POST",
data: {
'id' : $id
},
datatype: "json",
success:function(data){
$result = data;
console.log($result);
$('#inputid').val($result.column1);
$('#inputid2').val($result.column2);
}
});
in PHP
add one more line
echo json_encode($result);
I have this php code that is call using jQuery ajax that queries a database and gets results and then json encode the results
//$rows is another query
foreach($rows as $row) {
$sql = 'SELECT field1, field2 FROM table WHERE field1= :field';
$stmt = $db->prepare($sql);
$stmt->bindValue(':field', trim($row['field_1']));
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
}
The outputting json looks like this
[{"field1":"J1","field2":"0088","field3":"2928868"}][{"field1":"J2","field2":"0171","field3":"2928868"}][{"field1":"J2","field2":"0249","field3":"2928868"}]
The problem I'm getting is processing it in the Ajax response. What I would like to do i s loop through each of the array/rows and display the data but the responseText shows an error.
I thought it should look this but i don't know for definite.
[{"field1":"J1","field2":"0088","field3":"2928868"},{"field1":"J2","field2":"0171","field3":"2928868"},{"field1":"J2","field2":"0249","field3":"2928868"}]
My question is, am i doing the json_encode correctly and how do i output each of the rows?
$.ajax({
type: "POST",
url: "check.php",
data: { order: order },
dataType: "json",
cache: false,
success: function(response) {
if(response.length != 0) {
//output results here
}
else {
$('#foo').text('Order number not found!!');
}
// set the focus to the order input
$('#order').focus().val('');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('An Ajax error was thrown.');
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
You should JSON encode the entire output, instead of outputting the json encoded version of each row:
$output = array();
//$rows is another query
foreach($rows as $row) {
$sql = 'SELECT field1, field2 FROM table WHERE field1= :field';
$stmt = $db->prepare($sql);
$stmt->bindValue(':field', trim($row['field_1']));
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
$output[] = $array;
}
echo json_encode($output);
Answering your question, to work with your JSON in JavaScript, you treat it as if it were an array of objects. You can even use jQuery to help loop through the results for you with $.each:
if(response.length != 0) {
$.each(response, function(index, row) {
console.log(row);
// Access your row variables like so:
// row.field1, row.field2, row.field3, etc.
}
}
If you prefer natively looping through, you can do the following:
// Let i start at zero. If the response array length is less than i, execute the block, then increment i by 1.
for(var i = 0; response.length < i; i += 1) {
}
Related Question / Further Reading: How to parse JSON in JavaScript
I'm trying to pass a json from php jquery, after getting into an array of sql query and get the following javascript error.
JSON.parse: unexpected character
The function to return result of sql:
public function selectassocSql($sql){
$i = 0;
$resSelect = array();
mysql_query("SET NAMES 'utf8'");
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) )
{
$resSelect[$i] = $row;
$i++;
}
mysql_free_result($result);
return $resSelect;
}
After use this function in this way,
$sql = "SELECT id, code, name FROM table WHERE code LIKE '%$codcli%' ";
$v = $data->selectassocSql($sql);
echo json_encode($v, JSON_FORCE_OBJECT);
And the javascript code is this:
$('#formclientes').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = $.parseJSON(data);
}
})
})
How I can correct this error and how I can read a json from jquery?
You don't need the $.parseJSON call as jQuery automatically does it because if you don't specify a dataType property jQuery tries to guess it and calls the correct function to parse the response before the data is handled to the success function
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = data;
}
})
check out also this question Why is 'jQuery.parseJSON' not necessary?
I just ran into this in FF10.0.2 with data that looked like:
[ { "firstName": 'Joe', "lastName": 'Smith' } ]
(with multiple objects in the array - shortened for clarity)
It actually parsed OK using eval, though, instead of JSON.parse. (I'm not using jQuery here.)
The problem went away when I changed ' to " for the values:
[ { "firstName": "Joe", "lastName": "Smith" } ]
I thought the " requirement was only for property names, not data values.