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.
Related
everyone. I am making a website with t-shirts. I dynamically generate preview cards for products using a JSON file but I also need to generate content for an HTML file when clicking on the card. So, when I click on it, a new HTML page opens like product.html?product_id=id. I do not understand how to check for id or this part ?prodcut_id=id, and based on id it generates content for the page. Can anyone please link some guides or good solutions, I don't understand anything :(.
It sounds like you want the user's browser to ask the server to load a particular page based on the value of a variable called product_id.
The way a browser talks to a server is an HTTP Request, about which you can learn all the basics on javascipt.info and/or MDN.
The ?product_id=id is called the 'query' part of the URL, about which you can learn more on MDN and Wikipedia.
A request that gets a page with this kind of URL from the server is usually a GET request, which is simpler and requires less security than the more common and versatile POST request type.
You may notice some of the resources talking about AJAX requests (which are used to update part of the current page without reloading the whole thing), but you won't need to worry about this since you're just trying to have the browser navigate to a new page.
Your server needs to have some code to handle any such requests, basically saying:
"If anybody sends an HTTP GET request here, look at the value of the product_id variable and compare it to my available HTML files. If there's a match, send a response with the matching file, and if there's no match, send a page that says 'Error 404'."
That's the quick overview anyway. The resources will tell you much more about the details.
There are some solutions, how you can get the parameters from the url:
Get ID from URL with jQuery
It would also makes sense to understand what is a REST Api and how to build a own one, because i think you dont have a backend at the moment.
Here some refs:
https://www.conceptatech.com/blog/difference-front-end-back-end-development
https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm
First of all: sorry for my bad grammer. English isn't my native language, but i will try to exlpain my problem as simple as i can.
I'm working on a web-application, where user can enter a link. (Question 1) This link should be send to the server/servlet and will be progressed to other things. (Question 2) After the progression, the servlet will send a json-array (?) back to the javascript-part of my app.
I'm completly new to this kind of stuff, but its very important to me, to find out how this works or better, how i can make this work. Its actually very simple, but i used plenty of weeks and cant figure it out.
The application is using the SAP UI5-libs (Question 3), where i would also like to know, if there is any possible way, to parse JSON with the UI5 libs.
I hope, i could explain my problem good enough, so i can get some help. Thanks to all!
The 'sending' of the string to the server/servlet would happen via ajax in either POST or GET form. That is up to you.
I recommend you use a javascript plugin like jQuery (JQuery Ajax API) because the regular ajax code is a bit messy.
As for the servlet/server communicating back to the client is as simple as writing to the page. In a typical servlet context it would be something like
out.print("This is a message");
where Ajax automatically returns the content of the entire page upon callback.
So in conclusion:
Consider test.jsp your servlet. I wish to send "Hi" from the client (being the browser) via GET to the servlet and I want the servlet to say "Hello" back.
I would open an ajax request of type GET to the url "test.jsp?param=Hi". In the servlet I receive this page request and process it. The servlet discards the parameter because it is not used and outputs "Hello" to the page.
In the client the ajax will have returned "Hello" and I can use this to put it into a var or whatever and all of this happened while not refreshing and not navigating in the original document where I did the javascript.
Another way is using websockets where you basically use sockets in javascript to send and receive any kind of data.
Also please check out this possible duplicate question: How to send a string to a servlet from javascript using xmlhttprequest
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.
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.
My friend has a search engine that he wants to have a widget access that can be put on other web pages. If I send a request to the search engine, it returns an XML file. The request would look something like this:
http://www.site.com/page.php?keyword=this+is+a+sample&page=1&num_days=3&source_id=site2.com&source_name=site2&source_url=sampleurl.php
I understand how to access this by using Javascript. However, I know that you can't do a cross-domain request. I would have to have it load a new page at the search engines's site and not in the window at the the site they were located at....right? Any ideas or insight are greatly appreciated.
Here is a good explanation too:
What is JSONP all about?
EDIT:
jsonpString
Override the callback function name in
a jsonp request. This value will be
used instead of callback in the
callback=? part of the query string
in the url. So {jsonp:'onJsonPLoad'}
would result in 'onJsonPLoad=?' passed
to the server.
jsonpCallbackString
Specify the callback function name for
a jsonp request. This value will be
used instead of the random name
automatically generated by jQuery. It
is preferable to let jQuery generate a
unique name as it'll make it easier to
manage the requests and provide
callbacks and error handling. You may
want to specify the callback when you
want to enable better browser caching
of GET requests.
taken from:
http://api.jquery.com/jQuery.ajax/