I have a loop that grabs DB values and creates an object. I want to echo a JSON object every time the loop is iterated through. As of now, I just get blank in my console. Also, those commented out printf statements work fine. Any help would be much appreciated!
AJAX call
$.ajax({
url:'ajax/ipGet.php',
type: 'GET',
dataType:'json',
success:function(response){
console.log(response);
}
});
PHP Data Generation
$infoArray = new Array();
while($row = mysqli_fetch_array($getIpQuery, MYSQLI_NUM)){
for($x=0;$x<count($row);$x++)
{
$getIpInfo = mysqli_query($dbcon,"SELECT * FROM ipInfo WHERE address='$row[$x]'");
$retrievedInfo = mysqli_fetch_array($getIpInfo,MYSQLI_NUM);
$ipInfo->ipAddress = $retrievedInfo[0];
$ipInfo->port = $retrievedInfo[1];
$ipInfo->status = getStatus($ipInfo->ipAddress, $ipInfo->port);
array_push($infoArray,$ipInfo);
}
}
echo json_encode($infoArray);
Thanks for any help!
~Carpetfizz
json must be a single self-contained entity. You're outputting MULTIPLE separate bits of JSON text, which is incorrect.
JSON encoding should be the very LAST thing you do, e.g.
while(...) {
$array[] = ....
}
echo json_encode($array);
Consider what you're doing from the client perspective... building an array of ipinfo, so you run the loop once and produce
{"ipAddress":"127.0.0.1","port":80,....}
But you're doing it multple times, so you end up with
{"ipAddress":"127.0.0.1","port":80,....}{"ipAddress":"127.0.0.1","port":80,....{"ipAddress":"127.0.0.1","port":80,....}
as your output, and now you've got illegal javascript. Remember that JSON text is essentialy the right-hand-side of a Javascript assignment operation, e.g.
var somevar = ...json_goes_here...;
So you're doing
var stuff = {...}{...}{...};
which is an outright syntax error, instead of
var stuff = [{...},{...},{...}];
which would be correct.
Related
I have a foreach loop that is called from my AJAX code. It appears that the foreach loop is being skipped right over. I would ultimately like to make it so that the foreach loop will execute a query using each value in the array, but I am first trying to test the the foreach loop works (which it does not). The alert (from my AJAX) that I am receiving is just the original array and not the one with the added items.
PHP:
$data = array();
if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']){
$data = $_POST['myArray'];
foreach ($data as $item) {
$data[] = $item;
}
echo json_encode($data);
die();
}
AJAX:
$(document).ready(function(){
$('#btn-addkegs').click(function() {
var arr = kegs;
var myArray = JSON.stringify(arr);
$.ajax({
url: "addkegs.php",
method: "POST",
dataType: "json",
data: {myArray: myArray},
success: function (result) {
alert("Your kegs have been added! These include: " + result);
textarea.value = "";
kegs = [];
}
});
});
});
As for the line var arr = kegs;, the value of the array 'kegs' is set through an input field and other AJAX, but all that works fine. I think that my problem is with my PHP code.
If you are send via post only values... like in comments : 1,2,3
your $_POST['myArray'] was receive literaly what you sent to.
So, data variable will receive the array that seems like this ['1','2','3']
Well... Since you are not creating a variable $data as an Array, and yes, only putting an array inside it.
The PHP doesnt consider the $data[] variable as same as $data.
So, the PHP was magicaly overwriting the values from each same values.
So, I think if you want to repeat the values in the same array, you must reference the array with the array_push
$data = $_POST['myArray'];
foreach ($data as $item) {
array_push($data, $item);
}
Now when you return this array, you will have a response like {1,2,3,1,2,3}
Answer from a comment by #David:
In your browser's debugging tools, take a look at the network requests. Examine the AJAX request and its response. If the result is entirely wrapped in quotes, then it's just a string and not an array. You may need to JSON-decode $_POST['myArray'] server-side to interpret it as an array.
I needed to change $data = $_POST['myArr']; to $data = json_decode($_POST['myArr']);.
I have a JSON encoded array, to which i am returning to an AJAX request.
I need to place the JSON array into a JS Array so i can cycle through each array of data to perform an action.
Q. How do i place the JSON array contents into a JS array efficiently?
The PHP/JSON Returned to the AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
You can use JSON.parse function to do so:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
You can also use jQuery.parseJSON() if you are using jQuery, however jQuery also uses same function under the hood as priority if available.
Adding to Safraz answer:
If you're using jQuery, there's another way to do that. Simply add json as last parameter to your ajax calls. It tells jQuery that some json content will be returned, so success function get already parsed json.
Below example shows you simple way to achieve this. There's simple json property accessing (result.message), as well as each loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each loop calling value.objectfield.
Example:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)
i'm just trying to query the database and display the result the jquery's ajax method but if i put the dataType property as json it is only logging the result which has only one object the following is my code:
//this is a method is an object which will be triggered after a selection was made
lister: function () {
//this is to target the object as it is inside an event
var self = users;
//the ajax call
$.ajax({
url: 'index.php',
type: 'POST',
data: self.config.form.serialize(),
//this is the dataType
dataType: 'json',
success: function (results) {
//this for logging the result
console.log(results);
}
});
}
the php code
if(isset($_POST['q']) && !empty($_POST['q'])){
$na = $_POST['q'];
$query = mysql_query("SELECT id,first_name, last_name
FROM users WHERE users.first_name LIKE '$na%'");
$num=mysql_num_rows($query);
if($num >= 1){
while($row = mysql_fetch_array($query)){
//encoding the result as json
echo json_encode($row);
}
} else{
echo "no results found ";
}
//here we return so it won't display all of the pages
return;
}
You are generating invalid JSON. You are encoding every row of your table independently, which generates something like this:
{"foo": "bar"}{"foo": "bar"}{"foo": "bar"}
This is isn't valid. It's just a concatenation of objects. What you need is an array of objects:
[{"foo": "bar"}, {"foo": "bar"}, {"foo": "bar"}]
You can achieve that by creating an array first, add each row to it and encode the array:
$data = array();
while(...) {
$data[] = $row;
}
echo json_encode($data);
Another problem is that in case no results are found, you are simple returning plain text, not JSON. This will probably result in an error on the client side. If you tell jQuery to expect JSON, then every possible response must be JSON. So you might want something like:
echo json_encode(array('error' => 'no results found'));
or even better, return an empty array:
echo json_encode(array());
It should be fairly obvious to the client that no results have been found if an empty array is returned.
Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);
How come i can't return id using data[0].id?
$(document).ready(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: '<?php echo matry::base_to('tests/map_it');?>',
success: function (data)
{
alert(data[0])
$('#alerts').html(data);
data[0].id
}
});
});
Here's the alert that's returning.
{"id":19385,"first":"RLY","last":"MAZI",
"trainer_address1":"19 NE 13H CRT",
"trainer_address2":null,"CITY":"MII","STATE":"AL",
"trainer_zip":"33333","trainer_phone":"(721)222-4444","trainer_fax":null,
"trainer_cell":"(213)213- 2133","website_trainer_id":115,"trainer_email":"MO#gmail.COM",
"trainer_group":"","inactive":null}
Any help would be greatly appreciated.
EDIT
Here is the php that returns that json:
$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
$return[] = json_encode($row, JSON_FORCE_OBJECT);
}
echo json_encode($return);
I have to loop through and encode each row because, otherwise, the ajax function doesn't think there is json that is returned (and my data var is empty)
Your real issue is in your PHP:
$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
$return[] = json_encode($row, JSON_FORCE_OBJECT);
}
echo json_encode($return);
You are double json_encoding your data, which is causing the inner JSON to be treated as a string in JSON form when returned to your Javascript.
You should be doing it as follows:
$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
$return[] = $row;
}
echo json_encode($return);
Notice I've removed the innermost json_encode.
Now, you don't need to use the .parseJSON() call in your Javascript. This solution will be much more efficient than the accepted solution, which didn't address the real problem.
It will be more efficient because
You aren't double encoding data that doesn't need to be encoded in
PHP.
You aren't decoding data that didn't need to be encoded in
Javascript.
Thus, you eliminate 2 needless operations, and many wasted cycles (because those operations are contained within loops).
data[0] looks like JSON, so you'll have to parse it before you can use it as an object. e.g. $.parseJSON(data[0]).id
It looks like it is just a single object being returned rather than an array so you should be able to access the id property using data.id , no need to specify an array index.
Try adding "Content-Type: application/json" to your response headers. Adding this header Google Chrome, Opera, Safari and IE will automatically convert your string to a JSON oject.
The parseJSON will only be needed on Firefox if you add this header.
If you don't wish to add that header then "JSONObject = jQuery.parseJSON(response);" is required in your javascript to convert the string to a JSON object.