*Hi ,
I am very new to using JSON in Jquery. I have a html form which made out using json data and javascript. The Json string is holding the result. Now my question is how to send this string to php file. I am using ajax function for submitting the form *
this is the json string i have
var jsonstr = JSON.stringify(result);
$.ajax({ type:"POST",
url: "ajax.php",
headers: {
'Content-Type': 'application/json',
success: function(){
alert('Test results submitted!');;
Specify the data and dataType options:
var jsonstr = JSON.stringify(result);
$.ajax({
type:"POST",
url: "ajax.php",
data:'json=' + jsonstr,
dataType:'json',
success: function(){
alert('Test results submitted!');
}
});
From php, you can get json string using:
$_POST['json'];
Related
I have 2 ajax is an array and single char:
var jsonEncode = JSON.stringify(TableData); --> output: [{"name":"Ristha","age":"30"},{"name":"Niken","age":"25"}]
var code = $('#mutiplearray-code_reg').val(); --> output: 1RF46TA
How to send ajax post when I use 2 data like that:
$.ajax({
type: "POST",
data: "pTableData=" + jsonEncode + "code1=" + code,
success: function(msg){
// alert(msg);
},
});
When I get using in my controller:
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData, true);
$name1 = $tableData['name'];
$age1 = $tableData['age'];
$code1 = $_POST['code1'];
It's have error dev tool undefined code1 and pTableData?? What I'm do wrong with use multiple data in my ajax?
When I'm just using post data one of them is work correctly
Pass data as json. You passed the data as string.
$.ajax({
type: "POST",
data: {pTableData: jsonEncode, code1: code},
success: function(msg){
// alert(msg);
},
});
$.ajax({
type: "POST",
data:{'pTableData':jsonEncode,'code1':code},
success: function(msg){
// alert(msg);
},
});
In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);
This is the jquery ajax part in which i have sent json data to the php file.
$(function () {
$('form').submit(function () {
var fields = $(this).serializeArray();
var ans_json = JSON.stringify(fields);
console.log(ans_json);
$.ajax({
url: "results.php",
type: "POST",
data: ans_json,
dataType: "json",
success: function (result) {
console.log(result);
}
});
return false;
});
});
Now i want to use this json data sent to the php page.How can i do it? I have done it this way but it returns null.
<?php
echo json_decode('ans_json');
?>
I have a set of 10 questions which need to be answered. 3 questions were answered so got the below result.This is what i got in my console.
[{"name":"answer_9","value":"a"},{"name":"answer_10","value":"a"}] quizzes.php:14
null
You don't need to decode any JSON string at server-side if you encode properly your parameters.
You can use .serialize() to do the form serialization for you, and it's ready to send.
$(function () {
$('form').submit(function () {
var serialized = $(this).serialize();
$.ajax({
url: "results.php",
type: "POST",
data: serialized,
...
});
return false;
});
});
Your parameters will be available in your $_POST as in any normal POST request. For example,
$ninth_answer = $_POST["answer_9"];
You need to decode the POST variable. Currently you're decoding just a string which even isn't valid JSON.
<?php
$json_arr = json_decode($_POST['my_json'], true);
var_dump($json_arr);
echo "First name in json is:". $json_arr[0]['name'];
?>
and edit your javascript to reflect following:
This posts my_json parameter with your json as an value. This makes it easy for PHP to recieve it using $_POST.
$.ajax({
url: "results.php",
type: "POST",
data: {"my_json": ans_json},
dataType: "json",
success: function (result) {
console.log(result);
}
});
I suggest to read a little about those things:
http://api.jquery.com/jQuery.ajax/
http://ee1.php.net/manual/en/function.json-decode.php
I am trying to send a JSON to my PHP script and for some reason is returning null in the alert message.
I've searched throughout Stack Overflow and other forums and used other people's examples but somehow I keep getting it wrong. I checked in Firebug and the request is being sent. I am very new to handling JSON queries.
Could anyone point at what I am doing wrong so that I can learn for the next time?
My JQuery Code:
var name = $('#formName').val();
var regno = $('#formRegNo').val();
var charityinfo = $('#formCharityInfo').val();
var searchimprove = $('#formSearchImprove').val();
var finantialaid = $('#formFinantialAid').val();
var contactname = $('#formContactName').val();
var contactphonenumber = $('#formContactPhoneNumber').val();
var contactfaxnumber = $('#formContactFaxNumber').val();
var contactemail = $('#formContactEmail').val();
var website = $('#formWebsite').val();
var address = $('#formAddress').val();
var postcode = $('#postCode').val();
var arrayData = {"name":name,"regno":regno,"charityinfo":charityinfo,"searchimprove":searchimprove,"finantialaid":finantialaid,"contactname":contactname,"contactphonenumber":contactphonenumber,"contactfaxnumber":contactfaxnumber,"contactemail":contactemail,"website":website,"address":address,"postcode":postcode};
console.log(name);
$.ajax({
url: "test.php",
type: "POST",
dataType: "json",
contentType: "json",
async: false,
data: arrayData,
success : function(response) {
alert(response);
},
error: function(){
alert("error");
}
}); //End AJAX
My PHP Code:
<?php
$return = $_POST;
echo json_decode($return);
?>
first, collect your form data in 1 step, serialize it as json:
var arrayData = $('#my_form_id').serialize();
If you post your data, you should post the appropriate post variable name with it. Add some more decriptive error handling:
$.ajax({
url: "/test.php",
type: "POST",
data: 'mydata = ' + arrayData,
success : function(response) {
alert(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
And then on the php side pick it up:
$mydata = $_POST['mydata'];
$arrayData = json_decode($mydata);
var_dump($arrayData);
You haven't encoded the data you are sending as JSON. You are passing an object to jQuery and allowing it to encode it (as application/x-www-form-urlencoded). You need to encode your data as JSON and pass a string to data:.
json is not a content-type, application/json is.
$_POST is populated from application/x-www-form-urlencoded or multipart/form-data, it doesn't contain the raw post request. You need to use php://input to get that.
First of all you don't need to create json yourself
use JSON.stringify() function function to create JSON
or you can also use the jquery serialize() function
var arrayData=$("FORMID").serialize();
$.ajax({
url: "test.php",
type: "POST",
dataType: "json",
contentType: "json",
async: false,
data: arrayData,
.....
and decode this json serverside using json_decode() function
I'm calling a php script (getNum.php) via ajax after creating an object and using jquery.json to turn
it to json. Now i want to handle the object on the php side.
print_r($_POST['data']) doesn't work nor anything else i've tried.
This is my code:
// create object
var bing= new Object();
bing.id = 99;
bing.nameList = getBingList();
//create pdf
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "getNum.php",
dataType: "html",
data: $.toJSON(bing),
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
If you're using print_r($_POST['data']) to show the content, you'll need to send it as "data" as well.
$.ajax({
type: "POST",
url: "getNum.php",
data: {data: $.toJSON(bing)},
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
Otherwise you have to do print_r($_POST)
Since you are posting a JSON object directly, there is no argument name for $_POST. You'll need to read the raw contents of the POST request. Try this:
$data = json_decode(file_get_contents('php://input'));
print_r($data);