jsonp, jQuery & PHP to make cross-domain ajax call - php

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.

Related

How to console the PHP echo in my javascript?

I can not get the PHP echo in my Ajax.
This is my test01.html code:
In my HTML code, I quote the jQuery, and I bind the event in my "sub01" button, I use Ajax provide the POST request:
$(".sub01").bind("click", function() {
$.ajax({
type: "POST",
url: "cms/test01.php?action=test01",
dataType: "json",
data: {
"var_01": "var_01_value",
"var_02": "var_02_value",
},
success: function(response) {
console.log(response) // there I want to console the response from PHP.
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<form>
<input type="text" value="var_01">
<input type="text" value="var_02">
<input id="sub01" type="submit" value="click me!">
</form>
</div>
And this is my PHP test01.php code:
in my PHP code I want to echo the $_POST, then I want the AJAX code get the response.
<?php
echo $_POST;
I want the code
success: function(response) {
console.log(response) // there I want to console the response from PHP.
}
shows the PHP echo, but there console nothing.
Problem 1
You never call your JS function
$(".sub01").bind
You are binding to the click event of elements with the class sub01.
<input id="sub01" type="submit" value="click me!">
Your button doesn't have that class!
Aside: bind is deprecated in favour of on.
$("#sub01).on("click" ....
Problem 2
You aren't letting the JS run
Since you are (trying) to run the JS when a submit button is clicked, the form is submitting.
The browser is leaving the page before the Ajax response comes back and triggers the success function.
You need to prevent the default behavior of the submit button.
$("#sub01").on("click", function (event) {
event.preventDefault();
// etc
});
Problem 3
You aren't parsing the response correctly
You said dataType: "json", which means "Tell the server I only Accept JSON and ignore the Content-Type and parse the response as JSON regardless".
Since the server is not responding with JSON, the attempt to parse the response fails and it errors.
Option 1
Remove dataType: "json".
This will process the response as invalid HTML (because PHP sends Content-Type: text/html by default).
Then you will echo the response (which is Array … probably not the response you want PHP to send though).
Option 2
Change the PHP so it responds with JSON
<?php
header("Content-Type: application/json");
echo json_encode($_POST, JSON_PRETTY_PRINT);
You need to output a json.
header('Content-Type: application/json');
echo json_encode($_POST);

PHP capture data and join together

Okay so I need to parse two parts. Here is the code im trying to parse.
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
I would like it to parse and output like this once done.
10528935=12-1-D33D19A3F048E845A9AA885220729B98
Here is the site I'm trying to do this for
https://www.payqwiq.com/login?uid=582063bd-1973-42e4-8235-b28f5addf8bf
All I need is that data to be parsed and joined like above so I can continue with my program :)
Would appreciate some help if possible :)
I'm completely new in PHP.
Php is a back-end language. Since you are attempting to get data stored in a document object on the front-end, you should use a front-end language to parse the document object, then send the data to a php handler to do what you want with it on the back-end.
Using jQuery you can achieve the desired output with one line of code, then build an ajax call to send the output data to the desired php handler.
// when document is loaded
$(document).ready(function() {
// get data from document object to send to php handler
var combinedData = $('input').attr('name') + '=' + $('input').val();
// execute ajax method to send data to php handler
sendData(combinedData);
});
function sendData(data) {
// ajax method to send data to php handler
$.ajax({
url: 'pageToSendTo.php',
type: 'POST',
data: {
"data": JSON.stringify(data)
},
dataType: 'JSON',
success: function(data) {
console.log(data);
},
error: function(xhr) {
console.log('error: ' + xhr.responseText);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
<!-- this is the "pageToSendTo.php" php handler. -->
<?php
if ($_POST['data']) {
//echo 'received data!';
$data = json_decode($_POST['data']);
// do stuff with data
print_r(json_encode($data));
}
?>

How to pass HTML via JSON from PHP to AJAX - properly

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");
}
},

How to send a json string back to jquery

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.
}

how can i get html generated by a php script from another domain(cross-domain)

i am wondering how can get the HTML code which is generated by a cross-domain php script?
Normally if i'm on the same domain , i would use Ajax as follows:
$.ajax({
type: 'GET',
url: 'user.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#info').empty().html(html);
}
});
But i am now working on a different domain than my server domain. Which means i use JSON to send data back and to my server php scripts.
However , i know that JSON only send data but not a complete HTML CODE(or am i missing out some point here?)
So , how can i get the html code generated by a cross-domain php script(server) to my web page(another domain).
using javascript you can do the same as if it was JSON, it's called JSONP the P is with padding.
Or you can call it JSON with callback:
// Request Page
myCallback("Some string or Object to parse to your site");
// Your Page
window["myCallback"] = function(string_or_object) {
// Here you can do everything with the parsed data
}
Create a script-tag and include the request page. Make sure to define your callback before including the script-tag
or you can use jQuery's ajax method with dataType set to jsonp:
$.ajax({
"url": "requst_page.php",
"dataType": "jsonp",
"success": function(string_or_object) {
// Here you can do everything with the parsed data
}
})
Look at http://remysharp.com/2007/10/08/what-is-jsonp/
EDIT TO COMMENT:
JSON is right an object normally starts with braces {}.
Demo JSON:
{
"myString": "myValue",
"myOtherString": ["My", "Other", "Value", "This", "Is", "An", "Array"]
}
But using the same method as JSONP you can parse an string instead of the weird looking thing starting and ending with {}.
as myCallback in my example 1: myCallback("HERE I PASS A STRING INSTEAD OF AN OBJECT"). See the "". "STRING GOES IN HERE"
if it was JSON and taken usage of my DEMO JSON it would look like this:
myCallback({
"myString": "myValue",
"myOtherString": ["My", "Other", "Value", "This", "Is", "An", "Array"]
})
JS:
$.ajax({
type: 'GET',
url: 'curl.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#info').empty().html(html);
}
});
curl.php;
function get_data($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$user_id = $_GET['user_id'];
$url= "http://www.example.com/user.php?user_id=".$user_id;
echo get_data($url);
You can set up a proxy on your domain and use CURL to get the json from other domain. You then send request to this proxy.
Alternately you would need to set up the other domain to process request as jsonp in order to be able to access directly with ajax
You have to use JSONP or tell the website owner of the other site to add a Access-Control-Allow-Origin header.
I also get same problem when access cross domain using ajax. Then I solve it by make the ajax call to same domain. Then on that php script I apply following code block. This will get the content from cros domain and out put the same to ajax call.
$content = file_get_contents('http://crossdomain.com');
echo $content;
This can be done through jsonp. Following is an example.
$.ajax({
url: "example.com/respond.php",
data: {id: id},
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback"
});
respond.php
<?php
header("content-type: application/json");
if (isset($_GET['id'])) $rtnjsonobj->id = $_GET['id'];
$rtnjsonobj->message = "This is the message from cross domain";
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';
?>

Categories