I cannot send JSON Data from HTML to PHP with jquery and always show fail status at console.log. Please check my code.
jsonObjects.domain = client_domain;
jsonObjects.pkg = client_package;
jsonObjects.company_name = client_company;
jsonObjects.company_email = client_email;
jsonObjects.personal_name = psn_name;
jsonObjects.personal_phone = psn_phone;
jsonObjects.personal_email = psn_email;
var JsonPush = new Array();
JsonPush.push(jsonObjects);
var JsonArray = JSON.stringify(JsonPush);
$.ajax({
type: "POST",
url: 'order.php',
data: JsonArray,
dataType: 'json',
})
.done(function (data) {
console.log('done');
console.log(data);
}).
fail(function (data) {
console.log('fail');
console.log(data);
});
Order.php file
<?php
$decoded = json_decode($_POST['data']);
var_dump($decoded);
?>
You don't need to stringify first, just post it in a keyed object and access via the key like this
let postData = { object: jsonObjects };
$.ajax({
type: "POST",
url: 'order.php',
data: postData,
dataType: 'json',
})
Then in php:
$jsonObjects = $_POST['object'];
note: you don't access the posted variable by the name of the object itself but rather the keys inside the posted object
You have no data parameter in your AJAX call. It should be:
data: { data: JsonArray },
But there really isn't any need to use JSON at all. You can just given an object as the data: option, and its properties will become POST parameters.
data: jsonObjects,
Then in PHP you can access $_POST['domain'], $_POST['pkg'], etc.
Related
I pass the variable javascript method by ajax post method to the php file in this way:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: 'php/file.php',
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
name: name,
time: time
},
success: function(response){
console.log(response);
}
});
});
Request Payload in my Browser returns: name=Adrian&time=00%3A01%3A59. What should I write in the file file.php to send variables using sql query to my mysql database?
You can make good use of php explode() method here:
$string = name=Adrian&time=00%3A01%3A59
$parameters = explode("&", name=Adrian&time=00%3A01%3A59)
This will give you an array $parameters:
($parameters[0] == name=Adrian,
$parameters[1] == time=00%3A01%3A59)
Now you can get the name and time from $parameters:
$name = explode("=", $parameters[0])[1];
$time = explode("=", $parameters[1])[1];
I am tying to pass a javascript variable as an ajax paramater but it is being sent as null. Simply passing 'host' gives 'host' itself which isn't what is desired
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: '{'
hostname '=' + host '}',
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
Try the following:
data: {'hostname' : host},
Pass the data as an object, using key you can access the value of the variable on the server side.
USE:
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: {
"hostname": host
},
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
If you are trying to send data as a string make use of JSON.stringify()
dataToSend = JSON.stringify({ "hostname": host });
And in your AJAX
data : dataToSend
I feel the problem is you have made the wrong JSON data format.
the correct JSON format should be like this:{key:value}
Give an eg. here:
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
ex:the employee contains 3 elements
Wish can make some help :)
I'm trying to get back a json object from php to then use in my ajax.
My ajax is
$( document ).ready(function() {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
success: function(data) {
var json = JSON.parse(data);
$('#eventInformation').html(json[table]);
}
});
});
and then my php does stuff but I basically want to return a string (plus more, but getting the string to work first would probably help the rest):
$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);
But the line
$('#eventInformation').html(json[table]);
seems to only give me back an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
What am I doing wrong?
first, use the Network Monitor to see the result of the HTTP request
e.g. in Firefox : https://developer.mozilla.org/en-GB/docs/Tools/Network_Monitor
then, try this code who let jQuery do the JSON parsing in the AJAX call :
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
result: "json"
success: function (dataJson) {
$('#eventInformation').html(json.table);
}
});
});
Try to use . operator, also there is no need to parse the JSON string it is already in JSON form :)
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
success: function (data) {
$('#eventInformation').html(data.table);
}
});
});
ON PHP, ensure that you are instantiating the response data like below
$obj = new StdClass;
$obj->table="hey";
First of all you should check the response is properly parsed as json. if any data is present before the json array, javascript will throw exceptions. Use the chrome's developer tools response tab in the network option for seeing the response. If it's ok , try the below code.
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
method: "get",
url: eventsListPath,
dataType : "json",
data: {}, //data
success: function (data) {
$('#eventInformation').html(data.table);
}
});
});
I have a function that includes an AJAX to send a JSON object retrieved from localStorage. For some reason, in my PHP script, it never shows anything in the $_POST variable, despite me being pretty sure the AJAX call goes through successfully. My code is as follows:
The javascript:
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
dataType: 'json',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
The php script:
if(isset($_POST['answers'])){
$obj = json_decode($_POST['answers']);
print_r ($obj);
}
Any help as to why this isn't working would be greatly appreciated. Thank you.
I've tried all of the options given so far, and nothing seems to be working. I'm at a total loss.
For those asking, the finalResult variable is structured as:
[{"answer":0,"elapsed_time":1378,"stimulus_id":"8","task_id":1},{"answer":1,"elapsed_time":157,"stimulus_id":"2","task_id":1},{"answer":1,"elapsed_time":169,"stimulus_id":"1","task_id":1}, etc....
dataType: 'json' requires that what you output in PHP (data accepted in success section) must be valid json.
So valid json will be in PHP:
if(isset($_POST['answers'])){
echo $_POST['answers'];
}
No need to decode it, it is json string already. No var_dump, no print_r
I would remove the dataType property in your Ajax request and modify the structure of your data :
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: 'answers='&finalResults,
success: function(data){
console.log(data);
console.log('Success');
}
})
And in a second time I would test what I receive on PHP side :
if(isset($_POST['answers'])){
var_dump(json_encode($_POST['answers']));
}
Remove dataType: 'json', if you sending with JSON.stringify
JS.
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
PHP CODE:
if (!empty($_REQUEST['answers'])) {
$answers = json_decode(stripslashes($request['answers']));
var_dump($answers);
}
In data from server I get the following JSON:
{
"response": {
"upload_url": "http:\/\/cs9458.vk.com\/upload.php?act=do_add&mid=6299927&aid=-14&gid=0&hash=73e525a1e2f4e6a0f5fb4c171d0fa3e5&rhash=bb38f2754c32af9252326317491a2c31&swfupload=1&api=1&wallphoto=1",
"aid": -14,
"mid": 6299927
}
}
I need to get upload_url. I'm doing:
function (data) {
var arrg = JSON.parse(data);
alert(data.upload_url);
});
but it doesn't work (alert doesn't show).
How do I get parameter upload_url?
It looks like you need to access arrg, not data. Also you need to access the 'response' key first.
function (data) {
var arrg = JSON.parse(data);
alert( arrg.response.upload_url);
}
There are several correct answers here, but there is one trigger that decides how you should handle your returned data.
When you use an ajax request and use JSON data format, you can handle the data in two ways.
treat your data as JSON when it returns
configure your ajax call for JSON by adding a dataType
See the following examples:
returned data string:
{"color1":"green","color2":"red","color3":"blue"}
ajax call without dataType:
$.ajax({
method: "post",
url: "ajax.php",
data: data,
success: function (response) {
var data = JSON.parse(response);
console.log(data.color1); // renders green
// do stuff
}
});
ajax call with dataType:
$.ajax({
method: "post",
url: "ajax.php",
dataType: "json", // added dataType
data: data,
success: function (response) {
console.log(response.color1); // renders green
// do stuff
}
});
In your case you probably used JSON.parse() when the call was already configured for JSON. Hope this makes things clear.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Your code has a small error. try:
function (data) {
var arrg = JSON.parse(data);
alert(arrg.response.upload_url);
});