I'm looking for something.
The problem is that I want to make my app do more locally and less remote.
It needs to put a parameter in every request (or websession id)
I tried the following
$.getJSON('http://*******************.com/loginapi.php?uuid=0x1a2b3c4e', function(jd) {
var reg = jd.usrreg;
var uuid = jd.usrpin;
var usrid = jd.usrid;
});
});
That does nothing, on the server side I don't even see a request to that page.
document.write(uuid) does not give anything back, when I go in my browser to the requested page I see the following:
{"usrreg":"0","usrpin":"0x1a2b3c4e","usrid":"0"}
I also tried with form data, so when I press login it sends a request to the server, but I should still get something back like usrreg=0 or 1, because it means the person is not registered, or usrreg=2 for wrong user/pass.
How can I read the value that I get when I open the page?
Cross Domain Request with Ajax are fobidden cause of Same Origin Policy: http://en.wikipedia.org/wiki/Same_origin_policy
So what are you alternatives?
Learn to use AJAX with JSONP - will only work if the other side provides it
Write a PHP bridge running locally that provides the remote data for you
Use postMessage: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
Related
for a project at school I am trying to make a website that can show your grades in a prettier way than it's being done now.
I have been able to log in to the site using cURL and now I want to get the grades in a string so I can edit it with PHP.
The only problem is that cURL gets the html source code when it hasn't been edited by the javascript that gets the grades.
So basically I want the code that you get when you open firebug or inspector in a string so I can edit it with php.
Does anyone have an idea on how to do this? I have seen several posts that say that you have to wait till the page has loaded, but I have no clue on how to make my site wait for another third-party site to be loaded.
The code that I am waiting to be executed and of which I want the result is this:
<script type="text/javascript">
var widgetWrapper = $("#objectWrapper325");
if (widgetWrapper[0].timer !== undefined) {
clearTimeout( jQuery('#objectWrapper325')[0].timer );
}
widgetWrapper[0].timer = setTimeout( function() {
if (widgetWrapper[0].xhr !== undefined) {
widgetWrapper[0].xhr.abort();
}
widgetWrapper[0].xhr = jQuery.ajax({
type: 'GET',
url: "",
data: {
"wis_ajax": 1,
"ajax_object": 325,
'llnr': '105629'
},
success: function(d) {
var goodWidth = widgetWrapper.width();
widgetWrapper.html(d);
/* update width, needed for bug with standard template */
$("#objectWrapper325 .result__overview").css('width',goodWidth-$("#objectWrapper325 .result__subjectlabels").width());
}
});
}, 500+(Math.random()*1000));
</script>
First you have to understand a subtle but very important difference between using cURL to get a webpage, and using your browser visiting that same page.
1. Loading a page with a browser
When you enter the address on the location bar, the browser converts the url into an ip address . Then it tries to reach the web server with that address asking for a web page. From now on the browser will only speak HTTP with the web server. HTTP is a protocol made for carrying documents over network. The browser is actually asking for an html document (A bunch of text) from the web server. The web server answers by sending the web page to the browser. If the web page is a static page, the web server is just picking an html file and sending it over network. If it's a dynamic page, the web server use some high level code (like php) to generate to the web page then send it over.
Once the web page has been downloaded, the browser will then parse the page and interprets the html inside which produces the actual web page on the browser. During the parsing process, when the browser finds script tags it will interpret their content as javascript, which is a language used in browser to manipulate the look of the web page and do stuff inside the browser.
Remember, the web server only sent a web page containing html content he has no clue of what's javascript.
So when you load a web page on a browser the javascript is ONLY interpreted once it is downloaded on the browser.
2. What is cURL
If you take a look at curl man page, you'll learn that curl is a tool to transfer data from/to servers which can speak some supported protocols and HTTP is one of them.
When you download a page with curl, it will try to download the page the same way your browser does it but will not parse or interpret anything. cURL does not understand javascript or html, all it knows about is how to speak to web servers.
3. Solution
So what you need in your case is to download the page like cURL does it and also somehow make the javascript to be interpreted as if it was inside a browser.
If you had follwed me up to here then you're ready to take a look at CasperJS.
Works:
function jsUpvote(photo_id, username) {
//var getURL = "http://www.uglyfacez.com/gallery/upvote.php?photo_id=" + photo_id + "&username=" + username;
$.get("http://uglyfacez.com/gallery/upvote.php?photo_id=15&username=user000",
function(returnValue){
// do stuff here
});
}
I wrote the function above to run a php script on the page and pass in the variables photo_id and username to the script through the URL. When I hard code it, as above, it works just fine, but when I give it the javascript variables (as you can see in getURL), it won't work at all. For example, this is what I want to do, but will not work:
$.get("http://www.uglyfacez.com/gallery/upvote.php?photo_id=" + photo_id + "&username=" + username,
function(returnValue){
// do stuff here
});
Why will this not work and what is the solution?
EDIT: I discovered what the problem was. For some reason, including www in my GET url keeps it from receiving a response from the server. Once removed from the URL, it works just fine.
This seems to be an issue regarding cross domain requests.
You can use some solutions such as JSONP or you can load script from different domain (in this case: www subdomain). To see different aspects and settings regarding cross-domain, please go to the .ajax() documentation page (and search for " cross-domain " or " crossDomain ").
The issue is basically a problem connected to same origin policy. On the mentioned documentation page you can read, that:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
Script and JSONP requests are not subject to the same origin policy restrictions.
Here is the sysntax for the jquery .get function:
jQuery.get( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
something like:
$.get("http://www.uglyfacez.com/gallery/upvote.php", {'photo_id':photo_id,'username':username},
function(returnValue){
// do stuff here
});
try to follow the syntax first put the data on the parameters of the function, I think this link might help you as well:
http://api.jquery.com/jQuery.get/
Or if you still encounter the same problem try to open the link manually on your browser again and check if it returns any error just to be sure that it returns your expected output. :)
Are you setting photo_id and username properly?? More code might help. What's the error message? Are you using Firebug or Chrome to see if you are getting an error?? Seems as though photo_id and/or username are not being passed in properly.
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 tried these two codes but it is not functioning.. i only want to ask for the data output from another domain from http://vrynxzent.info/hello.php
first code
$.post("http://vrynxzent.info/hello.php",function(e){
alert(e);
});
second code
alert(askData());
function askData()
{
var strUrlList = "http://vrynxzent.info/hello.php";
var strReply = "";
jQuery.ajax({
url:strUrlList, success:function(html){strReply = html;}, async:false
});
return strReply;
}
is there another way for this? or is it posible to do this? i want the "Hello World!" output to store in a variable in javascript..
Same old same origin policy.
The most common way to solve this is to do query in back-end (php in your case). I.e., browser sends ajax request to your host, which sends requests to other domain, receives response and sends it back to browser.
There're also some options if you own that other domain. JSONP, for example.
edit
Forgot to tell, this jquery plugin allows cross-domain requests through YQL. Tried myself.
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
It doesn't work in all cases (in particular, if webmaster has banned robots from his site), but it's still fairly simple and usable.
Because of same origin policy you cannot make ajax requests like this to some other domain,.
i would suggest using a proxy in between,.
for that what you have to do is have a script proxy.php on your own domain and then your ajax request will be
$.post( 'proxy.php' )
then proxy.php would send a request to http://vrynxzent.info/hello.php using curl and send you back the response
By default this does not work because of the "Same Origin Policy."
There are workarounds... see: http://www.ajax-cross-domain.com/
Help, if you can-
The situation:
http://foobar.com includes a remotely hosted javacript file (http://boobar.com/stuff.js).
The goal is to just get an alert from the remotely hosted php script on foobar.com
I have tried the following code in stuff.js:
$.ajax({
type: "GET",
url: "http://www.boobar.com/script.php?callback=?",
dataType: 'jsonp',
success: function(result) { alert(result); }
});
No luck.
$.getJSON("http://www.boobar.com/script.php?jsonp=?",
function(data) { alert(data); }
);
Also no luck.
On the php side I have tried both the following:
return json_encode(array(0 => 'test'));
echo json_encode(array(0 => 'test'));
In Firefox I get a security error. I understand that it thinks I'm violating the security model. However, according to the jquery documentation, I should be able to accomplish this.
The error seems to be a security feature of the Same Origin Policy: to simplify, you can only make AJAX requests for stuff on the originating server (http://foobar.com). One way around this is to make a simple facade on the originating server, e.g.:
<?php
// this file resides at http://foobar.com/getstuff.php
echo file_get_contents('http://www.boobar.com/script.php?callback=?'
. $possibly_some_other_GET_parameters );
?>
Then, from foobar.com, you can make an AJAX request for http://foobar.com/getstuff.php (which in turn makes a HTTP GET request from your web server to boobar.com and sends it back to the browser).
To the browser, the request goes to the origin server, and is allowed (the browser has no way of knowing that the response comes from somewhere else behind the scene).
Caveats:
the PHP config at foobar.com must have allow_url_fopen set to "1". Although this is the default setting, some servers have it disabled.
the request to www.boobar.com is made from foobar.com server, not from the browser. That means no cookies or user authentication data are sent to www.boobar.com, just whatever you put into the request URL ("$possibly_some_other_GET_parameters").
You can get data from another server asynchronously using script tags and json:
<script type="text/javascript" src="http://somesite.com/path/to/page/"></script>
You can use this to dynamically load a remote javascript (by created a new script element and setting the src attribute, then loading into the DOM), which could set a variable. However, you need to really trust the remote site, because the JS will be evaluated without any precondition.
There is a method called window.name transport or window.name method which uses a general browser bug(not sure if this is a bug actually). You make the request through an iFrame and the loaded page puts the information you need to the "name" property of the JavaScript window object of itself.
This method uses a "blank.htm" since it first navigates to the target page and then goes back to the blank.htm page to overcome the "same origin policy" restriction.
Dojo have implemented this and you can find a more detailed explanation here.
Also I have implemented a cross-domain XMLHttpRequest object based on this method in the library I have written which can be found here.
You may not be able to use the library since it will need 1 or 2 additional libraries which can be found here.
If you need further help in implementing it in your style, I'll try to do my best.
So what I ended up doing, since it was just a GET - no data need to be retrieved - I used JQuery to create a hidden iframe with the URL including the variables I wanted to pass set as the source. Worked like a charm. To all who provded feedback - Thanks!
How about this !! Using a php proxy.
Cross-Domain AJAX calls using PHP
http://www.phpfour.com/blog/2008/03/cross-domain-ajax-using-php/
jQuery .ajax also has a setting 'crossDomain'.
http://api.jquery.com/jQuery.ajax/
crossDomain (default: false for same-domain requests, true for cross-domain requests)
Type: Boolean
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5)