jQuery getJSON to external PHP page - php

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.

Related

html object to call php and return string

I want to call a php script (with args) from HTML and to process the returned data
I tried various flavours of :
<object id=test1 data="object.php" type="text/plain">
where object.php just returns a string, like
<?php print "firstText:Hello World";?>
I can't work out how to retrieve the returned string.
I was hoping to find it in something like
document.getElementById("test1").firstText
But no joy
Why am I doing this, you ask?
I'd like to get the page working interactively between the user and the server, avoiding the repainting of the browser window that comes with re-submitting with POST/GET.
Thanks for your responses.
I'm not happy using JQuery - another layer beyond my control
I have eventually found the returned text in
document.getElementById("test1").contentDocument.body.firstChild.textContent
which I can then work with.
Thanks
Use AJAX. Here's an example using jQuery:
$.get('yourpage.php', function(response){
// response contains the string returned by your PHP page.
});
PaulPros idea is probably your best method. Don't forget to include jQuery.
Is there any reason you could not just make the .HTML a .php file and include your script?

external URL AJAX and JSON PHP side of things

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.

Replace an API call using $.ajax() and JSONP with a server-to-server API call

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.

How to implement php tags in javascript for url's or anything

I was wondering how i could achieve using <?php?> in javascript for url's? There's a certain route you have to go, Anyone know?
the normal way for example:
$fetchContent = $('#div').load('website/members #content');
What i'm trying to do:
$fetchContent = $('#grav').load('<?php?> #poppu');
Yep, thats wrong as hell lol, but i'm sure someone knows
I would also like to know how to tie php with javascript, but thats probably a whole new topic
You said it right :)
Yep, thats wrong as hell lol, but i'm
sure someone knows
Anyway, from your php script, output the url as a javascript code anywhere in the script before the javascript used for ajax call, e.g.
<?php
echo '<script language="javascript"> var g_ajax_url = "'. $the_url . '";</script>';
?>
and in your javascript, use it this way
$fetchContent = $('#grav').load(g_ajax_url + ' #poppu');
What it simply does is define g_ajax_url as a global variable with the proper php value, and you can use that variable in your js as you use other variables.
To tie php with js directly, try looking into xmlrpc topic.
If javascript is in .php file you can use <?php echo $url ?> and if the file is .js you can't use <?php ?>
It is not clear to me what you are trying to achieve. I assume you are using the jQuery load() function, if yes, you should state so.
You can't load php during javascript execution because the php has already been processes and rendered as HTML and sent back to the client. As PHP is processes on the server it is logical that you cannot run it on the client side.
You could of course send an AJAX request to the server that runs a certain php page and you will be able to use the response as you please.
you can't necessarily "tie" them together because they operate in two different spectrums of processing, php being processed on the server, and javascript being processed in the browser.
You can however render javascript within a php file.
if your javascript is included within a <script> tag within your php page your example should work should actually work. The php would render the urls into the script before it is sent to the browser.
if you are wanting to load external javascript files with php inlcuded urls, you will need to set the proper headers and include the php file just as you would a normal .js file.
good article on this topic HERE
You cannot execute <?php ?> inside JavaScript, but inside PHP you can declare a global variable as:
var x = '<?php echo x;?>';
or, if it's an array, store it as JSON:
var x = <?php json_encode(x); ?>
then access the JavaScript variables inside the external JavaScript.

Using Ajax to Send Data Back to the Server

I understand there is a method send for xmlHttpRequest objects, but I've been working on this site all day and I'm unable to find any halfway decent tutorials on the subject and my brain feels like mush. Ajax is hard.
What I'm trying to do is send data from one Javascript file back to a PHP script on the server, where the data is simply a string and a small number. Is this possible? Why can't I find a good article on the subject?
tl;dr How do I use the send method to pass a string and a number from a javascript file to a php file?
Why don't you user jQuery or similar library?
Sending a variables with jQuery will be simple as that:
$.post("save.php", { name: "John", time: "2pm" } );
In your save.php file you can handle POST variables as you wish:
$name = $_POST["name"];
$time = $_POST["time"];
You can check it out: http://jquery.com/
I think you are wasting your time trying to make self made methods ...
It's definitely possible. This is a really nicely organized tutorial that walks you through the XmlHttpRequest object, how to set it up, and how to consume it on the server.
The server-side code is PHP, and I'm more of a C# guy, and it made total sense to me. (Maybe I should switch to PHP??).
I hope this helps! Good luck.
EDIT: In response to a previous SO question, I put this jsfiddle together to demo how to use XmlHttpRequest. Hope this also helps.
lots of good links here, so I'm not going to add to that. Just as a sidenote, you're dealing with a light case of ajaxness here :) - typically you'd want to send something back from the server that changes the state of the page in response to what was sent from the page in the first place (in fact one might argue why you need ajax in the first place and not simply post, if the page's not supposed to change - but I can see how there might be situations where you'd want ajax anyway). I'm just saying that because you're going to encounter a lot of content about how to deal with the stuff sent back from the server - just making sure you're aware that's not needed for what you're trying to do (I'm always glad when I know what I can leave out in the first pass ;)
step 1:
get jquery. all you have to do is download the latest file and include it on your page.
step 2:
make 2 files:
somepage.html:
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$.get("someScript.php",
// data to send if you want
{
'someVar' : 'someValue'
},
// receive and do something with response
function(response){
alert(response);
} // function (response)
); // .get()
</script>
someScript.php
<?php
echo $_GET['someVar'] . " response!";
?>
step 3:
upload all your files to your server and go to somepage.html
That's all there is to it. Though, you would generally put that code inside some kind of onclick or whatever, depending on what you want to use ajax for. But the comments in there are pretty self explanatory. jquery is used to make the ajax request, with an example of sending data to the server-side script receiving the request (using GET method). You would do whatever in someScript.php but in this example, it simply echoes back the value you sent. Then jquery takes what someScript.php echoes out and just throws it in a popup.
Using jQuery, you can use the post method:
$.post("test.php", { name: "John", number: 2 } );
Behind the scenes, this uses xmlHttpRequest, have a look at the source to see how they do it.

Categories