I am new to web services.I have the following code and when I try to run it on the local host I am not geting the required output...it shows FirstName:undefined LastName:undefined..
following is my code
$(document).ready(function(){
var employees = [
{ "firstName":"John" , "lastName":"Doe" }
];
$.ajax({
url: "MyService.php",
type: "POST",
data: employees,
dataType: "json",
success:function(data) {
alert("Firstname:"+data.firstName+", LastName: "+data.lastName);
},
error:function(data) {
alert('error');
} });
});
The php code is
echo json_encode($_POST);
The value of data should be an object. You are passing an array containing an object. Get rid of the array.
This:
var employees = [
{ "firstName":"John" , "lastName":"Doe" }
];
… is submitting the following to the server:
undefined=
It should be:
var employees = {
"firstName": "John",
"lastName":"Doe"
};
which would submit this:
firstName=John&lastName=Doe
Additionally, you don't appear to be specifying a Content-Type header, so PHP is defaulting to text/html. This is forcing you to write JavaScript that says "Don't believe the server, threat this as JSON and not HTML".
You can fix that with:
header('Content-Type: application/json');
echo json_encode($_POST);
Related
An example of how my JSON data is like:
$scope.a = [{
"email": "keval#gmail",
"permissions": {
"upload": "1",
"edit": "1"
}
}, {
"email": "new#aa",
"permissions": {
"upload": "1",
"edit": "1"
}
}];
I want to post the same, and here's my approach:
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: {
mydata: $scope.a
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});
And the PHP is to take the request and respond:
echo $_POST['mydata'];
I tried JSON.stringify before the call and json_decode while echoing it back; still didn't work. Been trying all the possibilities I can think of, and what I find on the web/other questions, but still not working.
I've made plnkr for you
http://plnkr.co/edit/K8SFzQKfWLffa6Z4lseE?p=preview
$scope.postData = function () {
$http.post('http://edeen.pl/stdin.php', {user:$scope.formData}).success(
function(data){
$scope.response = data
})
}
as you can see I'm sending a raw JSON without formating it, then in php
<?php
echo file_get_contents('php://input');
I read the JSON directly and echo it but you can do whatever you want
read more about php://input here http://php.net/manual/en/wrappers.php.php
I was using it for a long time for REST services to avoid transforming JSON to string to many times
I use this, with which I can send Array JSON:
var array = {}
array['key1'] = value1;
array['key2'] = value2;
$http.post(URL, array)
.success(function(data){
})
.error(function(){
});
try using $httpParamSerializer or $httpParamSerializerJQLike
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: $httpParamSerializer($scope.a),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});
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"];
?>
I have been searching for hours and haven't found any solutions for my problem.
This is my jQuery/Ajax code:
$(document).ready(function() {
$(".submit_btn").click(function () {
var name = $("input#name").val();
var dataString = 'query='+$("#query").val()+'&facebook='+facebook+'&twitter='+twitter;
$.ajax({
type: "POST",
url: "selectDataSets.php",
dataType: "json",
data: dataString,
success: function(data) {
alert ("hello");
}
});
return false;
});
});
Now my selectDataSets.php code:
<?
include_once 'config.php';
if ((isset($_POST['facebook'])||isset($_POST['twitter']))&&isset($_POST['query'])) {
$elements=0;
$dataSet=array();
$tt=array();
$fb=array();
mysql_connect($config['database_url'], $config['database_user'], $config['database_password']) or die(mysql_error());
$queries = explode(";", $_POST['query']);
foreach ($queries as $query){
if(isset($_POST['facebook']) && $_POST['facebook'] == true){
mysql_select_db("facebook") or die(mysql_error());
$mysql_query = "SELECT * FROM page WHERE lower(name) LIKE '%".mysql_real_escape_string(strtolower($query))."%'";
// Perform Query
$result = mysql_query($mysql_query);
while ($row = mysql_fetch_assoc($result)) {
$set = array(
"name" => str_replace("-","",$row['name']),
"likes" => $row['likes'],
"about" => $row['talkAbout'],
"source" => "Facebook (Page)",
"id" => $row["id"],
"query" => $query
);
$fb[$elements]=$set;
$elements++;
}
mysql_free_result($result);
}
}
mysql_close();
echo json_encode($fb);
}
With dataType: "json", the alert("Hello") does not work, as well as nothing that I add inside the success callback. Although when I remove dataType: "json", the alert works, but the variable data is not recognized as JSON (as I keep getting undefined when I try to do data[0].name), even though I have checked and data is on the format [ { "name: ... } ], which I guess is correct JSON. I don't know what else to do, as I have a similar (almost the same) code on another php file that works perfectly with the dataType: "json".
Thanks in advance!
Can you see the actual output of the PHP script/AJAX call using Chrome's network window?
Make sure there are no MySQL errors and stuff. The reason you get no error when you don't put dataType: "json" is because the JSON parser is not attempting to read your malformed JSON. For some reason, your example JSON is good but whatever AJAX is receiving is not good. From the network window, select your AJAX call and look at the response tab. This will show you the real output.
I have code working to pass JSON objects from Jquery to PHP page.
The problem is with sending Cross-domain requests, If i try
dataType:'json'
in jquery, it gives me a xhttp error (the security) error which I understand.
I also understood after reading this post that JSONP only works for GET methods
This is how I am creating and using my object:
function order(id, name) {
return {
id: id,
name: name
}
}
var orders= [];
orders.push(order("123", "Lamb Kebab"), product("234", "Chicken"));
var jsonOrders = $.toJSON(orders);
$.post(
"process.php",
{orders: jsonOrders },
function(data){
$("#result").html(data);
}
);
What is the solution for me to pass a JSON object cross domain?
if that is not possible, what is an alternate solution ?
Please advise
Thanks
Edit:
Jquery code
function product(code, type) {
return {
code: code,
type: type
}
}
var products = [];
products.push(product("333", "Product one"), product("444", "Second product"));
var jsonProducts = $.toJSON(products);
$.ajax({
type: "GET",
url: "http://page.tld/foo.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data:JSON.stringify({products: jsonProducts}),
error: function (msg) {
//alert("error");
console.log("Error here" +msg);
},
success: function (msg) {
console.log("Success"+msg);
}
});
**
The error on PHP end is: Invalid argument supplied for foreach() in
....
**
PHP Code (simplified version)
<?php header("Content-type: application/json; charset=utf-8");
require_once('json.php');
if (isset($_GET['products'])) {
$products = json_decode($_GET["products"],"true");
foreach ($products as $product){
echo $_GET['callback'] . '(' .(json_encode($product["type"])). ')';
}
}
else
{
echo $_GET['callback'] . '(' .(json_encode("not found")). ')';
}
?>
it is going into the block where it is able to find $_GET['products'], is it a parsing error on my part? i am sure it is an obvious mistake but im not able to spot it.
real sorry about that
I used the GET parameter and decoded JSON on the PHP end.
I have the following data in a JS script:
$("#holdSave").live('click', function () {
var arr = {};
var cnt = 0;
$('#holdTable tbody tr').each(function () {
arr[cnt] = {
buyer: $(this).find('#tableBuyer').html(),
sku: $(this).find('#tableSku').html(),
isbn: $(this).find('#tableISBN').html(),
cost: $(this).find('#tableCost').val(),
csmt: $(this).find('#tableConsignment').val(),
hold: $(this).find('#tableHold').val()
};
cnt++;
}); //end of holdtable tbody function
console.log(arr);
$.ajax({
type: "POST",
url: "holdSave.php",
dataType: "json",
data: {
data: arr
},
success: function (data) {
} // end of success function
}); // end of ajax call
}); // end of holdSave event
I need to send this to a php file for updating the db and emailing that the update was done. My console.log(arr); shows the objects when I run it in firebug, but I can't get any of the information on the php side. Here is what I have for php code:
$data = $_POST['data'];
print_r($data); die;
At this point I am just trying to verify that there is info being sent over. My print_r($data); returns nothing.
Can anyone point me in the right direction please?
dataType: "json" means you are expecting to retrieve json data in your request not what you are sending.
If you want to send a json string to be retrieved by $_POST['data'] use
data: {data: JSON.stringify(arr)},
Use the json_encode() and json_decode() methods
Use the next way:
data = {key1: 'value1', key2: 'value2'};
$.post('holdSave.php', data, function(response) {
alert(response);
});
Note: haven't tested it, make sure to look for parse errors.