I'm trying to load an external page using JSONP, but the page is an HTML page, I just want to grab the contents of it using ajax.
EDIT: The reason why I'm doing this is because I want to pass all the user information ex: headers, ip, agent, when loading the page rather than my servers.
Is this doable? Right now, I can get the page, but jsonp attempts to parse the json, returning an error: Uncaught SyntaxError: Unexpected token <
Sample code:
$.post('http://example.com',function(data){
$('.results').html(data);
},'jsonp');
I've set up a jsfiddle for people to test with:
http://jsfiddle.net/8A63A/1/
http://en.wikipedia.org/wiki/JSONP#Script_element_injection
Making a JSONP call (in other words, to employ this usage pattern),
requires a script element. Therefore, for each new JSONP request, the
browser must add (or reuse) a new element—in other words,
inject the element—into the HTML DOM, with the desired value for the
"src" attribute. This element is then evaluated, the src URL is
retrieved, and the response JSON is evaluated.
Now look at your error:
Uncaught SyntaxError: Unexpected token <
< is the first character of any html tag, probably this is the start of <DOCTYPE, in this case, which is, of course, invalid JavaScript.
And NO, you can't use JSONP for fetching html data.
I have done what you want but in my case I have control of the server side code that returns the HTML.
So, what I did was wrapped the HTML code in one of the Json properties of the returned object and used it at client side, something like:
callback({"page": "<html>...</html>"})
The Syntax error you are facing it's because the library you're using expects json but the response is HTML, just that.
I've got three words for you: Same Origin Policy
Unless the remote URL actually supports proper JSONP requests, you won't be able to do what you're trying to. And that's a good thing.
Edit: You could of course try to proxy the request through your server …
If you really just want to employ the client to snag an HTML file, I suggest using flyJSONP - which uses YQL.. or use jankyPOST which uses some sweet techniques:
jankyPOST creates a hidden iframe and stuffs it with a form (iframe[0].contentWindow.document.body.form.name).
Then it uses HTML5 (watch legacy browsers!) webMessaging API to post to the other iframe and sets iframe's form elements' vals to what u specified.
Submits form to remote server...done.
Or you could just use PHP curl, parse it, echo it, so on.
IDK if what exactly ur using it for but I hope this helps.
ALSO...
I'm pretty sure you can JSONP anything that is an output from server code. I did this with ClientLogin by just JSONPing their keyGen page and successfully consoleLogged the text even though it was b/w tags. I had some other errors on that but point is that I scraped that output.
Currently, I'm trying to do what you are so I'll post back if successful.
I don't think this is possible. JSONP requires that the response is rendered properly.
If you want another solution, what about loading the url in an iframe and trying to talk through the iframe. I'm not 100% positive it will work, but it's worth a shot.
First, call the AJAX URL manually and see of the resulting HTML makes sense.
Second, you need to close your DIV in your fiddle example.
Related
How can I make a POST request to some URL (see my code below) in Javascript ?
My code so far doesn't work and I actually need to put it into an iFrame (having its with and height set to 0) to prevent the main page to reload.
$(document).ready(function(){
$("button").click(function(){
$.post(
"http://control.msg91.com/api/sendotp.php?otp_length=4&authkey=xxx&message=Your OTP is ##OTP##&sender=OTPSMS&mobile=xxx&otp_expiry=2"
, function(data){
alert(data);
});
});
});
If you want to use an iframe, then do not use XMLHttpRequest (NB $.post is a jQuery that wraps around XMLHttpRequest).
Create a <form>. Set its action to the URL. It's method to POST and its target to the ID of the <iframe>.
Put the data in that form. Then submit it.
If you want to do this entirely with JavaScript, then you can create the form using DOM and with entirely hidden inputs so that nothing shows up in the existing page. Ensure that you append the form to the document as some browsers will not let you submit forms that aren't part of the document.
That said, since you want an iframe with no dimensions, it seems odd to want to use an iframe at all.
You might be trying to work around CORS limitations, but you should be able to use the code you are using to make a request successfully. You just won't be able to tell if it was successful or not (because the restrictions are on reading the response). If you used an iframe, you would have the same limitations.
If you want to suppress the error message that is shown in the console, you could use fetch with mode: "no-cors". You still wouldn't be able to read the response though.
Make sure you are not hitting an issue with CORS. Unless the resource you are hitting allows exceptions to the cross-origin policy, you will not be able to access it if your webpage is not located on control.msg91.com.
Can anyone please explain how jquery handles cross domain requests? I understand the theory that it does via script using src attribute as url. But i was trying to test the same thing in plain javascript . I need to know the sequence of activities to be done for a post request. at what stage the data is sent and script element is constructed ? I am tired of asking the same at different forums where i got to see links explaining CORS. i need a to-do solution here.
Thanks
PS: sorry if i am asking too much :)
The ajax request URL is set as the .src attribute on a dynamically generated script tag and a parameter is added to the URL &callback=someFunc where someFunc is a local javascript function. When the server receives the URL, it's job is to parse the generate javascript that contains the returned data and then calls the passed in function name with the data as an argument. This is usually referred to as JSONP.
I want to get a short string hosted on a server where I do not have access to the data as XML, JSON, etc. I am trying to use either .load or .ajax to do this. I want to be able to parse the data into a javascipt array. The entire contents of the remote page is text and I am happy to take all of it and remove what I do not need via a small javascript. I have tried:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"http://url:8888/data", success:function(result){
$("div").html(result);
}});
});});
</script>
I have two questions.
1- why does this not work?
2- What would be the best way to store the string in a javascript var?
I am sure JQuery is working correctly.
The answer would be to long to post here (really). But look those up:
Same Origin Policy
Padded JSON
If you have no control over the remote site, you have lost - you will not get any data from it by Ajax (which is actually a feature, not a limitation of the technology). One way of circumventing the protection would be to build a proxy that just mirrors the remote service you need to reach and makes it available in the same domain that your main HTML came from.
I haven't found an answer to this, and since I'm pretty new to JS, I don't know if it's even possible.
I have a regular HTML form, where the only field is a user types in a URL (any URL) and clicks submit.
The URL will "be sent" to JS code that stores this URL in some variable, I guess. Basically, I need to be able to call getElementsByTagName() on any URL submitted by the user.
My point is to count up the number of times a URL contains a specified element, which I do know how to do :)
How do I interpret a URL submitted through a form by someone and then take that URL and be able to perform methods (such as getElementsById) on it? I want to return the count of the number of elements to the user.
Any ideas? Can this all be done in JS? Is this possible?
When you say "URL," I assume you are talking about the actual webpage and not the url string. In other words, you want to load the entire DOM into a javascript variable and then parse it with getElementsByTagName(), etc. Javascript cannot load this webpage due to the Same Origin Policy, unless users can only submit pages that are on the same domain as your site. If that was the case, you could use a frame. Otherwise, JS can't do it without Jsonp, which isn't going to work in this case.
However, all is not lost. You can have your JS make an asynchronous request (ajax) to your own server. Your server scripting language /can/ get the entire DOM of the webpage (e.g. PHP can do this with cURL). Then it can send the entire string back to JS as xml that can be parsed. Good luck.
You can't really do that from the client (the web browser) with nothing but Javascript, because security rules will prevent your page from fetching and examining content from a different domain. You'll need to send the URL to a server and have it do the work.
I need to find a way to write ajax responses to a file. The responses are XML strings, which is more than fine by me.
What I would like to do, is click on something in my webpage, and save the XML that is returned to a file.
But since I know, that Javascript can't access local files by itself, it is also possible to just send the data on to another server, where PHP would take care of this.
Now the place where I'm stuck is the javascript and the interception. I know, that some of this can be done using greaseMonkey in Firefox. If so, how? Thanks!
Edit: Some explaining.
The script that creates the output is not written by me.
Yes, I could see the data in Firebug, seeing is one thing. I need to interpret the data
There are a lot of requests going on here. About 1 every 2 seconds, so copying them by hand isn't an option.
Still, help?
You should provide more details, a link to the target page is best.
Is the page using jQuery?, Some other library?, or custom XMLHttpRequest() calls?
Anyway, a simpler approach may work, try it first...
If the AJAX data is being written to the page, attach a DOMSubtreeModified event listener to the container element. Something like:
document.getElementById ("ContainerID").addEventListener ("DOMSubtreeModified", YourFunction, false);
function YourFunction () {
//--- Get the target node's inner HTML and send it to our server.
}
Note that DOMSubtreeModified events work fine in FF and Chrome, the two main browsers for Greasemonkey.
If the data is not being written to the page, then the best way to intercept the AJAX depends on if the target page is using a library like jQuery.
A generic way to intercept AJAX can be seen in this SO question (and others).
As you said, once you have the data, to automatically write it to a file, use GM_xmlhttpRequest() to send it to a server that you control.
Why cannot you do it like this?
Save AJAX response to file on the server side and then provide a link to it, so it can be downloaded.
Firebug will also help, you can view in very convenient way each response in few formats, and eventually copy/save it.
Use a normal (non-AJAX) request and add a Content-Disposition: attachment; filename="foo.xml" header to the response.
If you're just going to save the XML, why are you using AJAX? Just set location.href to the location of a PHP script that sends a "Content-disposition: attachment" header and gives the XML in the response body. AJAX seems totally the wrong tool for the job.