Cross domain call through JSONP - ajax

I want to display html pages from external domains but unable to do this through JSONP i.e when page loads,page doesn't contain anything. It just shows a blank page. Please find my code below for reference.
Code:
Ext.util.JSONP.request({
url:wikiurl,
callbackKey:'callback',
params:{},
callback:function(data){
console.log(data);
console.log("inside callback");
},
success:function(result,opts){
console.log(result);
},
failure:function(result,opts){
console.log(result);
}
});

=>what is the URL?
=>who is sending the response, you need to send specific response from server when some one need JASONP data.
=>you are logging everything to console, it wont show in page, probably in firebug console or similar console it would be visible.
=>to see response in page, just dump the data in a div element in page.

Related

Stripping content from HTML page returned through ajax

Is there a way to display specific text out of a HTML page which was returned by an ajax call? By specific text, I mean the first paragraph/div of the HTML page returned.
By using $.load in jquery, I am able to fetch the page. How do I proceed from here.
Is it even possible to implement this using jQuery alone, without parsing html at the back end , and returning selected text as the response from my server.
.load() accepts a selector which can be used to specify the fragment of the page to be appended
$('#x').load('page.html div:eq(0)')
Demo: Plunker
$.get("/mypage.html",function(html){
var fisrtdiv = $('div',$(html)).first();
});
$.load returns the whole html page unless you specify a fragment of it (as seen in another answer here). You might be better off using $.get or $.ajax and then dealing with the returned data using a function:-
E.g. using ajax
$.ajax({
url: "your url here",
success: function(data) {
//Do something with your data (ie the returned html).
}
})

Clicking Back after fancyBox AJAX Form Submission

Not sure if this is even possible, but I have a AJAX form like this fiddle:
http://jsfiddle.net/nicorellius/GfeEf/
On my website, it is working fine. I do a simple validation in the form with JavaScript, but if the user gets through the JavaScript, the user is presented with a Campaign Monitor webpage: either saying yay or nay to their validation.
When the user subscribes successfully, if the user clicks back or uses the CM back link, the fancyBox remains with data populated. Based on how I have the script written it should close after submission.
This is Firefox behavior in Linux and Windows. Chrome actually clears the page and removes the fancyBox form. 
The AJAX section is here:
$.ajax({
type : "POST",
cache : false,
url : "http://<comapny_name>.createsend.com/a/b/c/abcdef/",
data : $(this).serializeArray(),
// I've tried both of these commented out pieces to no avail.
//beforeSend : function() {
//$.fancybox.close(true);
//},
//success : function(data) {
//$.fancybox.close(true);
//}
});
So despite adding:
success : function() {
$.fancybox.close(true);
}
to the AJAX script, I cannot get it to close after submission.
EDIT
I should note, too, that this phenomenon seems to occur with Firefox, Safari and Opera. Chrome behaves as I would expect (eg, when clicking the back link, I get the fresh page reload). The CM page is using javascript:history.go(-1) to send me back.
I have no idea about Campaign Monitor but why not force close your fancybox on document load?
$(document).ready(function(){
$.fancybox.close(true);
}
It looks like you might be wanting the code from the answer to this: How to close fancybox after Ajax Submit?
(Here is the part extracted & modified)
var fancyboxProxy = $.fancybox; //declared before $.ajax
//and then modify your success to:
success : function() {
fancyboxProxy.close();
}
I would also try a simple alert() or conosle.log() in your success function to determine you are receiving the success event, if you are receiving the event then you know it is specifically a problem with the code you are using to hide the fancybox.

Is it possible to get a part of page in an ajax get request?

I know we can fetch a whole page when doing a GET request to the server, but what if i'm only interested in one particular div on that page, or more exactly in its content. Is the only option here is to fetch the whole page, get the div content from it using jquery find() for example? Or is there some possibility to set up some kind of query to the server to ask for this particular div to return.
$.ajax({
'type': 'get'
...some params...
success: function(response){
$(response).find('div you are looking for').appendTo('div you want to append it');
}
});
For some params check jQuery ajax.
And answering your question: no, there is no way to get some parts of HTML without making special server-side service.
You might want to use a simpler form of jQuery's AJAX tool for this situation, .load.
$('#wrapper').load(href+fragmentSelector, function() {
// callback to do stuff afterward
});
Here, we're loading content from the element with ID fragmentSelector from the url href into #wrapper on our current page.
The entire page is still being requested, but only the content you request is returned.
Reference: http://api.jquery.com/load/#loading-page-fragments
You can use HTTP RANGE Header, but you can select a byte range to download and not a select content by DIV.
Example:
curl -r 0-1000 http://localhost -v
see Using the HTTP Range Header with a range specifier other than bytes?

Generate save as dialog box with AJAX request in Ext Js

I have an application that contains a grid and button for the user to be able to export the grid to excel. I want to be able to show the save as dialog box when the server responds with the excel file.The server accepts the parameters as a JSON object. Here is my code:-
Ext.Ajax.request({
url: '/export/excel/',
method: 'POST',
//Send the query as the message body
jsonData: jsonStr,
success: function (result,request) {
Ext.DomHelper.append(document.body, {
tag: 'iframe',
frameBorder: 0,
width: 0,
height: 0,
//src:result,
css: 'display:none;visibility:hidden;height:1px;'
});
}, //success
failure: function (response, opts) {
var msg = 'server-side failure with status code: ' + response.status + ' message: ' + response.statusText;
Ext.Msg.alert('Error Message', msg);
}
});
I know there is a similar question ( ExtJS AJAX save as dialog box) but that references a static file on the server.In my case, depending upon the json sent the result is going to be different each time. I get back the entire excel file that i want in the result.responseText. What needs to be done so that the dialog box popup up asking the user for save as options? Also, im not sure how the src in the domhelper should be configured. Any help would be really appreciated.
I believe the only way to do this in a totally client agnostic way is to force it from the server-side using a Content-Type of: octect-stream and Content-Disposition of 'attachment' with a suggested filename. See:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1
and
http://www.ryboe.com/tutorials/php-headers-force-download
You can also use so-called 'dataURIs' but they have their own set of issues:
http://en.wikipedia.org/wiki/Data_URI_scheme
My recommendation would be to return EXCEL content dynamically on the server and just make the button a link to that url that POSTS the current data your working with and sets the correct response headers to trigger your browser to download the file. Since you are doing an AJAX call and not letting the web-browser get the URL directly, any HTTP headers you set to control the way the browser interprets the content won't matter because you are doing it in JS not in the user's browser. By returning the content directly to the user through a link on the server, you'll get around this problem.
Since you actually want the user to click on the link, I don't think AJAX is appropiate here.
I made the server side return the path of the location the file is created and saved, instead of sending the file as an attachment in the response and hence avoiding the problem of setting the headers in the response. Then i just set the source of the iframe in the code to the path that gets returned in the response (result.responseText).

Chrome displays ajax response when pressing back button

I've come across a problem that if I use jQuery's Get method to get some content, if I click back, instead of it actually going back one page in the history, it instead shows the content returned by the Ajax query.
Any idea's?
http://www.dameallans.co.uk/preview/allanian-society/news/56/Allanian-test
On the above page, if you use the pagination below the list of comments you will notice when clicking back after changing a page, that it shows the HTML content used to generate the list of comments.
I've noticed it doesn't always do it, but if you click on a different page a few times and click the back button, it simply displays json text within the window instead of the website.
For some reason, this is only affecting Chrome as IE and Firefox work ok.
Make sure your AJAX requests use a different URL from the full HTML documents. Chrome caches the most recent request even if it is just a partial.
https://code.google.com/p/chromium/issues/detail?id=108425
Just in case you are using jQuery with History API (or some library like history.js), you should change $.getJSON to $.ajax with cache set to false:
$.ajax({
dataType: "json",
url: url,
cache: false,
success: function (json) {...}
});
Actually this is the expected behavior of caching system according to specs and not a chrome issue. The cache only differentiate requests base on URL and request method (get, post, ...), not any of the request headers.
But there is a Vary header to tell browser to consider some headers when checking the cache. For example by adding Vary:X-Requested-With to the server response the browser knows that this response vary if request X-Requested-With header is changed. Or by adding Vary:Content-Type to the server response the browser knows that this response vary if request Content-Type header is changed.
You can add this line to your router for PHP:
header('Vary:X-Requested-With');
And use a middleware in node.js:
app.use(function(req, res) {
res.header('Vary', 'X-Requested-With');
});
You can also add a random value to the end of the ajax url. This will ignore the previous chrome cache and will request a new version
url = '/?'+Math.random()
Just add the following header to the Response headers :
Vary: Accept
I couldn't give different urls for each ajax request as it was an ajax pagination, declaring no cache on headers did nothing, so i included a little javascript in the view only when headers were for the ajax request:
<script>
if (typeof jQuery == 'undefined') {
window.location = "<?php echo $this->here; ?>";
}
</script>
It is a dirty trick, but it works, if the ajax content is normally loaded, the container has Jquery loaded so it does nothing. But if you load the ajax supposed content without the surrounding content, Jquery is missing (at least in my case), so i redirect to the current page requesting a normal GET page with all the headers and scripts.
If you put it in the top of the page, the user won't notice because it won't wait till the page loads, it will redirect as soon as the browser gets this 4 lines...
Replace here; ?> by the current url in your APP, this was a CakePhp 2.X
Still had this problem in 2021 in Chrome.
Problem is doing underlying ajax request to the same url as the one the user is currently on.
I was working in Symfony and the complete fix that did the work for me was
$response->headers->addCacheControlDirective('no-cache', true);
$response->headers->addCacheControlDirective('max-age', 0);
$response->headers->addCacheControlDirective('s-maxage', 0);
$response->headers->addCacheControlDirective('must-revalidate', true);
$response->headers->addCacheControlDirective('no-store', true);
/**
* from https://stackoverflow.com/a/1975677/5418514
*
* The HTTP request header 'Accept' defines the Content-Types a client can process.
* If you have two copies of the same content at the same URL, differing only in Content-Type,
* then using Vary: Accept could be appropriate.
*/
$response->headers->set('Vary', 'Accept');
The #abraham's answer is right.
I just wanted to post a solution for Rails: all you need is just add different path to routes.rb.
In example, I have resource :people and I want to compose index page from ajax parts one of those is list of people. The straightforward way is to create index.js.erb and to load partial via ajax using url: people_path. But here occurs the issue.
So, for Rails, it needs just add a different route, like
get 'people_list', to: 'people#index', as: :people_list, format: :js
If I want to use index method of a laravel controller returns both html and json response, I add a get parameter at the end of the endpoint to pass browser caching:
axios.get(url, {params: {ajax: 1}})

Resources