I am trying to send data using AJAX to PHP page. I am getting all the data from the form and I am trying to convert it to JSON. However, .stringify() doesn't do the job for me.
Here is my code:
<script>
$(document).ready(function(){
console.log("Ready..");
$("#profile-form").submit(function(event){
var data = $(this).serialize();
console.log(JSON.stringify(data));
$.ajax({
type : "POST",
url : "profile.php",
data : JSON.stringify(data),
success : function(response){
alert(response);
}
});
});
//$("#profile-form").submit();
});
</script>
I am able to see the form-data on the console. However, I am not getting any JSON data on the server. I have just done print_r($_POST['data']) in my profile.php page. However, it says variable data not defined.
since you already serialize your data. no need to use JSON.stringify it.
also add an option dataType : json
$.ajax({
type : "POST",
url : "profile.php",
data : data,
dataType : 'json',
success : function(response){
console.log(response);
}
});
also on your PHP. you should do
print_r($_POST);
There should be no $_POST['data'] available because the data you are sending is saved directly in $_POST variable, which should be accessible with print_r($_POST) or print_r(json_decode(print_r($_POST))) (since you have stringified it.)
According to documentation,
The .serialize() method creates a text string in standard URL-encoded notation.
Just something like single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1
It is not what you want, actually.
You can simply generate a JavaScript object and serialize it:
$.ajax({
type : "POST",
url : "profile.php",
data : 'data=' + JSON.stringify({
"name": $("#name").val(),
"password": $("#password").val()
})
}).done(function(dt) {
});
At the server-side, $_POST['data'] will contain the JSON representation of your form.
It may be automated. Read these articles on how to do the universal solution:
Convert form data to JavaScript object with jQuery
Serialize form data to JSON
Related
I am looking for get json response from third party website. Its providing me json data when I call with ajax. Its fine. I am looking for pass same json data to my PHP file. so I can decode that json data and can store in MYSQL database. So for I am trying like this
<script>
$("#diary").click(function(){
$.ajax({
type:'get',
url:'https://example.com,
data:{
},
dataType:'json',
success:function(result){
console.log(result);
$.ajax({
type: "POST",
url: "dd.php",
data:result,
dataType: "json",
success: function (msg) {
console.log(msg);
}
});
}
});
});
</script>
Its working for get data from third party site but in my php page, I am not receiving proper data so json_decode function not working. May be I am not posting correct json data to PHP page. I am not able to use CURL in PHP because its giving me connection error, its possible that third party site have some security function which does not allow me to connect via CURL so ajax is the only method for get data.
My PHP file is like below
<?php
$ajax = json_decode(file_get_contents('php://input'), true);
print_r($ajax);
?>
Let me know if anyone here can help me for solve my issue.
Thanks!
You need to call JSON.stringify() on the result and pass that through data in your ajax request. You are just sending a string that happens to be JSON data. In PHP you can call json_decode() on $_POST['data'] and you should have your data.
I have a simple script that gets the value of a textarea and posts this via AJAX. If I post "??" I get strange values. If I log out the value it retrieves before posting it all is correct. But the POST data my script receives includes the jQuery version number. My code and results are are below. Should I be escaping this somehow ?
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
My post data comes through as "jQuery17106460378167700797_1345234676316" for the value of text.
It's a POST request, not GET, and should be:
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data: {text : value}, //object
dataType:'JSON',
success:function(data){
}
});
PHP
$value = $_POST['text'];
Also, setting the dataType to JSON evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner, any malformed JSON is rejected and a parse error is thrown. This means any malformed JSON, and your ajax call will fail.
I am not sure when you are executing the script, is it on button press?
If not, you will need to wrap it so that it runs only after DOM had completed loading:
$(document).ready(function()
{
var value = $("#textarea").val();
$.ajax({
url:'index.php',
type:'POST',
data:'text='+value,
dataType:'JSON',
success:function(data){}
});
});
I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)
How do I send AJAX data through $.ajax() in JavaScript via type: "POST" using JSON data formatting and how do I receive the data in a PHP script (through $_POST??) and put it into an array so I can use it? I've been kicking at this for hours and I have no idea what I'm doing wrong. If someone could post the JS and PHP code for sending and receiving JSON formatted data, I would be eternally grateful!!!!!
JS Code:
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"value1": 1,
"value2": 2,
"value3": 3,
"value4": 4,
"value5": 5
},
dataType: "json"
});
PHP Code:
I was just using $_POST["value1"], etc., to get that value. On that note, is there a way to make the ajax request GET instead AND open up a new window with that GET data on it so I can see what's going on??
The idea is to create a php page the outputs data in JSON form. This data is taken from an array and echoed using the json_encode function. Using the $.ajax() method from jQuery, you send a request to that page and manipulate the data in the success: function.
Example.
PHP - array.php
$array = ("flag" => 1);
echo json_encode($array);
JavaScript
$.ajax({
url : '/array.php', // page containing JSON data
dataType : 'json', // must be specified for JSON manipulation in success
success : function(data) {
// this function is called if the call to test.php is successful
// access the data using object dot syntax
alert(data.flag); // should display '1'
}
});
// Send data to server this way
PHP - test.php
echo $_POST['data'];
JavaScript
$.ajax({
url : '/test.php',
dataType : 'text',
type : 'post',
data : { data : 'Hello, World!'},
success : function(data)
alert(data); // should display 'Hello, World'
}
});
As far as I know you can't POST data in a JSON format. Only as a query string, like GET. You can however return data from the PHP script in a JSON format.
Eg.
$.ajax({
url: "script.php",
dataType: 'json', // Tell jQuery/JS that the returned data from script.php is JSON format
data: 'id='+Id, // will become $_POST['id'] with the value of Id (js var)
success: function(data){
// data is JSON formatted
}
Now, in your PHP script, you receive a POST variable called $_POST['id'].
Let's say that $_POST['id'] is needed to request a certain customer from the database. Its data can be stored in an array and then json encoded and then send back to the page with the ajax request.
I have a simple jquery script as follows:
$('a').click(function()
{
//get the id of the song we want to play
var song_id = $(this).attr("id");
//do a get request to get the information about the song
$.get("http://www.site.com/v4/ajax/get_song_info.php", { id: song_id, }, function(data)
{
alert("Data Loaded: " + data);
});
//alert( song_id );
});
I have gotten it to work and it returns several bits of data 'artist' 'title' 'song duration' and so on.
How do I process my 'data' so I can then update my page with each bit. In this case I want to set a series of '' to hold each of the values returned.
Thanks.
Best practice would be to use a JSON encoding.
Whatever server-language you are using, encode your data as JSON object and send it with
the mime-type application/json.
Javascript/jQuery side make a call to .getJSON() which is aquivalent to
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
However, if you are using jQuery 1.4.x, you now have a JSON object in your data variable.
In a previous version you need to explicitly parse the incoming data into a JSON object. For instance
if(window.JSON) data = window.JSON.parse(data);
This will create a valid Javascript Object which you can treat and access like
data.artist
(Of course you need to create such an object structure serverside before sending)