Cross Domain Ajax Call Jquery - php

I am trying to call a page with ajax, but from another server. This js code runs from bookmark in any page you want and I need to get some data from my server. How could I do this? or maybe connect directly to the database?
I got this code:
$j.getJSON(serverUrl+"isLogin.php?callback=?",function(data){
//really no need to do anything here, we're just posting data
//but this will output success
alert(data);
});
isLogin:
if ($_SESSION['user'] == ''){
echo json_encode(array("isLogin" => "false"));
} else {
echo json_encode(array("isLogin" => "true"));
}
How could I make this? I try allot of solutions but none works. This one said no errors, but the alert never appear
Thanks

AJAX (The XMLHttpRequest object) is limited to the same domain for security reasons.
You have a couple ways to go about this:
You can use JSONP if your API supports it. This is very similar to your current AJAX approach.
This is jQuery's documentation - http://api.jquery.com/jQuery.getJSON/
Another option is to create a local proxy. This is a little more in depth, but gives you full control.
Here's a good article - http://developer.yahoo.com/javascript/howto-proxy.html

Related

Converting PHP to Ajax

I'm new to coding and was pretty proud when I created the following PHP code. Using TwitchTV's API, I can show the game someone is playing on TwitchTV. It works.
$info = "https://api.twitch.tv/kraken/channels/celgaming";
$json = json_decode(file_get_contents($info), true);
$thegame = $json['game'];
echo $thegame;
But I'm planning on caching the page this code is on and realized it won't work because PHP is server side. How do I convert this piece of code to Ajax or some other asynchronous method that will work with page caching?
I´m not sure about an async call being what you need, but I would try that first.
Here is, not a real answer, but hopefully some pointers to it:
Tried to make an Ajax call to "https://api.twitch.tv/kraken/channels/celgaming"
and stumbled upon 'same-domain policy' issue. See below link.
[Solutions to Ajax cross-domain problem][1]
I tried this from [1]: Ways to circumvent the same-origin policy
$.getJSON("https://api.twitch.tv/kraken/search/games?q=star&type=suggest&callback=?", function (data) {
$.each(data.games, function (index, item) {
console.log(index, item);
});
});
It works. Maybe you should scan the API docs for an alternate way to get the data you need.
I won't write you the javascript, you should try that first yourself, but propose other solutions that might solve your primary objective (caching):
you may use a database (e.g. MySQL) instead of client side caching. Just store the result of your TwitchTV query together with an expiration date in your database and check it before sending another request to TwitchTV.
you could send HTTP Cache-Control headers via PHP or included in your HTML code. See this question for instructions: Cache control and expires header for PHP. They suggest to the client to no query the server before the expiration date is reached.

Multiple php return values with jquery $.post

I dont really know how to ask this which is why I am asking it here. So if I was using some code like this:
$.post("/data/something.php", {stuff: 'hi'}, function(data){
$('#box').html(data);
});
Normally if you have php like this you only get 1 result:
<?php echo $_REQUEST['stuff'] ?>
I was wondering if there is any way for the php to send a bit of data, then a little bit more later without it just sending all of it at once like so:
<?php
echo 'Foo';
//Do stuff that takes time
echo 'Bah';
?>
There are 2 ways to accomplish this.
The first uses a standard workflow with the flush command (http://php.net/manual/en/function.flush.php). This means that you can do:
echo "Starting...\n"
flush();
// do long task
echo "Done!\n"
HOWEVER: This often won't work. For example, if your server uses deflate, the Starting likely won't get sent until the request is finished. Many other factors can cause this too (proxies, browser behaviour).
The better option is to use a polling mechanism. Your main script would write its progress to a file (with some session ID related filename), then delete that file when done. You would then add a second script to report the progress in this file (or completion if the file has been deleted) and your JavaScript would send an AJAX request to this checker script (maybe every second or two).
In PHP
<?php
echo 'Foo';
echo '||||';
echo 'Bah';
?>
In Javascript
var responses = data.split('||||');
//you will get
//Foo in responses[0]
//Bar in responses[1]
I expect that php has no problem doing that (as detailed by #Dave). The complicated part, is for javascript to retrieve the first part of the data, before the transmission completes...
I think what you are asking is answered here: Is it possible for an AJAX request to be read before the response is complete?
The way to accomplish this is by listening on the readyState in the the xhr object. When readyState == 3 it means new content has arrived and you can access it. The technique is referred to as Comet.
and...
So finally, yes it is possible, no it is not easy.

Access-Control-Allow-Origin server side by php

I am having problems with this topic: Access-Control-Allow-Origin.
I read about it and I found that is possible to get response using php, here
But I don't know how to adapt that code to javascript, I still have the same problem.
I tried this in javascript:
var url ='http://localhost:8080/com.webserver/rest/manage/order?parameter=parameter';
req=Ajax("getResponse.php/?" + url)
if (req.status=200)
alert("hi");
And on php file:
<?php
echo file_get_contents($_GET['url']);
?>
And nothing happends. I tried with ajax, something like:
$.ajax({
url: "http://localhost:8080/com.webserver/rest/manage/order?parameter=parameter",
async: false,
dataType: 'html',
success: function (text) {
alert(text);
}
});
But always same problem....
I read lot of people on internet having the same problem, but no one get a response. I just found 2 ways, using chrome and one option but just recomended for developers and adding headers on server but I don't know where to add them. I am using apache tomcat catalina for that localhost. I have 2 servers, webpage (in xampp) and rest (in tomcat)
Change
req=Ajax("getResponse.php/?" + url)
to
req=Ajax("getResponse.php/?url=" + url)
Bare in mind this is insecure, i could pass anything into the url parameter and your php scripts would use it. Allowing people to read files from your local system as well as get your php script to download malicious files from elsewhere
Edit:
To best way to secure it is to use an actions list, this means that the user never see's the url and can only modify an action word. for example
req=Ajax("getResponse.php/?do=getOrders")
then in php
$actions = array();
$actions['getOrders'] = "http://localhost:8080/com.webserver/rest/manage/order?parameter=parameter";
if(array_key_exists($_GET['do'], $actions))
echo file_get_contents($actions[$_GET['do']]);
Usually you'd want to do more that just translate an action to a url, you may want to pass additional parameters. In this case you could use a switch or a bunch of IF's to check if $_GET['do'] is equal to something and then process it. but it would take hours to give an example of every possible implementation method, so you may want to use google.
Please note: whilst this method is suggest adds 100x more security to your script, its not infallable, especially if you start passing through parameters from users too. Once again use google.

PHP GET variable in same document

how can i pass a variable from javascript to php using same file
in this example page keeps refreshing and i don't get to see the result
it works only if i separate the scripts... but i need it somehow like on ajax..
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
and this is the seccond part of the script ( they are both in same file )
<?php
Id = $_GET[Result];
echo $dbId;
?>
As Brian said you should put it in a conditional statement.. also your PHP is bad. Try the following
<?php if(isset($_GET["Result"])) : ?>
// do work with set variable
<?php $dbID = $_GET["Result"];
echo($dbID); ?>
<?php else : ?>
// "Result" not set
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
<? endif; ?>
I think this is a good exercise if you're trying to learn the Ajax method, in the real world I recommend using a framework like jQuery. Of course understanding how this works will help you build better applications in the end.
So you could do something like this in the PHP script:
if (!isset($_GET['Result']))
{
// include the javascript portion with the redirect
}
I'm with the others, though--I'm not seeing the value in a page load followed by an immediate redirect to the same page.
What you are trying to do cannot be done. Your script runs on the client in real time but the php will run on the server during the request. You will need to make an AJAX request.
First you will want to use Firefox with firebug and the web developer toolbar. Firebug gives a great view of ajax traffic and the web developer toolbar helps you see what's going on in the page.
Use jQuery make an ajax request to "send" the value to another php file. Don't be afraid to separate out files, in fact it's encouraged and considered good programming. If you find your sending a lot if information to a php script you will want to use JSON instead of as part of the url.
Man, you should follow a client-server pattern.. So the Client page can use some ajax to make a request to a Server page. This will response to the Client and you can make with the data what you want.
of course it will keep refreshing:)) Because as soon as the browser gets the js code, it will load that page you specify, which will send your browser the same page... you get the idea. It's like writing for(;;){}
Your question is difficult to understand (for me at least.) My guess is that you are wanting to use AJAX to send data to the server and receive a response without leaving the page.
Probably the easiest way to accomplish this is to use a library such as jQuery. (see jQuery.ajax())
PHP only runs on the server and the javascript only runs on the client. By the time your client is running the javascript, no more PHP can be executed on that request.

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