An AJAX request to get the new upload URL - javascript

I'm using Google App Engine for a backend service and I'm trying to upload a file using an AJAX post and their Blobstore API. I got that part working. If you are not familiar with the service, is quite simple. Blobstore API uploads is a two step process: You need to get an upload url and then upload into that url.
Now, I'm implementing an editor, medium.com-like.
The thing is this plugin needs an endpoint for the upload. As my endpoint is not static and I need to update that URL each time, I have prepared an API in the backend that responds with a JSON file with that URL. I'm trying to do an AJAX request to get that URL but I'm getting an error, as the POST request is done to bad url.
This is the POST requet:
INFO 2014-10-19 08:58:22,355 module.py:659] default: "POST /admin/%5Bobject%20Object%5D HTTP/1.1" 200 2594
An this is my Javascript code:
function getURL(callback) {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
dataType: "json",
success: callback
});
};
$('.editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: getURL().done(function(json){return json['url']})
},
embeds: {
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});
I guess I'm doing something wrong with the AJAX return, but if I console.log it I get the result I want. I've read this answer and try to apply it, but I didn't manage to get it working.
Thanks for your time and your help ! :)

If someone ever has the same problem this is the way I solved it. If you are reading this and you now a better one, please, every help is appreciated.
var url; // Set a global variable
// Define the AJAX call
function AJAXURL() {
return $.ajax({
type: "GET",
url: "/admin/upload_url",
success: function(response){
// Sets the global variable
url = response['url'];
}
});
};
// Gets a first upload URL doing an AJAX call while everything keeps loading
AJAXURL();
$('#editable').mediumInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: function getURL() {
// makes a request to grab new url
AJAXURL();
// But returns the old url in the meanwhile
return url;
}
},
embeds: {
urlPlaceholder: 'YouTube or Vimeo Link to video',
oembedProxy: 'http://medium.iframe.ly/api/oembed?iframe=1'
}
}
});

Related

Why is res.sendfile() doesn't work when I call from jQuery ajax?

Issue:
The first ajax is working properly in the main.js, the second one is doing its job at first look but I think there might be a bug somewhere. I can reach the getProducts method after I click to the button.
The product_list.html file should appear on the browser screen, but it doesn't.
I get no error message on the front-end or the back-end.
This is what I noticed: After click to the button -> F12 -> Network -> products -> I can see here a status code: 200 and the product_list.html file content as response.
In case the POST ajax call succeeds and in the case I add: location.href = "/products";, the browser will load product_list.html
I use the get ajax call because i need to pass the jwt token in the req header. (I deleted the jwt authentication parts from the code below because I narrowed down the error to the $.ajax() and res.sendFile() relationship)
//routes.js
routes.get("/products", ProductController.getProducts);
//ProductController.js
var root = path.join(__dirname, '../../views');
module.exports = {
getProducts(req, res){
console.log("getProducts!"); //I can see in the console
res.sendFile("product_list.html", {root}) //It doesn't render the html
},
}
//main.js
$("#btn-login").click(function(){
$.ajax({
type: 'POST',
url: "http://localhost:8000/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"username": $("#login-user").val(),
"password": $("#login-pwd").val(),
}),
success: function(data){
if ($("#login-chkbx").is(':checked')){
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
});
}
}else{
console.log("Checkbox is not checked");
}
}
});
});
What causes the issue and how to solve it?
Thanks!
file should appear on the browser screen
No it does not and it should not. The file should be returned to the ajax function call in the success callback:
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
success: function (file) {
// The file is in the "file" variable above.
// Do whatever you want with it. For example you can replace
// the current page with the returned file:
document.body.innerHTML = file;
}
});
That is the whole point of AJAX - a mechanism for programmers to override the normal flow of HTTP requests that loads the response to the browser page. If it allows you to not load the response to the browser page it also means it will not automatically load the response to the browser page - because doing so will not allow you to not load the response.
If you want to automatically load the response then don't use ajax:
// Replace $.ajax(... with:
window.location.href = "http://localhost:8000/products";
However, this method does not allow you to set custom request header.
in your frontend code you do nothing with the GET /products response
the backend sendfile as the name says it just sends the file over to the requester. Being an ajax call, it must be rendered by the frontend code.
Add something like success: response => $('body').html(response)

Simple POST request using jQuery leads to unexpected redirect

I've got a few similar POST request on a website. In one case, the request is working (data is stored on the server), but then, there's an unexpected redirect. I send/receive data using jQuery. On the backend, I use the PHP framework Laravel.
Let's say I'm on myapp.dev/clients/123. Then I click the store-data-button and data is sent to/received from the server (Let's assume $('#resubmission_note').val() === 'abc'):
// AJAX request
$('#store-data-button').on('click', function() {
let ajaxRequest = $.ajax({
url: '/resubmissions',
type: 'POST',
data: {
// An integer, some text, and a date
'client_id': $('#id').html(),
'resubmission_note': $('#resubmission_note').val(),
'resubmission_due_date': $('#resubmission_due_date').val()
}
});
ajaxRequest.done(function(returned_id) {
// Removed all code here for testing. Browser still redirecting.
});
});
But then the browser is redirected to myapp.dev/clients/123?resubmission_note=abc.
The network tab in Chrome devtools says
Name:123?resubmission_note=abc
Status: 200
Type: document
initiator: Other
There's data appended in the URL, that should only be the case with GET request, AFAIK. I checked whether some other JavaScript code might interfere, but couldn't find store-data-button or resubmission_note in any unexpected files.
Any advice on how to fix the problem or how to debug it?

Jquery get Request Uri too long

I have a project which is built on ASP.NET MVC. There is a database table to store user's details including image, an api to output his details and view where i consume the api by ajax call. My api is returning the base64 value of image perfectly, but a 404 error comes saying request uri too long when i try to display the image.
Relevant lines of code are
$.ajax({
url: // url of api,
type: "GET",
success: function (data) {
var preview = document.querySelector('img');
preview.src = data.Image;
}
})
Does your base64-string start with data:image/png;base64,?
Look here for complete example.

How can i receive data from external url using json?

Recently i am learning json to create apps.I have a doubt in a Json , php based chat system .
In this , the code work fine for same origin policy.But for sending and receiving data from external url, it successfully sends data to external php.But not receiving any data from server.I search in internet to solve this problem , and found jsonp as alternative. I tried jsonp , but i m not sure if am correct because i am new to ajax itself.
Please don't mis understand my question.I want to load a index.html file from localhost , when i send request to external url (anysite.com/xx/ajax.php) .It process and returns the data back to index.html.But the problem is my data is sended finely and processed on the server but it doesn't return to remote file.But it works fine for same server.
$.tzPOST = function(action,data,callback)
{
$.post('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
please help me with a code.
You cant receive JSON from external web by JavaScript, because of the policy.
But you can do AJAX request on your PHP file and there you can get the JSON by file_get_content http://cz2.php.net/file_get_contents function.
For using(working) with jsonp, u can take ready solution jquery-jsonp
from GitHub.
Example of using (by you question):
$.tzGET = function(action,data,callback){
var url = 'http://anysite.com/xx/ajax.php?action='+action;
$.jsonp({
type: 'GET',
url: url,
callbackParameter: callback,
dataType: 'jsonp',
data: data,
timeout: 10000,
success: function(json){
alert('success')
},
error: function(){
alert('error')
}
});

Downloading a file using AJAX in an EXT.JS blind

I've got the following ajax call:
var blind = Ext.create('MyApp.view.blind.Progress', {});
blind.show();
Ext.Ajax.request({
url: config.url,
params: {
nodeId: config.data[0].value,
fileName: config.data[1].value,
startDateTime: config.data[2].value,
endDateTime: config.data[3].value,
reportFormat: config.data[4].value
},
success: function (response) {
console.log(response);
blind.close();
}
});
I want to display a blind with a loading graphic, and close it upon completion. Is there any way to use this ajax callback to download the file from the response? Am I on the right track? I would like to avoid using iframes or opening new tabs if possible. I'm open to using other libraries like jquery if it's easier.
Don't think its possible to respond with a file to an ajax request. a simple form submit should do the trick.
Well I don't like being told what I can't do so I kept researching and found this jquery plugin. It works by polling a cookie made by the server when the file is delivered, and the typical iframe method for downloading files. No bloat, no flash, exactly what I was looking for:
Jquery File Download
Download the plugin, link it somewhere in your site, and add this cookie generation code to wherever your file request is going (there are more examples at the link, I'm using ASP.NET):
HttpContext.Current.Response.SetCookie(new HttpCookie("fileDownload", "true") { Path = "/" });
Sample code from my app, using the success and fail callbacks of the plugin to control my extjs blind:
$.fileDownload(config.url, {
successCallback: function (url) {
//Show a message here or perform some task
blind.close();
},
failCallback: function (html, url) {
blind.close();
alert("The report generation failed.");
},
httpMethod: "POST",
data: {
nodeId: config.data[0].value,
fileName: config.data[1].value,
startDateTime: config.data[2].value,
endDateTime: config.data[3].value,
reportFormat: config.data[4].value
}
});

Categories