Converting native JS Ajax snippet to JQuery alternative? - javascript

I am updating historic JS code from another author but having problems converting the below to the JQuery alternative:
var xhr = new XMLHttpRequest();
xhr.open('GET', songurl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(this.response);
}
}
xhr.send();
This is more so to aide consistency, Chrome - developer tools is also suggesting the code to be re-factored.
Here is what I have started with (appreciate it's not much!), the issue I'm having is checking the status code and returning the response if the status code is 200.
$.ajax({
url: songurl,
method: 'GET'
);

You want to attach a function for success.
$.ajax({
url: songurl,
method: 'GET',
success: function(response){
//do stuff with response
}
})

ajax(), or the shorthand get(), will do all that for you. There's a success() function that's only called on a successfull, 200-status request:
$.get( songurl,
function(data) {
document.getElementById('songdiv').innerHTML = '';
song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(data);
},
'blob'
);

Related

PDF File download from AJAX Post success callback

When I try to link to a data-generated file that I've set up to be rendered as a PDF document, this works to open a PDF document in a new window, but only for small sets of data:
window.open(myUrl + params, "_blank", "menubar=no,status=no");
I need it to work for something like this so I can make my PDF compatible with larger data sets. I tried passing the params in the data section of the ajax request but it doesn't work for PDF documents only. It works for Word and Excel documents. When I try the same thing as a PDF, it returns a download to a broken PDF object.
$.ajax({
type:"POST",
async:true,
url: myUrl,
data: params,
success: function(result,status,jqhxr) {
var blob=new Blob([result]);
var link=document.createElement('a');
link.setAttribute('target','_blank');
link.href=window.URL.createObjectURL(blob);
link.download="PreviewProposalAsPdf.pdf";
link.click();
}
});
What do I need to do to get this to render a PDF correctly? Ideally I'd like to navigate directly to the PDF page in a new window, but I will settle for a clickable file download. Please post the full solution directly if possible. I've spent a ton of time on this and my time is now running short.
I looked for the solution on other questions but none of the solutions worked. In some cases, what I'm already trying was posted as a solution. Please help.
Thanks
The result you get back from using jQuery ajax is plain text and can lead to "out of range" for downloading binary as text and not as arrayBuffer or blob. jQuery don't support responseType in any way (that i know of)
So you need to rely on xhr or fetch to get it as a blob to get the content right. Otherwise you will get corrupt data
Here is an example of using the new fetch api and FileSaver
function saveAs(blob, filename){
if(navigator.msSaveOrOpenBlob)
return navigator.msSaveOrOpenBlob(blob, filename)
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = filename
link.click()
}
fetch(myUrl, {
method: 'post',
body: JSON.stringify(params)
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(res => res.blob())
.then(blob => saveAs(blob, 'PreviewProposalAsPdf.pdf'))
// EXAMPLE USING XHR
var req = new XMLHttpRequest
req.open('GET', myUrl, true)
req.responseType = 'blob'
req.onload = function() {
saveAs(res.response, 'Dossier_' + new Date() + '.pdf')
}
req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
req.send(JSON.stringify(params))
But ofc, there is more wider support if you use xhr + responseType = blob
The best thing you can do is just send content-disposition header and make a attachment - but then you can not use ajax... need to submit form (could be from iframe)
Another solution using $.ajax & FileSaver
I think the xhrFields should be the answer you look for...
$.ajax({
type: "POST",
url: "your-url/to/pdf/response",
data: params,
xhrFields: {
responseType: 'blob' // without this, you will get blank pdf!
},
}).done( function(res) {
blob = new Blob([res], { type: 'application/pdf' })
saveAs(blob, "response.pdf")
}).fail( function() {
alert("Error! Please try again later...");
});
This is the correct answer, without using the SaveAs function:
var req = new XMLHttpRequest();
req.open("POST", myUrl, true);
req.responseType = "blob";
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(data);
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
console.log(req.responseText);
}
}
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};
Ultimately it solved my problem. Thank you, Endless.

How can I make a Ajax request & response with firefox OS?

I'm having a php function which returns a Json data from db.
I want get all the json from the function and display that into my Firefox App. I tried Jquery Ajax. But its not working.
Any other library or Ajax coding?
var a=1;
$.ajax({
url:"http://localhost/shop/home/home/demo",
type:"POST",
data:{b:a},
success: function(msg){
alert(msg);
}
});
It's not working with firefox app. Help me.
You must use the mozSystem property. Here's an example using native XMLHttpRequest.
var xhr = new XMLHttpRequest({
mozSystem: true
});
xhr.open("POST", "http://localhost/shop/home/home/demo");
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send("b=" + a); //serialized data
Hope it helps!

Jquery Ajax function is not working while calling the Servlet

I am facing some problem while calling ajax. Can anyone look at my code and suggest something to solve my problem
function search(file,input){
$.ajax({url:'/Searchandhighlight?name='+input+'&file='+file,type:"post",
success:function(){
$("#bodyy").html();
}
});
}
I am using ajax to call the servlet and servlet changes some contents of database and after success I am trying to refresh my "#bodyy" div.
Thanks in advance
Firstly let us know what file variable holds.
Normally Ajax call with parameters goes like this. dataType depends on what kind of response you are expecting.
$.ajax({
type: "POST",
url: "/Searchandhighlight",
dataType: "json",
data: {"name" : input, "file" : file},
success:function(data){
if(data){
alert("success");
}
},
error:function(){
alert('failed');
}
})
I finally solved my issue by following code
function search(file,input){
if(input != "") {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Searchandhighlight?name=" + input + "&file=" + file, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location.reload();
}
}
xmlhttp.send(null);
}
}

How to pass AJAX variables to PHP

I understand I can't pass AJAX Vars directly to PHP, being a client versus server side script. But that being said, here's my code:
setInterval(function()
{
//do something after you receive the result
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("message_area").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","messages.txt",true);
xmlhttp.send();
}
I know I can indirectly process AJAX variables by POSTing them to a PHP page using AJAX, like so:
$.ajax (
{
type: "POST",
url: "decode.php",
});
I just need to know how to pass the contents of the "messages.txt" file used in the xmthttp.open call to a PHP file for further processing.
How can I do this?
If you are using pure javascript:
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
or if you're using jquery, simply:
$.ajax (
{
type: "POST",
url: "decode.php",
params: {param1: "val1", param2: "val2"}
});
Hope this helps :
$.get( "messages.txt", function( data ) { //Fetching contents of messages.txt file.
$.ajax ({
type: "POST",
url: "decode.php",
data: data, //passing contents of messages.txt file to decode.php
success: function(result){
alert(result);//Getting result from decode.php
}
});
});
cheers
Are you using jquery? You first code block is regular js, the second is jQuery's ajax short hand.
That said, if you want to POST data with ajax using jQuery, you would do something like the following.
var PostData = "something";
$.ajax({
type: "POST",
url: "someurl",
data: PostData
}).done(function(returnData) {
//process data returned from server, if there is any
});

Javascript AJAX call to Jquery Call

In order to have my code written almost fully written in Jquery, I want to rewrite an AJAX call in Jquery.
It's a call from a webpage to a Tomcat servlet.
Similar code of my present situation:
var http = new XMLhttpRequest();
var url = "http://example.com/MessageController?action=send";
http.onreadystatechange = function ()
if (http.readyState == 4)
{
if (http.status == 200){ var response = http.responseText;}
else {/*code2*/}
};
http.async = false;
http.open("POST", url, true);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(string);
Which would be the best way to do this? .ajax or .post? Could you help me with some pseudo code to start this?
Use .ajax or (as you are using POST) .post:
$.ajax({
url: "http://example.com/MessageController",
type: "POST",
data: { action: "send", yourStringName: "something" },
async: false, // make sure you really need it
contentType:'application/x-www-form-urlencoded'
}).done(function(response) {
console.log(response);
});
It doesn't matter which one you use, because .post is shorthand for .ajax.
You can use jQuery post.
var url="MessageController"
$.post(url, { action : "send"} ,function(data){
//response from MessageController is in data variable
//code 1
alert(data)
}).error(function(){
alert("error"); //code 2
})
Assuming MessageController is some url in your domain and you are aware of the same origin policy

Categories

Resources