I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.
This is the jQuery code that sends the data to the external page:
function LoadImageData(url)
{
$.ajax({
url: 'get_image_data.php',
dataType: 'json',
data: {'url': url },
success: SetTag()
});
}
This is the PHP code htat receives the data and is required to send some data back:
<?php
require_once('FaceRestClient.php');
$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);
$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);
return $photos;
?>
So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.
Thanks in Advance,
Mark
You need to echo the resulting JSON:
echo $photos;
If $photos is not already JSON, use json_encode:
echo json_encode( $photos);
One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?
You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.
Try this:
$.ajax({
url: 'get_image_data.php',
type: 'POST',
data: {'url': url }
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('Your ajax just failed');
});
Open the console, and see what is printed
At the end of a PHP function I tend to do :
exit(json_encode($someData));
To return the data as JSON, but anything that prints the data is ok.
try this
echo json_encode( $photos);
you need to echo
echo $photos;
and as metntoned by #nickb if $photo is not already a json then convert it into json first and then echo.
echo json_encode($photos)
in jQuery if you want to fetch the data
onSuccess: function(data, status) {
//var data contains the returned json.
}
Related
I have an ajax-script that retrieves jsondata from php - so far ok, but the data could not be parsed since other outputs (echoes) comes along with the jsonstring. I searched this issue and it seems one should add header information when sending relevant output (json) from php back to clientside (ajax). When I do that nothing is sent back. How could I solve this?
this is how it looks like on the client side retrieving json (together with other prints)
connected to database { jsondata comes here .. } success
So, how to isolate the jsondata sending it back?
clientside (ajax) , snippet
$(function(){
$.ajax({
type:'POST',
url: 'endpoint.php?function=getJson',
data: {name: 'Stockholm'},
success: function (data){
console.log('success',data);
var jsonData = JSON.parse(data); //error here when parsing!!!
serverside (php), snippet
//header('Content-Type: application/json'); //if I add thos row no data is sent back
$result = $_GET['function']($_POST['name']);
echo $result;
function getJson($name) {
...
return $json;
}
I solved the problem by cleaning stdout (output buffer), putting the function call just a line before echo $result
that is:
$result = $_GET['function']($_POST['name']);
ob_clean(); // this call solved the problem
echo $result;
source:
https://www.php.net/manual/en/function.ob-clean.php
I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>
I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?
http://serverA.com/list.php:
html:
<form id="myform">
<input id="inputfield" name="view">
</form>
js:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: inputdata,
dataType: 'jsonp'
});
});
http://serverB.com/detail.php
php:
<?php
$view = $_GET['callback'].'('.json_encode(name) .')';
?>
html:
<h4><?php echo $view; ?></h4>
what the code does is:
from serverA, assign a value "ocean-view" to an input field, submit this form to serverB, and display this value in a h4 tag.
I couldn't quite figure out how to write the server-side code to output the value, even though I have found the following posts.
this and this.
Any kind of help is appreciated.
UPDATE:
I used YQL to help to see the jsonp callback response, here is the json structure:
callback({
"query": {
"count": 1,
"created": "2013-07-29T13:01:12Z",
"lang": "en-US",
"results": {
"h3": {
"class": "mytitle",
"content": "Example"
}
}
}
});
Actually You are very close to success... just read these points.
Whenever you are making an ajax request the browser sends a hit on ajax URL with respected parameters and details. On respected URL PHP code executes. It can return data in some format. It can not return data in directly PHP variable.
Formats are:
text/html
json
xml
......
Mainly for cross domain requests we use JSONP.
And it means PHP script will return data in JSON.
So you will just echo your json_encode in directly script. That will be the response of your ajax request.
Now when you have got the data in ajax function, then jQuery uses success: function(response){ } where you response will come.
So variable response will contain JSON.
You can access JSON and put data in any tag by using jQuery selector.
$().html(response.);
These thing can be analyzed in any browser in debug console. That what is requested and what is returned.
even you can use Firebug in Mozilla to inspect ajax request.
So you will do three changes.
In Ajax function write a success function:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: "inputdata="+inputdata,
dataType: 'jsonp',
success:function(response){
// response will be json type so access it
// print ur json in html tag like resposne is {"data":23}
$(<jquery selector>).html(reponse.data);
}
});
});
<?php
// echo this
$inputdata = $_GET['inputdata'];
// perform you logic ,
// make an array to encode it in json
echo $_GET['callback'].'('.json_encode($responseArr) .')';
?>
and remove PHP code from h4 tag.
I'm still in AJAX stuff since morning so maybe thats the reason why some things does't work as they schould - let's forget about it. To sum up, my problem is coincident with passing HTML via JSON. An example of the PHP code:
$list = "<strong>This is test</strong>";
$response = array('success'=>true, 'src' => $list);
echo json_encode($response);
Basicly that's the main part of the code which is responsible for passing the HTML to AJAX. Now, let's have a look on part of AJAX code:
success: function(output)
{
alert(output);
json = $(output).find(".content").text();
var data = $.parseJSON(json);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
Some of you will ask what am I doing in this part:
json = $(output).find(".content").text();
The answer is: I retrieve the json string from the ".content" box, so when I alert variable "json: i get:
{"success":true,"src":"1. dsfasdfasdffbcvbcvb<\/span>Edytuj<\/span> <\/a>Usu \u0144<\/span><\/div>2. vbnvbnm454t<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div>3. ndfhgndgfhndfhgndfhd<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div><\/div>"}
The problem is that I do not get this HTML... I get only text witout any HTML tags, styles etc...
String which I get, rather than HTML:
"1. dsfasdfasdffbcvbcvbEdytujUsuń2. vbnvbnm454tEdytujUsuń3. ndfhgndgfhndfhgndfhdEdytujUsuń"
Please don't try to look for anything smart or gunius in the above string because u won't - it's only a test string.
Acording to the part of PHP code - in my case I get "This is test" rather than "This is test".
To sum up my question is, how to pass these HTML tags or whole HTML code via json from PHP to AJAX.
I think you're misunderstanding how jQuery.ajax() works. You just need to tell it that dataType: 'json' (meaning that you're expecting JSON output from the server), and it takes care of the rest. You don't need to use jQuery.parseJSON(). The success() method will be given a JavaScript object representing the server response.
success: function(output)
{
// output is a JS object here:
alert(output.success); // true
// ...
},
To get your HTML from that point, you would just access output.src.
You can specify dataType: 'json' in your ajax request and receive an object(i.e. json already parsed) in your success call. eg
$.ajax(url, {
dataType: 'json',
success: function(output)
{
if(output.success == true)
{
obj_a.parents(".row").append(output.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
if you can't change dataType you would call $.parseJSON on output
function(output)
{
alert(output);
var data = $.parseJSON(output);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},