I send data from javascript to PHP like this:
$.ajax({'url': 'my.php',
'type': 'POST',
'data': JSON.stringify(update_data),
'success': function(response) {
alert(response);
}
});
Using HTTPFOX Firefox plug-in I see the following data in the POST DATA tab:
{"file_id":["1","2","3"],"description":["lala","kuku","wow!"],"tags":[["julia","paper"],["Very nice car"],[]]}
however, if I do in my.php print_r($_POST) I see an empty array. Why is that ? How could I collect the data ?
The data needs to be in the form name=value.
try...
$.ajax({'url': 'my.php',
'type': 'POST',
'data': 'mydata=' + JSON.stringify(update_data),
'success': function(response) {
alert(response);
}
});
Then you should have your json string in $_POST['mydata']
You'll then need to use json_decode to actually get at the individual values in your string.
http://php.net/manual/en/function.json-decode.php
The response you are getting is in JSON format. Use the json_decode function to convert it to array.
print_r(json_decode($_POST['description'], true));
I'd expect your data to be in $HTTP_RAW_POST_DATA. Then json_decode to make sense of it.
Related
I'm passing a simple JSON array with 4 words to PHP. I want to store that array in a database after I serialize it. Since it's an Ajax call I can only investigate any echoed values by json_encode and alerting them in AJAX success function.
Here's my code:
var jsonString = JSON.stringify(ans);
//if I alert jsonString - it shows the proper array
$.ajax({
type: "POST",
url: "script.php",
data: jsonString,
cache: false,
success: function(data){
alert(data);
},
error: function(){
alert("error");
}
});
That's what I do in PHP with the array:
$answerAr = json_decode($_POST['data']);
$answers = serialize($answerAr);
If I echo the json_encode($answerAr) it alerts NULL in Ajax and $answers turns into 'N;'
Json_last_error returns 0.
If you're posting data directly to PHP, you'll have to use php://input and parse that; data given in JSON isn't form data, and wont auto-populate the request superglobals ($_GET, $_POST).
$data = json_decode(file_get_contents("php://input"));
Most frameworks do this transparently for you and populate a request object with data in it. You should probably check if the request sends JSON data in the body via headers (Content-Type, Accept: application/json, etc)
Alternatively, you can change your AJAX call to give it an array key:
$.ajax({
data: {data: jsonString},
// etc
});
Which will then be accessible as $_POST["data"]
Change your ajax data attribute to like this and try
data: {json: jsonString}
and in the php script you can access it by
$answerAr = json_decode($_POST['json']);
I have the below code running to send data as a JSON object
var jdata = JSON.stringify(grid.serialize());
$.ajax({
'type': 'POST',
'url': 'print.php',
'data': jdata, //assuming you have the JSON library linked.
'contentType': "application/json",
'success': function (data) {
alert(data);
},
'error': function (x, y, z) {
alert(x.responseText);
// x.responseText should have what's wrong
}
});
alert(JSON.stringify(grid.serialize()));
Currenty the alert after the ajax function prints
[{"id":"1","col":"1","row":"1","size_y":"1","size_x":"1"},{"id":"2","col":"2","row":"1","size_y":"1","size_x":"1"}]
On the receiving page I am using <?php print_r($_POST) ?> to see what the page is being sent and it keeps outputting
Array
(
)
I must be missing something simple but have been unable to figure out what. Maybe a fresh set of eyes will see a simple mistake I have made.
I think $_POST is only populated if you send the data encoded as x-www-form-urlencoded. So, just assign the JSON string to a key (jQuery takes care of encoding it properly):
'data': {data: jdata}
and remove the 'contentType': "application/json" part.
Then you get the data in PHP with:
$data = json_decode($_POST['data'], true);
Alternatively, get the raw body of the request in PHP and process it: How to retrieve Request Payload
If you are sending JSON to the server, on the back-end grab your JSON using:
json_decode(file_get_contents('php://input'));
It won't be in the $_POST super global.
I want to manipulate a PHParray in javascript. This is the code i'm using.
Array.php
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
?>
fx_funciones.js
/*Pre-sentences*/
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
}
});
This is what I want to do but it's not working.
I think , the answer for above question is already addressed in below link. please check them out.
Get data from php array - AJAX - jQuery
I hope it will help you
Try this:
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
echo json_encode($sentido);
And:
$.getJSON('array.php', function(sentido) {
console.log(sentido);
});
You'll need to return the array from your PHP code as JSON, using the json_encode function. Then, in your jQuery code, specify a json dataType so that it's implicitly converted and passed to the callback function as an array:
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
},
dataType: 'json'
});
Use the standard JSON notation. It serializes objects and arrays. Then print it, fetch it on the client and parse it.
On the server:
echo json_encode($sentido);
For more on PHP's json_encode: http://php.net/manual/de/function.json-encode.php
On the client, this is specially easy if you use the jQuery function for ajax that expect JSON-encoded objects, and parses them for you:
$.getJSON('address/to/your/php/file.php', function(sentidos) {
alert(sentidos[0]); // It will alert "ver"
alert(sentidos[1]); // It will alert "tocar"
});
It uses GET but this most probably what you need.
For more on jQuery's $.getJSON: http://api.jquery.com/jQuery.getJSON/
I can't figure out how to get a bunch of MySQL rows into a JSON data structure and iterate each of the row fields in java script.
Here is my query in codeigniter
function get_search_results() {
//$this->db->like('title', $searchText);
//$this->db->orderby('title');
$query = $this->db->get('movies');
if($query->num_rows() > 0) {
foreach($query->result() as $movie) {
$movies[] = $movie->title;
}
}
return $movies;
}
Encode array for json
$rows= $this->movie_model->get_search_results();
echo json_encode($rows);
My jQuery AJAX request,
$.ajax({
type: "GET",
url: "publishlinks/search_movies",
data: searchString,
...
This is how I've been trying to traverse rows in the java script. It is iterating over every character: 1 t 2 h 3 e 4 g ... 7 e
I need this: 1 the game 2 lost 3 you
success:
function(result) {
$.each(result, function(key, val) {
alert(key + ' ' + val);
})
//alert(result);
}
It looks like it is treating the result as a string instead of parsed JSON, hence iterating over it as if it was a string. This could mean that it isn't returning a clean JSON encoded string in the response, so I'd check the response to make sure it is valid JSON. jQuery is supposed to intelligently guess the content type and parse accordingly.
You could also try the dataType: "json" option on the ajax request to force it to be parsed as JSON instead of letting jQuery guess.
Use the dataType property of $.ajax
$.ajax documentation
dataType
"The type of data that you're expecting back from the
server."
Use firebug to find the type of the response variable. In your case the response is string but it should be Array (or Object?)
If you don't want jQuery to automatically eval the json then live it as it is and in the success function add the following:
var parsed = $.parseJson(response);
Here is the documentation of the parseJson method: parseJson
I think you problem is you don't fetch actual json but simple string response....
use $.getJSON or specify dataType as json in your jquery ajax request!
Do you return a JSON header with your PHP ?
header('Content-type: application/json');
Else try
result = JSON.decode(result);
before your "each" loop
Be sure to return proper content-type from your server side. For JSON that would be application/json.
$rows = $this->movie_model->get_search_results();
header('Content-type: application/json');
echo json_encode($rows);
Also add dataType: "json" to your jQuery request, just as beefsack said:
$.ajax({
type: "GET",
url: "publishlinks/search_movies",
data: searchString,
dataType: "json",
...
dataType: "json",
success:function(data){
var obj=$.parseJSON(data);
data=obj.data;
$.each(data,function(){
//json data
})
}
I don't understand one thing. If I want to get JSON data (key-value-pairs) from PHP to jQuery using Ajax, which of the following ones should I use?
$.get
$.post
$.getJSON
Do I need to use getJSON if I want to use json_encode in a PHP file? But what if I want to send with post (there is no postJSON)?
And one more thing:
In a PHP file I wrote:
<?php
if($_GET['value'] == "value")
{
$array['firstname'] = 'Johnny';
$jsonstring=json_encode($array);
return $jsonstring;
}
?>
In the jQuery file:
$.getJSON("php.php", {value: "value"}, function(data){
alert(data.firstname);
});
Why doesn't this work?
The problem lies with the line in PHP:
return $jsonstring;
You should echo it instead:
echo $jsonstring;
As for which jQuery method to use, I suggest $.getJSON() if you can return a pure json string. It really depends on how you use it.
When using $.getJSON(), your server file should return a JSON string. Thus echoing the string returned by json_encode() would be appropriate for the $.getJSON() method to take in the response.
You can use .ajax, this allows you to do both get and post.
I always use $.ajax.
$.ajax({
url: "script.php",
type: "POST",
data: { name : "John Doe" },
dataType: 'json',
success: function(msg){
alert(msg);
}
});
in PHP:
$name = $_POST['name']
echo $name
this will alert "John Doe"
also, if it's not working, use firebug to see values being passed around.