POST file data with AJAX is appending unknown jquery callback string - javascript

I'm building a configuration file web editor that lets the user edit settings in a textarea, converts the contents to a Blob file, and then POST the data to a remote API. For some reason, it's appending a random callback parameter and I have no idea where it's coming from...
http://ipaddr:8080/compile?callback=jQuery341029448751790349491588432312011&=1588432312012
Here is what the code looks like. If anyone can point me in the right direction, I would greatly appreciate it.
<script>
$(document).ready(function() {
$('#btnCompile').click(function(event) {
// Convert TextArea contents to a Blob file
var configText = $('#configuration').val();
configText = configText.replace(/\n/g, "\r\n"); // retain line breaks
var configFile = new Blob([configText], { type: "text/plain" });
var documentData = new FormData();
documentData.append('file', configFile, "configuration.cpp");
$.ajax({
url: "http://ipaddr:8080/compile",
method: "POST",
data: documentData,
dataType: 'jsonp',
crossDomain: true,
cache: false,
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
alert('success: ' + textStatus);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error status: ' + textStatus + ' error message: ' + errorThrown);
}
});
});
});
</script>

You said dataType: 'jsonp' and so your request is subjects to the limitations of JSONP (including being a GET request, putting data in the query string, adding a callback argument, and being unable to set custom request headers).
If you don't want that (and everything about your code indicates you don't), don't use JSONP. It's a dreadful hack with a security risks that was superseded by CORS over a decade ago.

Related

slim framework and ajax. '/' character as a parameter

I'm making an ajax call to a Slim framework web service. This is for sending notes to my database.
The problem is that the users can write for example "send 1/2 piece". So when I make the call, the URL throws 404 not found because of the '/' character.
Is there any way to avoid this problem?
notes = 'send 1/2 piece'
$.ajax({
type: 'GET',
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + notes,
dataType: "json", // data type of response
beforeSend: function(xhr, settings){
},
success: function(data){
},
error: function(xhr, status, errorThrown){
errorPopup(errorThrown);
},
complete: function(xhr, status){
}
});
You need to run EncodeURIComponent against notes, only.
Before your ajax call:
notes = 'We have funny characters in here like /es';
encNotes = EncodeURIComponent(notes);
Then, create your url string using the encoded string.
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + encNotes,

Trying to send specified values as FormData with Jquery sends ?[object%20FormData]

I'm trying to send some FormData via a simple jquery ajax GET/Post but for some reason my formData is not getting set right. I end up with ?[object%20FormData] as my payload.
I'm a bit new to this FormData stuff, but I was able to use it successfully with file uploads no problem using this same technique... Here's what I'm doing with my specified values I want to send:
I should note: I'm not using any form element to grab these values from.
var data = new FormData();
data.append("date", curDate);
data.append("serviceID", sID);
data.append("attSummID", asID);
data.append("totalCount", 0);
data.append("visitorCount",0);
data.append("reset",false);
$.ajax({
url: '/4DACTION/WEB_ServiceCounts/',
processData: false,
contentType: false,
data: data,
dataType: 'json',
type: 'GET',
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert('ERRORS: ' + textStatus);
}
});
Any tips?

Show a pdf stream in a new window

I'm generating in a server a PDF document that I want to show then in the client. The server side looks like following:
ByteArrayOutputStream baos = generatePDF();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
response.setContentLength(baos.size());
baos.writeTo(response.getOutputStream());
In the client, I have the following code to get retrieve the PDF:
$.ajax({
type: "POST",
url: url,
data: {"data": JSON.stringify(myData)},
success: function(data, textStatus, jqXHR) {
window.open("data:application/pdf," + escape(data));
},
error: function(jqXHR) {
showError("...");
}
});
It looks well, the new window is opened, but the PDF is not shown. It always appears an empty document.
Nevertheless, if the client looks like following, it works fine:
var form = $("<form target='_blank'>").attr({
action : myURL,
method : "POST"
});
var input1 = $("<input type='hidden'>").attr({
"name": "data",
value: JSON.stringify(myData)
});
form.append(input1);
$("body").append(form);
form.submit();
form.remove();
But I can't use the second way cause I need to manage the errors, and I can't do it using form.submit().
Any idea about what's happening with the PDF?
You can get base64 string of your pdf stream and pass it to response.
And your method change
$.ajax({
type: "POST",
url: url,
data: {"data": JSON.stringify(myData)},
success: function(data, textStatus, jqXHR) {
var pdfWin= window.open("data:application/pdf;base64, " + data, '', 'height=650,width=840');
// some actions with this win, example print...
},
error: function(jqXHR) {
showError("...");
}
});
Try using:
dataType: "application/pdf",
success: function(data, textStatus, jqXHR) {
window.open(escape(data), "Title", "");
},
I couldn't do this async, but this js returns the attachment ok for me:
$('<iframe src="url"></iframe>').appendTo('body').hide();
The browser then fires a save/view popup, which is fine for my requirements; no error handling though.
I think with your server side, you might want to return it as inline e.g. response.setHeader("Content-Disposition", "inline; filename=file.pdf");
You're setting the content length OK, it could be the success code will be firing twice, the first time at the beginning of the stream and the second time at the end.
Do let us know if you got this working.

Receive serialized in php data by using ajax

I have a php script, which return serialized in php data. And I try to receive this data by using $.ajax() method from jQuery 1.7. Here is the example.
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res) {
alert('COMPLETE() done');
console.log(res);
}
});
In console I see only
Object { readyState=0, status=0, statusText="error"}
So, what I do wrong? Could you help me please?
UPD
Interesting notice: if I use JSONP dataType request can receive data, but can't process it.
Here is an example.
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
dataType: 'jsonp',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Instead of complete: use success: then res will be the returned data from your ajax request.
Remember to use error: as well incase there is an error with you call, as it seems that there might be in your console output.
Code:
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Your code is probably fine, but you're trying to violate the same origin policy. Basically, if your site is http://aaa.com/, you cannot make AJAX called to http://bbb.com/.
There are a few ways around it:
Getting around same origin policy in javascript without server side scripts
But most of them require that both sides play nice.
The response is the second parameter of complete function:
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res,response) {
alert('COMPLETE() done');
console.log(response);
}
});
More info: http://api.jquery.com/jQuery.ajax/
You should also consider using JSON, not php serialized data

Posting to YouTube API with jQuery

I am trying to post a request to the google authSub for youtube. I use jQuery for AJAX posts etc. When I make the POST I get a 405 error: "405 Method Not Allowed".
Here is my js:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
},
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
});
The page I am using in the API for this is here.
Here is what the error looks like:
Your data parameters for the request are misplaced see below:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
data: {
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
}
});
Now it may be something youre doing wrong additionally, but this for sure needs to be corrected.
Ah, here is a solution to the problem. If I make the request with the url built out and assigned as an href to an anchor or call it in window.open(); it works.
window.open('https://www.google.com/accounts/AuthSubRequest?scope=http://gdata.youtube.com&next=http://' + globalBrand + '/sitecreator/view.do&session=1');
As for why jQuery's method with the ajax was being rejected I know not. It seems to be an issue elsewhere also.
Solution to error HTTP HEADER OPTIONS in JQuery, this request is ok for me:
var word = 'search+word';
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/api/videos?q="+word+"&max-results=10&alt=json-in-script&format=5,
cache: false,
dataType:'jsonp',
success: function(data){
//json 'data' var treatment
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert("Not able to fetch the data due to feed unavailability!!!");
}
});
Reference: http://www.mohammedarif.com/?p=180

Categories