I'm tring to post an array to PHP file using JSON. It does not work. The problem is nothing happens. If I decomment datatype:"json" then I get the alert (but without data).
This is my jquery code
var arr = new Array();
arr.push('1','Brussels|25');
arr.push('2','Antwerp|40');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "jsondecode.php",
data: JSON.stringify(arr),
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
And this is my PHP code (jsondecode.php);
<?php
$array = json_decode($_POST["arr"]);
foreach($array as $el){
$el_array=explode('|',$el);
echo"City=".$el_array[0]." And Age = ".$el_array[1]."";
}
?>
Does somebody know a useful tutorial on this?
You have to post the data in this format to retrieve like $_POST["arr"]
data: { arr : JSON.stringify(arr) },
What the heck are you trying?
It looks as if you are trying to put key-value-pairs to the JavaScript-Array with arr.push('1', 'Brussels|25'); expecting an array containing "Brussels|25" under the key "1" - but watch out, you are creating this array: ["1", "Brussels|25", "2", "Antwerp|40"].
If you want to send json, send json-data:
var arr= [{
"city" : "Brussels",
"age" : 25
},{
"city" : "Antwerp",
"age" : 40
}];
then your ajax call:
$.ajax({
type: "POST",
url: "jsondecode.php",
data: {arr: JSON.stringify(arr)},
success: function(data){
console.log("success:",data);},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
So you don't need to explode the data server-sided.
The server-sided script:
<?php
$data = json_decode($_POST["arr"]);
// will echo the JSON.stringified - string:
echo $_POST["arr"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach($data as $cityObject){
echo "City: " . $cityObject->city . ", Age: " . $cityObject->age . "<br/>";
}
?>
Hope, this helps you now.
#edit: By the way, use console.log() or console.error() instead of alert. Alert will cause scripts to pause until you click on ok and you cannot see objects in an alert.
#2nd edit: the script is now tested, I removed unnecessary code and added the server-sided code
Replace :
$array = json_decode($_POST["arr"]);
By:
$array = json_decode($_POST["arr"], true);
Worked for me:
JS:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "jsondecode.php",
data: JSON.stringify({"1": "Brussels", "2": "Antwerp"}),
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
PHP:
<?php
$p = file_get_contents('php://input');
$x = json_decode($p, true);
echo $x["1"];
?>
Related
I've been searching and searching, but unfortunately I can't find any answers that relates to my problem.
I'm having trouble to read data that I've sent through jQuery (ajax) in my PHP script.
jQuery:
$('.sendOrder').click(function(){
if (validateForm() == true) {
(function($){
var convertTableToJson = function()
{
var rows = [];
$('table#productOverview tr').each(function(i, n){
var $row = $(n);
rows.push ({
productId: $row.find('td:eq(0)').text(),
product: $row.find('td:eq(1)').text(),
size: $row.find('td:eq(2)').text(),
price: $row.find('td:eq(3)').text(),
quantity: $row.find('td:eq(4)').text(),
});
});
var orderObj = [];
orderObj.push({
name: $("#customerName").val(),
email: $("#customerEmail").val(),
phone: $("#customerPhone").val(),
order: rows
});
return orderObj;
console.log(orderObj);
}
$(function(){
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(convertTableToJson()),
success: function(ret) {
console.log(ret);
}
});
When I'm looking at Chrome it seems to be sent correctly with json:
[
{
"name":"Kristian",
"email":"kristian#example.com",
"phone":"12345678",
"order":[
{
"productId":"Prod #",
"product":"Produkt",
"size":"Str",
"price":"Pris",
"quantity":"Antall"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
},
{
"productId":"09",
"product":"Bokser",
"size":"2 meter (249kr)",
"price":"249,- eks mva",
"quantity":"1 stk"
}
]
}
]
In my sendData.php I've got it pretty plain:
<?PHP header('Content-Type: application/json');
echo json_encode($_POST);
The return I'm getting are:
[]
What am I doing wrong? What have I forgotten?
$_POST expects an identifier. In your AJAX you'll have to supply one, for example:
request = $.ajax({
url: 'shop/sendData.php',
type: 'POST',
dataType: 'json',
// note the change here, adding 'json' as the name or identifier
data: { json: JSON.stringify(convertTableToJson())},
success: function(ret) {
console.log(ret);
}
});
Then you should be able to see the JSON string in $_POST['json']
Solved by using file_get_contents("php://input") instead of post.
I.e
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
if (strlen($json_params) > 0 && isValidJSON($json_params)) {
$decoded_params = json_decode($json_params);
echo $decoded_params[0]->name;
}
Returned "Kristian"
I have a problem that puzzles me. I have an ajax function that sends a json object, and I see the JSON parsed in the F12 Chrome Headers, and I receive the success alert.
$(document).ready(function() {
var test = {'bob':'foo','paul':'dog'};
$.ajax({
url: "test.php",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(test),
success: function(data) {
alert("Bien: " + data);
},
failure: function(errMsg) {
alert("Mal: " + errMsg);
}
});
});
But in my PHP page I cannot see any POST, anything. I can see that my post is received but anything else:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "post"; //Result 'post'
}
foreach( $_POST as $stuff ) {
echo $stuff; //Nothing at all
}
print_r(json_decode($_POST["data"], true)); // Undefined index: data
In the same code I use
$.post( "test.php", { data: { name: "John", time: "2pm" } } );
and works, then is something related with the code, but I cannot really see waht is it.
Thank you for your help!
try this instead
$results = json_decode(file_get_contents('php://input'));
echo $results->bob //Result foo
Hi i'm trying to get this with jquery ajax but don't know if i'm doing it correctly...
Really tried everything and basically had to look at jquery.ajax for dummies but still not getting it to work...
function addMix(mix) {
alert(mix);//Here I get my array of int's
var myArr = JSON.stringify(mix);
$.ajax({
type:"POST",
dataType: "json",
url: "add.php",
data: myArr,
success: function(data) {
alert("Success: " + data);
console.log(data);
},
error: function(x,y,z){
alert("Error: " + x + ", " + y + ", " + z);
console.log(x, y, z);
},
complete: function(data){
alert("Complete: " + data);
console.log(data);
}
});
}
the php:
<?php
header('Content-Type: application/json');
include "con.php";
$mix = json_decode($_POST);
foreach($mix as $index => $val){
$temp = array();
foreach($temp[$index] as $key => $value){
array_push($temp, $value);
}
}
$sql = "INSERT INTO mg_test(value)
VALUES('$temp')";
mysql_query($sql);
echo json_encode($temp);
mysql_close($con);
?>
Only thing im getting in return is,
alert(mix) = 2,1,3,2
Success: null
Complete: [object Object]
And I get nothing in the DB...
Could anyone point me in the right direction? What am I doing wrong?
Why do you do JSON.stringify(mix) in the $.ajax call?
You can just put the object / array or what it is there!
Here's a fixed JS:
function addMix(mix) {
$.ajax({
type:"POST",
dataType: "json",
url: "add.php",
data: { mix: mix }, // <--- this
success: function(data) {
alert("Success: " + data);
console.log(data);
...
});
}
And in PHP, you must use
$mix = json_decode($_POST['mix']);
instead of:
$mix = json_decode($_POST);
Also, I am pretty sure this query won't work:
$sql = "INSERT INTO mg_test(value) VALUES('$temp')";
$temp is an array - you will have to build the query of it, not just put it there and hope it will magically work. It won't.
Based on $.ajax documentation:
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}.
Just skip the stringify and pass the object as it it in the data field.
You are sending data to ajax call wrongly. Donot use JSON.stringify(), instead send request parameters like this.
type:"POST",
dataType: "json",
url: "add.php",
data: { "requestData": mix },
success:function(data){
console.log(data);
}
In PHP file. get this as
$mix = json_decode($_POST['requestData']);
dont alert an object alert("Complete: " + data); it (as you see) returns [Object Object]. so what says the console.log(data);?
If you want to see your objects while using
console.log(data);
It would be much better readable in Google chrome console.
I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);
I'm using this jQuery code:
$.ajax
({
type: "POST",
url: "customerfilter.php",
data: dataString,
cache: false,
success: function(html)
{
$(".custName").html(html);
}
});
How can i do something like this: $(".projDesc").html(html1);
So i can split the returned results into two html elements?
echo "<p>" .$row['cust_name']. "</p>";
thats the PHP i'm using and i want to echo another statement which i can put into another HTML element
Does this make sense?
Use json_encode() to convert an associative array from PHP into JSON and use $.getJSON(), which will return a Javascript array.
Example:
<?php echo json_encode(array("a" => "valueA", "b" => "valueB")); ?>
In Javascript:
$.getJSON("myscript.php", function(data) {
alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b);
});
Make your response return JSON, you'll need to change your jQuery to this, so the expected dataType is json:
$.ajax
({
type: "POST",
url: "customerfilter.php",
dataType: 'json',
cache: false,
success: function(data)
{
$(".custName").html(data.message1);
$(".custName2").html(data.message2);
}
});
Then you need to encode your response as a JSON Array:
<?php echo json_encode(
array("message1" => "Hi",
"message2" => "Something else")
) ?>
Why don't you return a JSON object. This way you can easily put many different results inside the ajax response.
You can use a separator and join the values like this in your response
echo $value1.'|'.$value2;
Now you can use JavaScript method split("|") as below:
var myarray = response.split("|");
var value_1 = myarray[0];
var value_2 = myarray[1];