can anybody help to explain or give reference on how to send array of multiple array (or just array ) in jquery. and what the best way to do when something is failed or successfull. what i mean is how the php code send back the success or failed message
See this article for an example. Basically, you have to use PHP's json_encode() to convert a PHP array to JSON code. In the linked example, the jquery-json plugin is used to convert JSON back to a Javascript array.
Alternatively, you can use jQuery's built-in capabilities for retrieving a PHP response as a Javascript array/object.
Use JSON ENCODE
Something like this:
index.php
<script type="text/javascript" src="jsfile.js"></script>
<a href='numbers.php' class='ajax'>Click</a>
numbers.php
<?php
$arr = array ( "one" => "1", "two" => "2", "three" => "3" ); // your array
echo json_encode( $arr ); // encode it to json
?>
jsfile.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
alert(snippets); // your array in jquery
});
});
});
If it is a simple error message and always the same one, you can simply return that string e.g. "error" and test for that value in JavaScript. But I would recommend to send the complec data in XML or even better in JSON (because it is smaller and can be used without poarsing it in JavaScript). Just do this in your PHP:
if($error){
echo "error";
} else {
json_encode($complex_data);
}
If you want to put some information into your error, which I highly recommend, just return an error array encoded with JSON. So replace the echo "error" with this:
echo json_encode(array("error" => "your error message", "status" => "an optional error status you can compare in JavaScript"))
Than you just have to check if the "error" is found in the JSON returned from PHP.
Related
I need help getting PHP to read an array name INSTEAD of the content in the array.
I am using PHP to parse a JSON response from an API call.
If the user inputs something incorrectly the JSON will respond with
array(1) { ["error"]=> ...
If the API request is successful the JSON that is returned is
array(2) { ["message"]=> ...
This would be easy if the API provided a ["success"]=true/false, but instead it provides two completely different response on success or failure so I need PHP to be able to read the array names, instead of the array content.
I want to create an if statement in PHP based on the array name. I can pull the message from error or the message from message just fine, but I want PHP to check to see what the array title is called. I was thinking something like this...
$response = json_decode(file_get_contents($url), true);
if ($response[] == "error"){
echo "There was an error: ".$response["error"];
} else {
echo $response["message"];
}
If i understand correctly, you should test that the key is present in array
$response = json_decode(file_get_contents($url), true);
if(isset($response["error"])) { // errror }
if(isset($response["message"])) { // ok }
I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.
The issue
I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.
The scripts
This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.
The jQuery/Ajax part
$(document).ready(function(){
$.ajaxSetup({cache: false});
var interval = 30000;
// var ids = ['1','2','3'];
var ids = []; // This creates an array like this: ['1','2','3']
$(".player").each(function() {
ids.push(this.id);
});
setInterval(function() {
$.ajax({
type: "POST",
url: "includes/fetchstatus.php",
data: {"players" : ids},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}, interval);
});
The PHP part (fetchstatus.php)
if (isset($_POST["players"])) {
$data = json_decode($_POST["players"], true);
header('Content-Type: application/json');
echo json_encode($data);
}
What I'd like
After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3.
But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.
All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.
Could someone tell me what exactly I am doing wrong/missing?
Perhaps the answer is easier than I think but I can't seem to find out myself.
Best regards,
Peter
The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json.
You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).
And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:
$returningData = array(); // or 'false'
$data = #$_POST['players']; // # supresses PHP notices if key 'players' is not defined
if (!empty($data) && is_array($data))
{
var_dump($data); // dump the whole 'players' array
foreach($data as $key => $value)
{
var_dump($value); // dump only one player id per iteration
// do something with your database
}
$returningData = $data;
}
header('Content-Type: application/json');
echo json_encode($returningData);
Using JSON:
You can simply use your returning JSON data in jQuery, e.g. like this:
// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
console.log( index + ": " + value );
});
And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:
$data = array(
1 => array(
// data from DB for player with ID 1
),
2 => array(
// data from DB for player with ID 2
),
...
);
// [...]
echo json_decode($data);
What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.
In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.
print_r prints human-readable information about a variable
So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.
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);
I have an array stored in php: $cv1 = array('a','b');
As you can see in the code below, I am trying to get the respective data from the array then delegate it to two separate functions.
But the data returned from the php callback function is: 'Array' instead of 'a','b';
and result[0] gets 'A' result[1] gets 'r' etc.
Thanks for help!
js:
$('a').on('click',function(){
var cv = $(this).data('cv');
var url= '_php/myphp.php';
$.post(url,{contentVar:cv},function(data) {
result=data;
return result;
}).done(function() {
alert(result[0]);
$('#myDiv').html(result[1]);
});
});
php:
$cv1 = array("a","b");
$contentVar = $_POST['contentVar'];
if($contentVar == "cv1")
{
echo json_encode($cv1);
}
It's common in PHP for you to get "Array" instead of an actual array when it accidentally gets cast to a string. That's not what you're doing here though; we can test:
> $cv1 = array("a","b");
array(2) {
[0] =>
string(1) "a"
[1] =>
string(1) "b"
}
> json_encode($cv1);
string(9) "["a","b"]"
$cv1 gets encoded correctly.
You must be treating it like a string somewhere else:
> (string)array("a","b")
! Array to string conversion
string(5) "Array"
Also, why do you have two success callbacks in $.post? The 3rd argument is a success callback, which works the same as .done. Use one or the other (I recommend done) but not both.
You may also consider passing json as the last argument (dataType) so that jQuery knows what to expect and will properly decode the result.
Try to do something like this:
$.post(url,{contentVar:cv}
function(response)
{
alert(response[0]);
},'json'
);
You need to convert the json string format to a javascript object/array.
var result = $.parseJSON(data);
see this question jQuery ajax request with json response, how to? for more detail.
But there is something strange that, if is returning 'Array', the php is not converting the array to json, what happens if the ($contentVar == "cv1") return false? If you will return an array to javascript you need to convert to a string (and the json format is perfect for this).
I'm trying to pass an array in an ajax request, but apparently it doesn't work...
$.post("process.php", array,
function(data) {
document.getElementById("output").innerHTML = JSON.parse(data);
});
My question is, how to use the data sent in the process file?
The array is built like that: [key (0/1/2...)] => ["prod_id"]. The id varies.
I read somewhere using $_POST["key"]; would work, but it doesn't.
It'd be even better if I could just get the array as is in the process file.
process.php (really basic - just to check wether it's working or not.):
<?php
print($_POST["test"]);
?>
Try to pass {data: array} instead of array. The AJAX call expects an object.
You need to build an Object of array elements. for example:
You can also try like:
{ 'key[]': [1, 2, 3] }
OR
{ key: [1,2,3] }
Read more about $.post()
In order to receive data in php you need to send key/value pairs, however you are only sending a value.
You receive in php with $_POST[key] which will return the value for that key.
JS:
$.post("process.php", {myAray: array}, function(data) {
$("#output").html(data);
});
php
$array= $_POST['myArray'];
To return this array from php as text just to test your ajax can use var_dump( $_POST) or var_dump($array);
If you intend to receive JSON in response from server, you do not need to use JSON.parse , jQuery will parse json internally. However you would need to add "json" as dataType argument to $.post
$.post("process.php", {myAray: array}, function(data) {
/* loop over json here*/
},'json');
if you want to pass an array, you have to "prepare" the key as following:
{'key[]' : ['value1', 'value2', 'value3']}
the same way you'd do it, when you want to pass an array in a form and set the name-attribute to "key[]".