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.
Related
I'm no expert in AJAX (or jQuery) but I thought what I was doing was pretty easy yet when I send an ajax request with:
$.ajax ( requestObj );
it doesn't send and I'm hoping someone can help. In order to give context, I've set the "requestObj" up as follows:
//initialise a request object
var requestObj = {};
requestObj.response = 'ajax-response';
requestObj.type = 'POST';
requestObj.url = my_config['ajax-service-list'][service]['url'];
requestObj.data = $.extend ( requestObj.data , {
action: service,
other: parameters,
_ajax_nonce: my_config['ajax-service-list'][service]['nonce']
});
requestObj.global = false;
requestObj.timeout = 30000;
requestObj.success = function ( r ) {
alert ( "Success: " + r );
}
requestObj.error = function ( r ) {
console.log ("FAILURE WITH AJAX Call ( " + JSON.stringify (r) + ")");
}
There's one thing that probably needs explaining. The two references to "my_config" are references to a Javascript variable that I set using Wordpress's wp_localize_script() function. Basically it just provides context about where to find the URL, the NONCE to use, etc. I have tested that the URL and NONCE information is working correctly so that shouldn't be the problem. For example, I put a breakpoint on the browsers debugger on the line after the two references are defined and got these results:
When I call the ajax function it immediately executes the success function and sends in the value of 0. Looking at my PHP error logs though I can see that the request was never sent. What could be getting in the way of $.ajax(requestOb) from actually sending the request?
UPDATE:
Thanks to Michael's sage advice I realised that I am in fact getting a request to go out but as it's running in a local environment the response is coming back lightening fast. Now I am suspecting this has more to with Wordpress configuration. I have hooked into the wp_ajax_[service_name] but it immediately returns 0. I'll re-ask this question with this new information in the wordpress forum.
You should be using a browser inspector to detect if an ajax request is made. Open up the network tab of any inspector, and you can watch requests as they happen. How is the $.ajax() method being instantiated? You may have an issue with that, as opposed to $.ajax().
Once you've used the inspector, look at the $_POST or $_GET data you're sending in the headers section, and then look at the response. Is the HTTP response code 200? If it's 500, then you probably have an error in your PHP controller that receives the request.
If you have PHP CLI, run this to see if you have a syntax error:
php -l path/to/php/controller.php
If you have a non-fatal error in your file, you'll see the error output in the request response.
Try var_dump( $_REQUEST ) at the top of your php file, too, to make sure that the file is receiving the data, and you can inspect it inside the browser-inspector response.
If you have a problem with the program inside of your controller... you've got yourself a new question to post. :)
At first look, it looks like your URL has spaces around get_action_template. That might be an issue.
Also, passing dataType might help.
If not try getting a JSON response without any parameters and post the output
Ok, i've answered this damn question finally. Arrgh. BIG, BIG THANKS to Mathew to who's troubleshooting skills I could not have done without. Anyway, the problem was in the AJAX request and as a result the Wordpress Ajax manager was never respecting the "hooks" I had put into place on the PHP side.
How was my AJAX request off? I had a POST request but the URL had GET variables hanging off of it. The key variable for Wordpress based Ajax requests is the "action" variable. This is the variable which WP's ajax manager uses to distinguish the various services and is the name that you'll be hooking into.
So in the end, my URL was:
http://mysite.com/wp-admin/admin-ajax.php
and my POST variables included:
action: get-action-template
My wordpress hook is:
add_action ( 'wp_ajax_get-action-template' , 'AjaxServiceManager::ajax_handler' );
My sleepless nights may continue but they won't be related to this damn problem anymore. :^)
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.
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
I am a JSON newbie, but have good experience in PHP and javascript. The question is simple, and the answer might be simpler. I am having trouble sending data from the PHP file on the server, to another PHP file that I have locally which would receive the data in JSON format from the server. What am I doing wrong?
Javascript Frag ( Local )
$(document).ready(function(){
//attach a jQuery live event to the button
$.getJSON('http://www.xpal.com/ws_users.php?action=get_user_data&user_id=33',function(data) {
alert(data); //uncomment this for debug
$('#showdata').html("<p>Username= "+data.username+"<br> Email= "+data.email+"<br> Firstname="+data.firstname+"<br> Lastname="+data.lastname+"</p>");
});
});
PHP Frag (Server #xpal.com) :
$users=new users;
if($_GET['action']=="get_user_data")
{
$user_id=$_GET['user_id'];
$assoc=array(
"username"=>$users->return_username($user_id),
"email"=>$users->return_user_emailid($user_id),
"firstname"=>$users->return_user_firstname($user_id),
"lastname"=>$users->return_user_lastname($user_id)
);
echo json_encode($assoc);
}
Edit :
The error message : XMLHttpRequest cannot load xpal.com/ws_users.php?action=get_user_data&user_id=33. Origin localhost is not allowed by Access-Control-Allow-Origin.
You can't make ajax calls to a different domain that the page is hosted on. See the Same Origin Policy that browsers implement for security reasons.
There is a way to make cross domain ajax calls and it involves using JSONP. Basically, you inject a script tag into your own frame and that script tag points to server endpoint anywhere on the web. Since the src value of a script tag is not restricted by the same origin policy, you can reach that server. But, now you need to have a way to get that result back. That is done using JSONP where you specify in your server request a javascript function that you want the returned javascript to call. That returned javascript can have javascript data in it that is then passed to the desired function. JSONP requires cooperation between both client code and the server code since a normal ajax call might not support the extra part of JSONP. But, with this cooperation of both sides, you can get around the same origin policy for server endpoints that support JSONP.
As already explained in the other answers, this doesn't work because of the Same Origin Policy.
Now, JSONP (see jfriend00's answer) is one way around it, but it has its drawbacks. (see the end of this page).
There is another way around it: and that is have PHP query the remote server and send a response back to the client. See this page:
Cross domain AJAX querying with jQuery
The main drawback of this method is that all the traffic will go through your server, since you have to call the remote page, fetch the response and send the response back to the client.
To use jsonp, as other suggest, you must either put "callback=?" at the end of your URL, or use $.ajax() and specify the dataType is jsonp. Examples here.
Its called the Same Origin Policy. In short: the domain that your code is on, is the only domain your javascript can communicate with (by default)
JQuery won't get json?
You could run a php script on your own server if that is an option.
This:-
<?php
$details = file_get_contents('http://www.xpal.com/ws_users.php?action=get_user_data&user_id=33');
var_dump(json_decode($details));
returned this:-
object(stdClass)[1]
public 'username' => string 'sniper' (length=6)
public 'email' => string 'ajithsubramanian#gmail.com' (length=26)
public 'firstname' => string 'Ajith' (length=5)
public 'lastname' => string 'Ravi' (length=4)
Does that put you on the right path? You could do an AJAX call to a script based on this on your server.
You should take a look at CORS and its implementation.
In your case, the possible solution would be to use header(Access-Control-Allow-Origin:http://localhost) in your php file. Replace localhost with the domain which is restricted by SOP.
A good reference on CORS can be found at https://developer.mozilla.org/en/HTTP_access_control .
You could use the same jQuery to make a cross-domain request, Just check the link cross-domain request, they have demo how to implement the cross-domain request...
In your code, Make sure that the following things are correct,
the www.xpal.com output should be in json format
if there is any error in your output, jsonp technique doesnt display error (poor error handling).
Your json output should be covered with echo $_GET['callback']." ".json_encode($array).")"; as in the mentioned link.
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.