AJAX, POST, JSON, and PHP: How do I do it? - php

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.

Related

POST ajax json response to PHP

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.

How to convert form data into JSON (Beginner) in jquery?

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

How to retrieve values from a JSON Object in PHP

I've tried this many times now, using difference methods and none of them have worked for me, so I'm asking this question.
I have a small form that takes in 4 pieces of information, a persons title, first name, middle name and last name. When I hit a button, a JSON Object is formed, and sent as post data through a jQuery.ajax method.
JSON Sent to PHP file:
{
"title": "Mr",
"firstName":"Banana",
"middleName":"Slippy",
"lastName":"McDougle"
}
Ajax call on button press:
function insertPerson(obj, callback){
$.ajax({
type: "POST",
data: "json=" + JSON.stringify(obj),
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
}
I pass in a Javascript Object that is then stringyfied and posted as a parameter name 'json'.
In my php file I assign the posted string to a variable, name $json, I then decode using json_decode(), do some funky business, and send a response back to the browser.
insertData.php:
require ('connect.php');
header('Content-type: application/json');
$json_string = $_POST['json'];
$json = json_decode($json_string);
...do server related inserts/selects etc...
echo json_encode($json->title);
At the moment I just want to return the title property of the json object that was sent in the post request, but anything I return comes back as null. If I echo back the string, without decoding it, then I get the following:
{\"title\":\"Mr\",\"firstName\":\"Banana\",\"middleName\":\"Slippy\",\"lastName\":\"McDougle\"}
If I try to extract values using:
$title = $json->title;
and put that into a MYSQL statement, it's inserted as null or blank, nothing gets input.
Am I doing something wrong? Or have I somehow got an outdated version of PHP to handle JSON? And help is greatly appreciated.
Why do you want to send JSON to the PHP script? What's wrong with using a query string?
$.ajax({
type: "POST",
data: obj,
url: "insertData.php",
success: function(obj){
if (callback){ callback(obj) };
},
error: function(error){
console.log("Error:");
console.log(error);
}
});
This will convert obj to a query string, and then you can just do $_POST['firstName'] and $_POST['lastName'].
I think this is the best shot for you.
jQuery Ajax POST example with PHP

JS Ajax calling PHP and getting ajax call 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)

Jquery variables in JSON to PHP

I'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://example/ajax",
data: { test: test },
cache: false,
async: true,
success: function( json ){
$.each( json.rows, function( i, object ){
//Example: object.date
<?php date('g:ia', $objectDate ) ?>;
});
}
});
What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?
PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.
You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.
In summary what you should do is:
Pass some data from client to server with an AJAX call
PHP processes these data and returns a JSON object
JS processes the JSON object and, for instance, modifies the HTML of the page.
If you need to further process newly generated data with PHP do other AJAX calls.
Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.
Here's a basic rundown of going from JS to PHP, and PHP to JS:
To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:
var data = { message: "Hello" };
$.ajax({
data: { data: JSON.stringify(data) },
// ...
});
Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:
$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"
To send JSON back as the response to the browser (for your success callback), use json_encode like so:
header('Content-type: application/json');
echo json_encode(array(
'message' => 'Hello, back'
));

Categories