I'm aware that modern browsers don't allow AJAX requests to foreign URLS, The workaround is JSON encoding and I'm doing that like this:
function findZipCodesInRadius(userZip, radiusInMiles) {
$.getJSON("http://mydomain.com/php/zipCodesInRadius.php?callback=?", {
TheUserZip: userZip,
TheRadiusInMiles: radiusInMiles
},
function (data) {
alert("Data Loaded: " + data);
});
}
and on the PHP side of things I have it "echoing" the results back like this:
$JSONData = array("callback"=>"true");
echo json_encode($JSONData);
After looking around google, the above code is what I've found and it's still not working.
How do I properly echo the callback? Maybe I'm doing the ajax request incorrectly? I usually do it a different way, but because I'm trying to access a file on another website of mine, I've been looking everywhere on the proper way of sending the request and this is what I came up with. Not sure what I'm doing wrong.
You will need to implement a callback function in order for this to work. You will need to wrap your json_encode with the callback function which is defined in $_GET['callback'].
For example, echo $_GET['callback']."(".json_encode($JSONData).")";.
You have to add the callback for jsonp requests
$JSONData = array("callback"=>"true");
$callback = $_GET['callback'];
echo $callback,'(',json_encode($JSONData),')';
I'm aware that modern browsers don't allow AJAX requests to foreign URLS,
On the contrary, modern browsers allow that, if you tell them to (see CORS)
The workaround is not JSON encoding but JSONP, a technique that uses dynamic <script> elements to load the external source. For this to work, the source must be executable JavaScript, this is where the callback parameter comes into play:
echo $_GET['callback'] . '(' . json_encode($JSONData) . ')';
The parameter will be a function name, but you don't have to care about that in your JS code, JQuery.getJSON handles it for you transparently.
Related
Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");
I have a javascript application calling an ajax function that looks like this
$.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) {
if (data.ok) {
//do things
}}});
the ajax url im trying to access is through etsyapi
everything works fine and dandy until i try to access the application in chrome with adblock on. it makes the ajax call fail completely, returns an error with a Failed to load resource-"theActualURL" message.
I couldn't figure out how to get past this in javascript and was told that i need to do a php call to get this working.
Unfortunately, i dont know the first thing about php- ive tried to understand even the basic structure for it, and i havent been able to find any work arounds in javascript, so i think it has to be done with php.
Is there simplest way to call the ajax function in php with a dynamic url(which is passed to the php page from javascript) and have it pass the array back to javascript to maniuplate?
ive gotten this far with the php-
<?php
$json = array();
????????????????????????
$jsonstring = json_encode($json);
echo $jsonstring;
?>
but dont understand how to access a dynamic url from javascript.
If it's genuinely using jsonp you shouldn't need php. Replace your $.ajax... with:
var newScript = document.createElement('script');
newScript.src = apiURL;
document.head.appendChild(newScript);
Ignore the above, I'm out of date with jQuery. Even so, you shouldn't need php if the API endpoint is really responding with jsonp. It sounds like the url was wrong/bad if you're getting an error. Have you tried simply opening apiURL by putting it in your browser's address bar?
jsonp is a work around for cross domain ajax restrictions that wraps the returned data in a javascript function call. This allows you to load it in a script tag and the function is run with the data as a parameter when the script is executed.
I've made on my website a search.php file that produce a JSON string, helping me to use real-time ajax for my apps.
But now, I'd like to open it as an API to others, but I discovered that $.get $.getJSON $.ajax doesn't allow to use my search.php file from other servers/domains.
How can I do to transform my php search into a search.json, exactly like Twitter, passing parameters to it.
Thx
getJSON is limited by your browser's security restrictions that lock down non-origin domains. In order to do cross-domain, you have to use JSONP, which requires you wrap the data in a function that is defined by the callback variable (e.g. $_GET['jsonp_callback']). e.g.
Search.php
<?php
echo $_GET['jsonp_callback'] . '(' . json_encode($data). ');'
// prints: jsonp123({"search" : "value", etc. });
?>
jQuery
$.ajax({
dataType: 'jsonp',
data: 'search=value',
jsonp: 'jsonp_callback',
url: 'http://yourserver.com/search.php',
success: function () {
// do stuff
},
});
Just make sure that the callback variable that you define in your php script matches the jsonp value that you call through the .ajax query (or it defaults to "callback").
Twitter uses two mechanisms to allow cross-domain access to the search.twitter.com domain: crossdomain.xml (for Flash) and JSONP (for JavaScript).
With JSONP, the calling JavaScript includes a callback=? parameter in the URL, where ? is the name of a callback function. The server-side script wraps the encoded JSON as:
?(<JSON here>)
This allows the query parameters to be encoded as the src URL of a script tag, allowing cross-domain access that XMLHttpRequest does not allow. When the data arrives, it is executed as a script. The JavaScript interpreter decodes the JSON since it is a valid subset of JavaScript and then calls the callback function with the decoded JSON as an argument. It shouldn't take more than a few lines of code to implement JSONP in your PHP script.
I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject.
I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could.
Use PrototypeJS and do it like this:
Have some PHP like this
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
Then make your Ajax call like this
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call.
You do not have to just show what's 'printed in that PHP file', your PHP file could print JavaScript commends back to your page. You could then, upon receiving the response, execute those commands. I like to use the eval function for this, but many people here will discourage you from doing so :)
Just use the "echo" function to put put PHP variables to the standard output put.
echo $myVarName;
Or, I prefer the printf(), be sure to check for HTML in the input BEFORE you output to avoid XSS issues.
Use something like this:
printf("Your input was: %s", strip_tags(%myInputVar));
Also, remember to use the %d or %f formatters when outputting number for best security.
I've been trying to make an AJAX request to an external server.
I've learned so far that I need to use getJSON to do this because of security reasons ?
Now, I can't seem to make a simple call to an external page.
I've tried to simplify it down as much as I can but it's still not working.
I have 2 files, test.html & test.php
my test.html makes a call like this, to localhost for testing :
$.getJSON("http://localhost/OutVoice/services/test.php", function(json){
alert("JSON Data: " + json);
});
and I want my test.php to return a simple 'test' :
$results = "test";
echo json_encode($results);
I'm probably making some incredible rookie mistake but I can't seem to figure it out.
Also, if this works, how can I send data to my test.php page, like you would do like test.php?id=15 ?
The test.html page is calling the test.php page on localhost, same directory
I don't get any errors, just no alert ..
It could be that you haven't got a callback in test.php. Also, json_encode only accepts an array:
$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';
// the callback stuff is only needed if you're requesting from different domains
jQuery automatically switches to JSONP (i.e. using script tags instead of XMLHttpRequest) when you use http://. If you have test.html and test.php on the same domain, try using relative paths (and no callbacks).
Be careful with moff's answer. It's got a common XSS vulnerability: http://www.metaltoad.com/blog/using-jsonp-safely
The simplest solution would be to add the below code before any output to your test.php file, then you have more flexibility with what methods you use, a standard ajax call should work.
header ('Access-Control-Allow-Origin: *');
However, use the json callback thing when your getting data from a server beyond your control.