YUI3 io-upload-iframe - javascript

Can you use yui3's io-upload-iframe to send form data along with the file upload? I am setting the form's id, like I normally would to serialize the form data, but since I am setting upload : true, it doesn't seem to pass any form data with the request. Here is the code I am using.
var cfg = {
method: 'POST',
form: {
id: Y.ong('#myform'),
upload: true
}
};
var request = Y.io(requestURL, cfg);

Related

Sending a file and json data with AJAX

I have tried two methods of sending the file and json data from client side over to server side. I been partially successful with both methods, I could use some help on completing this. I have two methods:
Method 1: I am able to access the file server side, but my form data (input, select, textarea) are not available to access.
Method 2: Appends the data to the formData object. The issue with method one is that I got it to work the other day, but I believe my browser cached the code and now its not working, so I feel like im back at step one. I am able to access the data by using request.data, but its bytes. The code that was working (request.form['json_data'] or request.files['file'].read()) and now its not working.
Client Side Code:
$('form[name="upload-form"]').on('submit', (event) => {
event.preventDefault();
$('#form-loader').fadeIn()
// Method 1
// let formData = new FormData($('#upload-form')[0]);
// Method 2
let entry = get_form_entry('upload-form'); -> UDF to get all form data. Iterates each form data and applies .val() and creates a dict.
const formData = new FormData();
formData.append('json_data', JSON.stringify(entry));
formData.append('file', $('#file')[0].files[0]);
$.ajax({
data: formData,
url: '/newEntry',
type: 'POST',
contentType: false,
processData: false,
cache: false,
success: function () {
$('#form-loader').fadeOut()
},
error: function () {
$('#form-loader').fadeOut()
},
})
})
Server Side Code:
json_data = request.form['json_data']
# json_data = request.data
file_data = request.files['file'].read()

Can I send information in url similar to get method in a form using AJAX?

I want to send data to another page like using get method in a form when submitting form using php for example when I send data to a page test.php
I want it become like test.php?username=something here....
let headers = {
method: "GET",
data: {
username: "something here"
},
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
let data = await fetch('test.php', headers);
I want after I send that data to the test.php the $_GET has 'username' => something here
Note that this code is written inside an async function

Javascript Equivalent of Swift HTTPbody

I am looking for a way to put variables in to a AJAX get call, now i know the obvious way to do it would just be to add it too "data" like so
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication', favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});
But this goes to an api and the api also handles request from an iOS app which put the data into httpBody like so
let json: [String: Any] = ["userid":userID, "message":applicationtext.text, "favourid":selectedFavour]
let jsondatatosend = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = "myurl";
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsondatatosend
I believe the reason i did this origionally was it was messing up because of having strange characters in the URL so i had to send it through the body which all worked well, but now im trying to get a website to follow the same method on my api i would like it to be sent in the body from ajax so my php can do this function
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
I understand there are many ways for me to get around it in my php just use $_GET[' var '] instead of file_get_contents when it is sent from the AJAX of my website but i was wondering if there was a way of sending it into the body via ajax so i dont have to change the php file and then it is not sent through url's
so what i want to be able to do is something like this
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication'},
httpBody: {favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});

Upload Attachment and some additional parameters to MVC Controller

I have a MVC Controller with the following signature:-
[HttpPost]
public async Task<JsonResult> SaveBrochureAsAttachment(Guid listingId, HttpPostedFileWrapper attachmentFile)
{
///some logic
}
How do I make an ajax call and send the file attachment and additional listingId parameter. Currently I am only able to send the attachment like this:-
var uploadFile = function () {
if ($('#attachmentFile').val()) {
}
else {
alert('No File Uploaded');
return;
}
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/Listing/SaveBrochureAsAttachment',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert('File Uploaded');
},
error: function (jqXHR, textStatus, errorThrown) {
$("#FileUpload").replaceWith($("#FileUpload").val('').clone(true));
alert('File Uploaded Error');
},
cache: false,
contentType: false,
processData: false
});
return false;
}
Currently as you folks can see I am only able to send the attachment. How do I also send the Guid listingId to match the controller signature.
Try adding another formdata parameter:
formData.append("listingId", guidValue);
Provided you have the guid value accessible. You can use this to generate one from the client. Or create one from the server:
var guidValue = '#Guid.NewGuid()';
one approach would be to your controller accept viewmodel (a class) which contains different property you need. and use formdata.append required stuff to post to the server.
On Server side; you will need to use modelbinder so that you will get required stuff populated.
Refernce for modelbinder : https://www.dotnetcurry.com/aspnet-mvc/1261/custom-model-binder-aspnet-mvc
you can get more on google. :)

How to pass MVC view model into AJAX call with AntiForgeryToken

The code below is working for me, but I'm trying to find a way to read all values from the form instead of having to re-create the view model in JavaScript (vm is the name of the parameter of the object).
I tried to serialize the form and pass it in, but maybe my syntax is incorrect.
Any suggestions?
$.ajax({
type: "POST",
dataType: "json",
url: "/post-details-save",
data: addAntiForgeryToken({
vm: ({
Id: $("#PostImageDetails_Id").val(),
Title: $("#PostImageDetails_Title").val(),
Description: $("#PostImageDetails_Description").val(),
CopyrightOwner: $("#PostImageDetails_CopyrightOwner").val(),
CopyrightUrl: $("#PostImageDetails_CopyrightUrl").val(),
SourceName: $("#PostImageDetails_SourceName").val(),
SourceUrl: $("#PostImageDetails_SourceUrl").val(),
SourceLicenseType: $("#PostImageDetails_SourceLicenseType").val()
})
}),
success: postDetailsSaveSuccess,
error: postDetailsSaveError
});
Confirm Form Setup
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { #id = "formID" }))
I have done similar stuff with submitting forms in partial views.
Basically, you need to confirm that your html form is set up correctly:
The AntiForgeryToken
#Html.AntiForgeryToken()
Data Fields
Could look something like the following with the name attribute being important.
<input type="hidden" name="ApproveUserID" id="ApproveUserID" value="#Model.ApproveUserID" />
AJAX The Form
If your form is set up correctly like explained above, you will be able to submit the data via AJAX with something similar to the JS below.
var form = $("#formID");
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(), // data to be submitted
success: function (response) {
if (response == "Success") {
//DO SUCCESS STUFF
} else
{
//DO FAILURE STUFF
}
},
error: function () {
//DO ERROR STUFF
}
});
Pro Tip:
You can always expand the data you send by placing
var formData = form.serialize();
Into a variable and expanding it from there.
Good Luck.

Categories