Ext.data.JsonP.request always going to failed function? - javascript

I am doing application in Extjs, i am calling Ext.data.JsonP.request. In below code url path will come dynamically generate by appending name to base url of pdf. But Here i am hard coded. I am passing this url and testing jsonp request. if this url returns success i can write code success logic else failure, but here always going to failure method. also i have tried Ajax.request but no use. Some time i will get pdf path but that pdf is not in server that time i need showcase alert message like pdf is not found. Can tell me how can achieve this one? is it possible by calling jsonp request or any other method? Thank you
here is my code:
Ext.data.JsonP.request({
url: 'http://jmlr.csail.mit.edu/papers/volume10/mannor09a/mannor09a.pdf',
method: 'GET',
params: {
//fileID: feed_id, //this.form.getComponent('file').value,
},
failure: function () {
alert('failed !');
},
success: function () {
alert('success!');
}
});

Are you sure, that you need ajax to get pdf file? If you want to display this file to user, you can just put direct link to this file (without ajax or other tricks) and browser will show it.
Hard to understand, what do you want to get in the success function.
My recommendation to use plain link (you still can generate it dynamically to user)
Link
against using JSONP in this situation :)

Related

Download the returned PDF from Ajax

I have the following action that returns a PDF:
[HttpPost]
public string GetPDF(string data, float scaleFactor)
{
var result = JArray.Parse(data);
using (var fs = new FileStream(#"c:\pdf\pdftest.pdf", FileMode.Create))
{
MemoryStream ms = (MemoryStream)PdfMaker.CreatePDF(scaleFactor, result, dt);
ms.WriteTo(fs);
return Convert.ToBase64String(ms.ToArray());
}
}
(Ignore the FileStream, that is just for testing)
The result is basically the PDF itself, but it's not getting downloaded, how do I download the output PDF? Should I return something else? I tried using a FileResult, but it's basically the same scenario.
This is the way I'm currently "reading" the file via Ajax:
$.ajax({
type: "POST",
url: "home/GetPDF",
data: { data: JSON.stringify(data), scaleFactor: $("#sf").val() },
success: function (data) {
window.location = "data:application/pdf;base64, " + data;
}
});
Thanks.
Edit:
Used the solution in this post provided by Stephen Muecke
Downloading files via ajax doesn't work because the data ends up in memory in a JS object, not on the user's device. Ultimately you need to use a normal HTTP request and return a FileResult.
However in your case you also need to upload some data first which needs to be added to the PDF before it's downloaded. This is awkward because the download will have to be a GET request triggered in a separate window (because you need the application to remain on the same page afterwards) and supplying that data on the querystring is unlikely to be practical.
A solution to work round this is to have a two-step process:
1) From the browser, upload your data via AJAX to a "EditPDF" action method. In the action method, edit the PDF using the new data, and save it. Then return some sort of unique ID to the client which identifies the correct PDF.
2) When the browser receives the response from the EditPDF method, it grabs the returned ID, and makes a new window.open call to the "GetPDF" action's URL. This action accepts the PDF ID as a querystring parameter, so it's easy to include it in the URL when making the request. This action locates the correct document on the server, and returns it in a FileResult. The browser will download the document, while not affecting the HTML page being browsed.

problem CasperJS POST via AJAX not working

I'm working on a scraper of my bank statements with CasperJS, so far I've managed to login and get to the statements page. I accomplished to get the table with the first page of the statement, but I need to get it complete.
The bank's web have the option to export to a .txt file (sort of a CSV actually), but in order to download it I have to be able to download the file that comes as an attachment in the response header of a POST request when I submit a form by clicking a button.
So I figured that I could do the POST via AJAX, get the response and output it. I tried running the code on the firebug console and it works, but for some reason it just doesn't work in CasperJS.
Btw, I have tried using --web-security=no , still doesn't work
This is how I'm trying to do it:
this.then(function() {
eurl = "http://bankurl.com";
response = this.evaluate(function() {
params = $("#lForm").serialize();
$.ajax({
type: "POST",
url: eurl,
data: params,
success: function (data) {
return data.responseText;
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
I wasn't able to test this with the code you provided, but it looks as though you just aren't returning anything back from the evaluate().
return __utils__.sendAJAX(url, 'POST', params);
You would probably also need to call CasperJS with the following:
casperjs --ignore-ssl-errors=true /path/to/script.js
Well, after struggling finding a way to solve this I finally did, I just put the ajax call inside a try catch and found that the error was that it wasn't reading the eurl variable (I declared it outside the evaluate). I put it inside and it worked. Thanks for your help

How do I call a JS callback when a file upload completes?

I'm creating frontend upload for an app with appengine backend.
What I want to make is a file upload solution, and I dont want to be using plupload or those kinds of ready-made solutions.
I basically submitted the images to an iframe and then put a cover while it is uploading. Then after it finishes I performed an ajax call to get the image ids for the next view to be rendered. However, the render is always called before the upload is completed, thus I'm not getting any image ids from the backend. can anyonehelp?
here's my code for the upload
perform_input3:(event)=>
event.preventDefault()
$('#product-input-3').hide()
$('#product-input-3').submit()
$('#upload-cover').show()
item_id = $('#item3_id').val()
app.views.imageselect.render(item_id)
the app.views.imageselect.render(item_id) is below:
render:(data)=>
#item_id = data
item_id = #item_id
$.ajax(
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success:(data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
return #
)
I dont want to be using setTimeout function since it will not be flexible depending on the connection speed. Any help will be appreciated :)
Essentially, your question boils down to this: You want to wait to make your Ajax call to the server until the data you're requesting is available. Getting notifications from the server is tricky (depending on how your backend is implemented), so the best solution to your problem is probably to just make the Ajax call periodically (say, once per second) until you get a successful response from the server.
Here's some code that should do that:
do ajaxCall = =>
$.ajax
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success: (data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
error: ->
setTimeout ajaxCall, 1000
If you are only targeting modern browsers, then XHR2's FormData can enable a very simple and elegant approach.
The concept is:
add file(s) binary data to a FormData object
make a $.ajax() call with the FormData object as the AJAX call's "data" parameter
when upload is done, the $.ajax()'s success() or complete() callbacks will be triggered
This approach works with the latest Firefox, Chrome, Safari - http://caniuse.com/xhr2.
See this post for details: Sending multipart/formdata with jQuery.ajax
What you're missing is some sort of callback from the $('#product-input-3').submit() call. I think the following would work (pardon my bad CoffeeScript):
perform_input3:(event)=>
event.preventDefault()
item_id = $('#item3_id').val()
$('#product-input-3').hide()
$('#upload-cover').show()
$('#product-input-3').submit()
$('#target-iframe').ready ->
app.views.imageselect.render(item_id)
This is predicated on the idea that calling 'submit' immediately puts the target iframe into non-ready state, which seems reasonable, but I'd test it. Once it finishes loading The other option I've seen around is to have the page the iframe loads call back into its parent (top-level) window. In JS, something like:
parent.imageUploaded()
Or, if you want to use bound events:
parent.$(parent.document).trigger('upload-complete')
Where, of course, you've set up an upload-complete event on the top-level document object.

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

How to avoid values not to display with the url while using window.location.href to pass values from one page to other?

In my localhost url, am getting all the values which is being passed to the other page are getting displayed in the url.
I dont want it to display the values which are passing,
for example
http://localhost/accounting/credit/credit.php?prod=sdfsdfsd-12&prodId=6&batch=567567
am using window.location.href to pass the values to other page, i think that is the reason its getting added to the url. Is there any other way to pass the values other than window.location.href ? or is there any other way to pass.
Is it possible to make the url not to display the values ?
I just want the url to display as below
http://localhost/accounting/medismo/credit_note/credit.php
How can i do this ?
You can do this pretty simply using jQuery and an HTTP request:
$.ajax({
url: 'credit.php',
type: 'POST',
data: { prod: 'sdfsdf-12', prodID: 6 },
success: function (data, status) {
// Handle successful request
},
error: function (xhr, status, err) {
// Handle request failure
}
});
In this case, data is an object containing all the information you want to pass over to the given url. In your .php file you can access this information using:
$_POST["prod"], $_POST["prodID"], etc.
The tool you are using is called the GET-method to pass variables trough a URI! Another method you can use is the POST-method, which uses html forms (still visible in the source code).
For information about those two HTTP request methods, look here or use Google!
The next best method would be using a php session, where (when used properly) users won't be able to see the variables directly!

Categories