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'
));
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 am using jquery iframetransport (for blob uploading) and am forced to access my responses via data.responseText. I am able to embed simple JSON from my PHP such as
echo json_encode(array("response"=>"hello"));
And my console log will return
{"response" : "hello"}
But I need divs and to concat data from my PHP requests. I fail right away if I try to embed this:
echo json_encode(array("response"=>"<div>hello</div>"));
I end up with
{"response":"hello<\/div>"}
What can I do to have this kind of json data in a resposneText?
Alternatively you could cast htmlentities() to the response array. Like this:
echo json_encode(array('response' => htmlentities('<div>hello</div>')));
// {"response":"<div>hello<\/div>"}
exit;
On retrieving responses, since you're expecting JSON, add the dataType: property:
$.ajax({
url: 'blahblah.php',
dataType: 'JSON', // this one
});
What is the best way to transfer the following outputted value into a php variable?
$(document).getUrlParam("id");
Through an ajax post.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You should use JSON format to send and receive data from javascript to PHP. For example
function sendData(){
//with jquery, you can use `.post()`, `.get()` or for more control `.ajax()`
$.post(
//URL to send the data
url,
//data being sent, transformed to JSON
{dataSent: JSON.stringify(clientSideData)},
//Do something after sendind the data to server
function(dataReceived){
//transform data from json format to javascript object
var dataLog = jQuery.parseJSON(dataReceived);
//Do stuff
}
)
}
PHP:
//Receive data from POST
var phpVar = json_decode($_POST['dataSent'])
//send data back to javascript
echo json_encode(phpVar)
While all of these answers will get the value from javascript into the PHP script, I'd wonder if you need javascript at all.
From what I can see from a brief google the getUrlParam plugin is useful for getting and then breaking down the URL. Have you had a look at the variables available through $_SERVER? I'm sure you'd be able to find something suitable in there.
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 know there are alot of different questions about this but none of them seem to pertain to me. I have an ajax request as follows:
var responsePacket;
$.ajax({
dataType: 'json',
type:'POST',
data:{
"updatePacket":{
"job":"name-update",
"firstName":firstName,
"lastName":lastName
}
},
processData: false,
url:'modify.php',
success: function(json){
console.log(json);
responsePacket = json;
if(responsePacket.updateStatus==true){
genAlertAlignAndShow('Name Successfully Updated', false, 4000);
}
else{
genErrorAlignAndShow('Name Update Failed!', false, 4000);
}
}
})
And my PHP on the other end are as follows:
$updatePacket = json_decode($_POST['updatePacket'], true);
//and I access variables from the JSON Object like this:
$job = $updatePacket['job'];
In response to the AJAX, the PHP file will punch out a simple JSON object, and yes my headers are set to application/json. This is how I a output a JSON response, I have tested it and it appears to get back to the AJAX Request when I rig it to return a static response:
$responsePacket = array("updateStatus"=>true);
echo json_encode($responsePacket);
But Here Is The Problem
As you can see I output the data to the console, but all it says is null which I have deduced is indicative of the JSON not getting to the PHP correctly. So, is there a proper way to create JSON Objects and prepare an AJAX request that will get the data to the PHP script intact.
I have been grappling with this problem for about 3 hours now, ANY suggestions are welcome.
I believe $_POST['updatePacket'] is not actually a json string. Try to access it like this instead:
$updatePacket = $_POST['updatePacket'];
$job = $updatePacket['job'];
No need to json_decode() it. From the json_decode() manual (return value):
NULL is returned if the json cannot be decoded...
Give it a try. As mentioned in the comments, var_dump($_POST); should be the first thing you try, to ensure you're getting what you think you are.
I figured it out. Here is my AJAX Requst:
$.post('modify.php', { job: "name-update", lastName: lastName }, function(data){
console.log(data);
})
The Problem:
When declaring data for an AJAX Post request putting quotes on the variable names will make the variables inaccessible to the receiving script.
You can easily make the time consuming issue of getting form data in a clean way with jquery, or javascript alone.
All you need to do is .serialize() the data. An example is here.
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});
Once it is done you can transform a string that looks like this.
"param1=someVal¶m2=someOtherVal"
with this
$params = array();
parse_str($_GET, $params);
with this usage you also want to filter the data and you should do this prior to the above.
http://php.net/manual/en/function.filter-input.php
Do this is less time consuming then listing each one individually in your ajax. You can also create a function to do this so you aren't continually writing ajax boilerplate code.
You are doing it wrong. You don't send a JSON object to the server, you send key/value pairs. And it's what jQuery expects. Do it like this instead:
data: {
"job": "name-update",
"firstName": firstName,
"lastName": lastName
},
and access the values like this:
$job = $_POST['job'];