Unable to upload form data and file contents on submit - file-upload

I am attempting to use jQuery-File-Upload for showing the preview of the uploaded image. This is working fine. The code for file upload is as shown below
$('#Image').fileupload({
url : "/FileUpload/Upload",
autoupload:false,
add: function (e, data) {
gm.layout.loaderOpen(); //open loader
data.submit();
},
done: function (e, data) {
console.log("done")
if (data.response().jqXHR.status === 200)
$('#processImage').attr('src', data.response().jqXHR.responseText);
},
always: function (e, data) {
gm.layout.loaderClose();
}
})
However apart from the image preview the form also has other fields which the user fills up and then submits the form. Now I am trying to use ajax to submit and collect the data by serialzing the form
var formData = $('form').serializeArray();
$.ajax({
type:"POST",
url: "{url}",
data: formData,
contentType: false,
processData:false,
success: function (data) {
alert("whatever");
}
});
This ajax submit fails as long as I have the fileupload for the html input control. With the file upload the multimedia data doesn't reach the server on submit
However, in the absence of fileupload for the same control, everything works fine and I can get the file content on the server.
Any idea what I am doing wrong?

Related

grails redirect to another view

i am trying to create status page which check database for the job status every 5 minutes and then updates the user about the status of the job..
So once the job is finished, I want to move from the current page to result page..
To update the status i m using JavaScript :
function() {
setInterval(function() {
var uuid =" \'${uuid}\'";
var jobid =" \'${jobid}\'";
console.log();
$('#checkstatus').load('/jobque/connectdatabase',{jobid:jobid,uuid:uuid});
}, 5000);
});
Checking status works correctly. I tried using redirect or forward but both these terms loads the result page into current page. I want to go to next page not load into current page ..
What are the other option available ?
Your javascript uses jquery to load the results of a call to a controller action into the named element.
Why not check the result of your call to the controller action and if it indicates success, then use javascript to redirect to your desired page.
controller action:
def checkStatus() {
if (status_check_ok) {
render 'url_of_page_for_redirect'
return
}
render status:409 // failure
}
javascript on web page:
$.ajax({
timeout:5000,
type: 'POST',
url: controller_action_url_for_checkStatus,
success: function(data){
window.location.href=data
},
error: function(data){
// do something else
}
});

Using Fetch instead of XMLHttpRequest in React Native

I was trying to upload images to S3 from my react native app by following and adapting this guide by heroku: https://devcenter.heroku.com/articles/s3-upload-node
Essentially I am using the aws-sdk on my express.js backend to generate pre-signed request for uploading images to S3 from react native.
Everything works well, so then I tried to convert the XMLHttpRequests into fetch requests, which seem to be favoured by react native. After the conversion, the files are still being uploaded to S3, but when I click on the image links, then the images wouldn't not show properly, instead an empty square is shown:
Empty square shown instead of image
More specifically it seems to be this piece of code conversion that causes it to happen:
From:
_uploadFile(file, signedRequest, url){
const xhr = new XMLHttpRequest();
xhr.open('PUT', signedRequest);
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status === 200){
console.log("UPLOAD DONE");
} else {
alert('ERROR UPLOADING');
}
}
};
xhr.send(file);
}
To:
_uploadFile(file, signedRequest, url) {
let option = {
method: "PUT",
headers: {
"Content-Type": "image/jpeg",
},
body: JSON.stringify(file)
}
fetch(signedRequest, option)
.then(res => console.log("UPLOAD DONE"))
.catch(err => console.log("ERROR UPLOADING: ", err))
}
The file object being uploaded:
{
name: "profileImage",
type: "image/jpeg",
uri: 'data:image/jpeg;base64,' + response.data, //just a base64 image string
isStatic: true
}
Could anyone shed some light on why this could be happening, or have had similar experiences? Many thanks!
In your fetch example you put a JSON string in your body. It will be sent to S3 but it will not be interpreted as an image upload. You should be able to construct a FormData object yourself and pass it to fetch as the request body, but I think using XHR is the simpler option. According to this comment it's what Facebook does as well (the comment is over a year old).
If at all possible you should also try to use local URIs instead of passing Base64 encoded data. It takes quite a while to transfer a few MB of image data between JS and native.

How to POST data to a server in Sencha Touch without using AJAX

I am using Sencha Touch, I need post some data to a Server with a simple HTTP POST (NO AJAX)
At the moment I use
Ext.data.JsonP.request
Ext.Ajax.request
for my understanding both work with AJAX.
I would like to know how to disable the AJAX functionality and allow me to send some paramenters only via HTTP without using xhr and ajax.
You can create a form panel and then call the submit method with a url for the form to be submitted to:
// define your form
var form = Ext.create('Ext.form.Panel', {
...
// your form fields, etc
});
// later, in some handler for a button click, etc
form.submit({
url: 'url/to/submit.php',
method: 'POST',
success: function() {
// handle successful form submit
},
failure: funciton() { ... }
});

Ext.data.JsonP.request timeout

I have written a controller. When I click the button from view, this controller generic 'button' is called as follows:
'button': {
tap: function() {
Ext.data.JsonP.request({
url: 'http://download.finance.yahoo.com/d/quotes.csv',
params: {
s: '^BSESN',
f: 'nsl1op'
},
callbackKey: 'callback',
scope: this,
success: function( res, req ) {
Ext.example.msg('Sucess!', 'CSV file successfully generated.');
Ext.data.StoreManager.get('Files').load();
},
failure: function( res, req ) {
console.log('Failed to load csv file.');
}
});
....
....
....
It timesout and failure is called "Failed to load csv file."
The original URL I am using is "http://download.finance.yahoo.com/d/quotes.csv?s=^BSESN&f=nsl1op".
I would like know where I am going wrong.
You're requesting a CSV file via JSONP.
The file will be injected into the DOM via a '' tag (which is how JSONP works), but since it's not a valid JavaScript file, your callback (callbackKey: 'callback') is never executed, so Sencha Touch will fire the timeout handler, seeing the callback has not been fired by the injected <script> tag.
You probably need to change the URL to something that is actually JSONP (iow valid JavaScript wrapped in a callback), not a CSV file.

google places api error with jquery ajax call... html_attributions

I'm using the new google places api with jquery/ajax. When I run this code:
$.ajax({
url: "https://maps.googleapis.com/maps/api/place/search/json?location=40.7834345,-73.9662495&radius=50&sensor=false&key=Your_API_KEY_HERE",
dataType: "jsonp",
data: {
name: 'rogue'
},
success: function( data ) {
console.log(data)
}
});
I get this error: invalid label html_attributions []; I think this is preventing me from seeing the output object in the console, although I can see the response coming back fine in the json tab in firebug
It seems like the places api does not support ajax so far.
It not enough that the server responds with proper JSON. The answering server has to support JSONP and surround the JSON answer with a callback generated by jQuery. The response must look like that:
jQuery17101705844928510487_1324249734338({"data":"whatever"});
The hack that JSONP does, is to interpret the response as script, because the script-Tag is not affected by the Same-Origin-Policy. Without the callback you have no chance to do that in the browser.
If its not supported you have to do the requests from your server..
Server-Example with PHP:
<?php
header("Content-Type:text/javascript"); // avoid browser warnings
$request = new HttpRequest("http://programmingisart.com/json-data-source.php", HttpRequest::METH_GET);
$request->send();
$json_data = $request->getResponseBody();
// wrap the data as with the callback
$callback = isset($_GET["callback"]) ? $_GET["callback"] : "alert";
echo $callback."(".$json_data.");";
Client-Example with jQuery:
<div id="json-result"></div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "jsonp-wrapper.php",
success: function(data) {
$("#json-result").html(JSON.stringify(data));
},
error: function() {
alert("error");
}
});
});
</script>
You can replace the PHP-code with any other server-platform and do the required steps.
HTTP-Request to a JSON source
Wrap the JSON as with a callback-function