How to fetch object from aws s3 using ajax get rest api - javascript

I have a file named 3514706-ironmanvr-promo-nologo.jpg in my s3 bucket and I am trying to download the file using javascript rest api, here is my code
var jqxhr = $.ajax({
url: "https://s3.amazonaws.com/asif.test/3514706-ironmanvr-promo-nologo.jpg",
type: "GET",
async: true
})
.done(function (data, textStatus, jqXhr) {
console.log(data);
})
.fail(function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
if (errorThrown === "abort") {
alert("Uploading was aborted");
} else {
alert("Uploading failed");
}
})
.always(function (data, textStatus, jqXhr) { });
but in data I am getting garbage values like this
response image
I don't know how to deal with this.

I was having the exact same issue, and after much digging and hair-removal I came across this answer:
https://medium.com/#timleland/set-image-src-from-amazon-s3-2232d246bebd
It solved it for me; the article says:
"Since Jquery ajax does not support the responseType: ‘blob’, you have to set the value in the xhrFields. The other important part is to use window.URL.createObjectURL to convert the blob to a url for the image src."
var loadImage = function (imageUrl) {
$.ajax({
type: 'GET',
url: imageUrl,
dataType: null,
data: null,
xhrFields: {
responseType: 'blob'
},
success: function (imageData) {
var blobUrl = window.URL.createObjectURL(imageData);
$('#image-id').attr('src', blobUrl);
}
});
};

Related

Access post data from inside ajax error function

I have the below javascript function that takes POST data and sends post request to server using Ajax
function postData(post_data) {
console.log(post_data, "----------->");
var data = post_data;
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
// Can we access the post_data inside this error function ?
},
}
);
};
So what my actual point is, because of some reason the server is sending a 500 response and so the execution point is coming to error: function (jqXHR, textStatus, errorThrown, data), here I want to access post_data to display something to the user.... So can we access the post_data inside ajax error function above?
In case someone looks for a generic way to do this, here is how i did it: In case your handler functions are defined where their scope don't allow you to access some variables, you can add them to the ajax object itself in the function beforeSend. You can then retreive it in the ajax object by using this.
$.ajax({
url:'/dummyUrl',
beforeSend: function(jqXHR, plainObject){
plainObject.originalUrl = 'myValue';
},
success: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
$('#myValue').html(this.originalUrl);
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">waiting result</div>
<div id="myValue"></div>
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function (jqXHR, textStatus, errorThrown, data) {
// handle error
console.log(post_data); // and the magic happens
},
}
);
};
Above this issue you were having wrong key "dataType" i have modified it. Secondly, "post_data" is in your scope you can access it without any issue.
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataType: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function ( jqXHR jqXHR, textStatus, errorThrown) {
// post data is in your scope you can easily access it
console.log(post_data); // and the magic happens
},
}
);
};

Post AJAX API Javascript SAPUI5 failed

I want to use POST method with AJAX in SAPUI5 javascript but I found an error.
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({
nomorDosir: "01001961288",
kodeCabang: "A02"
}),
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: " + data + " " + JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});
error:
I already did change code with dataType=text, or data: {nomorDosir: "01001961288", kodeCabang: "A02"} (without stringify), but I not yet find the solution. How to fix this problem?
Thanks.
Bobby
Not sure what your use case is but if you are trying to post to an oData service, it might be much easier to use SAPs createEntry method where the URL is the path to the model you want to post to and your JSON are the properties:
var oModel = new sap.ui.model.odata.v2.ODataModel("https://services.odata.org/V2/OData/OData.svc/");
//oModel should use your service uri
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
oModel.createEntry(url, {
properties: {
nomorDosir: "01001961288",
kodeCabang: "A02"
}
}, {
method: "POST",
success: function(response) {
alert(JSON.stringify(response));
//do something
},
error: function(error) {
alert(JSON.stringify(error));
}
});
oModel.submitChanges();
What you have is wrong json format, you have:
data: JSON.stringify({nomorDosir: "01001961288", kodeCabang: "A02"}),
Which actually should be:
data: {"nomorDosir": "01001961288", "kodeCabang": "A02"},
Which then you don't need to do a json.stringify on, because it already IS a json format. Hope this will help you out.
Which you could also try is setting a variable outside like this:
var url = "https://xxxx*xxxx.co.id:8877/TaspenSAP/SimpanDosirPunah";
var json = {"nomorDosir": "01001961288", "kodeCabang": "A02"};
$.ajax({
type: "POST",
url: url,
data: json,
dataType: "json",
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data, textStatus, xhr){
console.log("sukses: "+data+" "+JSON.stringify(xhr));
},
error: function (e,xhr,textStatus,err,data) {
console.log(e);
console.log(xhr);
console.log(textStatus);
console.log(err);
}
});

Fake path Javascript Issue

When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp

Cannot return whole JSON object back to calling function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I am new to AJAX and I need to find a way to return an AJAX JSON response back to the calling function. Is there any way to achieve this.
My code snippet:
function requestAjaxWebService(webServiceName, method, jsonData) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
return returnData;
}
jQuery.ajax() performs asynchronous HTTP request. Hence, you can't return its response synchronously (which your code is trying to do).
If the request succeeds, the success(data, textStatus, jqXHR) handler will get called at some point (you don't know when).
Here is one way you could modify your code:
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: function (data, textStatus, jqXHR) {
callback(true, data); // some method that knows what to do with the data
},
error: function(jqXHR, textStatus, errorThrown){
callback(false, errorThrown);
}
});
}
callback should be a reference to a method like:
function onData(isSuccess, dataOrError)
{
if (isSuccess) {
// do something with data
} else {
console.error(dataOrError);
}
}
Update If the settings object is needed in the callback for some reason:
function onData(isSuccess, settings, jqXHR, errorThrown)
{
if (isSuccess) {
// do something with the data:
// jqXHR.responseText or jqXHR.responseXML
} else {
// do something with error data:
// errorThrown, jqXHR.status, jqXHR.statusText, jqXHR.statusCode()
}
}
function requestAjaxWebService(webServiceName, method, jsonData, callback) {
var settings = {
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
};
settings.success = function(data, textStatus, jqXHR){
callback(true, settings, jqXHR);
};
settings.error = function(jqXHR, textStatus, errorThrown){
callback(false, settings, jqXHR, errorThrown);
};
$.ajax(settings);
}
requestAjaxWebService("name", "POST", "json", onData);
You can also use .done() and .fail() callbacks of jqxhr object instead of callbacks in settings object, as obiTheOne's answer suggests. It may look neater, but is not actually important here.
jQuery.ajax is an asynchronous function, so normally it doesn't return anything.
You can anyway return a value to the original function by setting the async option to false, but is not recommended, because a synchronous request will block the rest execution of the rest of your code until a response will be returned.
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
var returnData;
$.ajax({
url: webServiceName,
type: method,
async: false,
data : jsonData,
dataType: "json",
success: function (data) {
returnData = data;
},
error: function(error){
returnData = "Server error";
}
});
}
take a look at this example: jsbin sync ajax example
You should instead use a callback (the standard way) to handle the response
function onSuccess (data) {
console.log(data);
}
function onFail (error) {
console.log('something went wrong');
}
function requestAjaxWebService(webServiceName, method, onSuccess, onFail) {
$.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json",
success: onSuccess,
error: onError
});
}
Or you can return a Promise (a sort of async object) that will change value as soon as the request will be fullfilled
function requestPromise (webServiceName, method) {
return $.ajax({
url: webServiceName,
type: method,
data : jsonData,
dataType: "json"
});
}
requestPromise('...', 'GET').done(function (data) {
console.log(data);
});
refs:
jquery.ajax params

asp.net ashx handler: can't receive response

Hello everyone and thanks for your time.
Here is my javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
And here is the code in my .ashx handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
While the click event is working, my Ajaxrequest doesn't seem to get any response as the alert at success doesn't popup. I've debugged using the browser's network console and it return the expected response but it doesn't seem to reach the success function in the JavaScript code. Any insights or suggestions are welcome. Thanks.
In case you are still interested in the answer, try this before doing the request
var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);
and change your AJAX request to
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
// do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error");
console.log(textStatus);
console.log(errorThrown);
});
Explanation
You are trying to send the plain data object. You must transform it into a Json string using JSON.stringify(object).
Changing the dataType isn't really a solution but a workaround.
Additional Notes
Also, I think you should use .done() and .fail(). See here for further details.

Categories

Resources