How to add headers at runtime in fine uploader - javascript

I am using fine uploader for uploading file on server, For this I need to make 2 web api calls.
On button click, First web api saving value and returning result in integer, and I need to pass that integer result in header for each file while uploading.
But I am not able to pass values in headers,
code,
uploader = new qq.FineUploader({
element: $('#manual-fine-uploader1')[0],
request: {
endpoint: Url.AddEvaluationFiles,
},
autoUpload: false,
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
},
debug: true,
callbacks: {
onSubmit: function (id, fileName) {
},
onStatusChange: function (id, oldStatus, newStatus) {
if (newStatus == "uploading") {
alert("Add header");
}
},
onUpload: function (id, name) {
alert("Onupload");
this.append("RequestId", $("#ReqId").val());
}
}
});
I am calling upload function in success block of first request,
$.ajax({
type: "POST",
url: Url.Details,
data: fileData,
async: false,
success: function (result) {
if (result == 0) {
toastr.error("Please pass user id");
} else {
$("#ReqId").val(result);
alert($("#ReqId").val());
uploader.uploadStoredFiles();
}
},
error: function (err) {
toastr.error("Not able to upload art details");
}
});
Here I want to pass RequestId header in onUpload event, but it's not working, What changes I need to make to make it happen.

The request option has a customHeaders property, that allows you to set any custom header.
Your constructor call should look something like
artistmanualuploader = new qq.FineUploader({
...
request: {
endpoint: "FoaUrl.AddEvaluationFiles",
customHeaders: {
"EvaluationRequestId": $("#CurrentEvaluationReqId").val()
}
},
...
});

Related

How can I use a PUT request, using Ajax, to change the value of a variable?

I'm using ASP.NET Core, and, on my Index View, I want to change the value of a variable when I click a button. I have a class that has a proprety named "Estado". On my Index I have a map with different markers, and each marker has an infowindow that have three buttons ("Aceitar", "Recusar", "Concluido"). When I click in one of those buttons I want to change the value of the variable "Estado" to another value depending on the button that is clicked. Here is the function on my index:
function atualizaBD(id, novoEstado) {
$.ajax
({
url: '/api/IgnicoesAPI',
type: 'PUT',
datatyoe: JSON.stringify({
id: +id,
novoEstado: +novoEstado
}),
success: function (result) {
//What do I do here
})
},
error: function () {
alert("ocorreu um erro!")
},
});
}
I'm not sure how to use the PUT request. Here is the PUT request on my controller:
//// PUT: api/IgnicoesAPI/5
[HttpPut("{id}")]
public async Task<IActionResult> PutIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignicoes)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ignicoes.Id)
{
return BadRequest();
}
_context.Entry(ignicoes).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!IgnicoesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
You have to fix few things. Datatype is type of response you expect to receive. ContentType is for type of data you send. If you want to pass data to your request which requires id from route then you have to pass it to url. If you want to pass data like objects then you need to pass it to data option.
More information in documentation.
Code after fixes:
function atualizaBD(id, novoEstado) {
$.ajax
({
url: `/api/IgnicoesAPI/${id}`,
type: 'PUT',
data: JSON.stringify({
id: +id,
novoEstado: +novoEstado
}),
success: function (result) {
//What do I do here
})
},
error: function () {
alert("ocorreu um erro!")
},
});
}

Problem: pass some parameters in ajax call (post)

I have 2 functions: one to add and another to delete. I would like to reuse the same ajax call to send the parameters that are added or deleted. How can I optimize my function?
Here is my code at the moment
jQuery(document).ready(function () {
function ajaxCall(action, callback) {
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
},
success: function (response) {
if (response.error == true) {
alert(response.errors.join('\n'));
}
else if (response.status == "DONE") {
callback(false);
}
},
error: function (xhr) {
console.log("Error: ", JSON.stringify(xhr));
callback(true);
}
});
}
jQuery('#ajax_add').click(function (event) {
event.stopPropagation();
var id = jQuery('#id').val();
var price = jQuery('#price').val();
//I want to send two variables: id, price
ajaxCall("addData", function (error) {
if (error) {
alert("Error!.");
}
else {
alert("It's OK!");
}
});
});
});
The function to delete is similar to "addData" function, it also calls "ajaxCall" and will send parameters to remove.
I'm blocked and I do not know how to solve it, I hope you can give me some help, thanks
You could add a new argument to the ajaxCall function and send the parameters as an object them merge them with the data you've in the function like :
function ajaxCall(action, params, callback) {
Then in the ajax call :
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: $.extend(params, {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
}),
...
The call inside the event will be like :
ajaxCall("addData", {id: id, price: price}, function (error) {

Unable to select the newly added selectize components post an ajax call

Unable to select the newly added selectize components post an ajax call
I have pre populated the options with the currently selected options, and trying to retrieve more option with an ajax call from the server.
My server returns data like this but I am not sure what to do with this data
[{"id":303,"name":"Short Sleeve Opening"}]
I've tried using the addOption and refreshOptions methods, but they doesn't seem to work.
Below is the piece of code which is invoking the selectize component.
$(function () {
$select_options = $('select').selectize({
plugins: ['restore_on_backspace', 'remove_button', 'drag_drop'],
delimiter: ',',
persist: false,
create: function (input) { // I am not sure if this is of any use, as I never found the control to enter in this part of code during debugging.
return {
value: input,
text: input
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
dataType: 'json',
url: '/measurement_tags/autocomplete_key?q=' + encodeURIComponent(query),
error: function () {
callback(); //Not sure what the callback should be, documenation is not self explanatory
},
success: function (res) {
//Added this callback to add the new options to the list, it is adding the new options to the list but I can't select them at all
//Moreover, second time I try to use autocomplete it doesn't work. The control doesn't reach the load method, and no error observed in console
for (index in res) {
$('.selectize-dropdown-content').append('<div class="option" data-selectable="" data-value="' + res[index].id + ' ">' + res[index].name + '</div>');
}
}
});
}
});
});
What is the exact way to add the new options to the list permanently?
Finally achieved this after wasting whole day:
$(function () {
$select_options = $('select').selectize({
plugins: ['restore_on_backspace', 'remove_button', 'drag_drop'],
delimiter: ',',
persist: false,
options: [],
load: function (query) {
$.ajax({
dataType: 'json',
url: '/measurement_tags/autocomplete_key?q=' + encodeURIComponent(query),
success: function (res) {
updateOptions(res);
}
});
}
});
var updateOptions = function (newOptions) {
var selectize = $select_options[0].selectize;
for (index in newOptions) {
selectize.addOption({
value: newOptions[index].id,
text: newOptions[index].name,
});
}
selectize.refreshOptions();
}
});

.NET MVC JSON Post Call response does not hit complete or success

I am new to .NET MVC so please bear with me.
I wrote a function that gets triggered when there is a blur action on the textarea control:
function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}
jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});
This works fine and will hit the controller:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
I get the intended results if the URL is valid; it will return a partialview to the .done() function and I just display it in code. However, if the URL is not valid i want it to hit either complete, success, or done (I have been playing around to see which it will hit but no luck!) and do something with the returned data. I had it at some point trigger either complete or success but the data was 'undefined'. Can someone help me out on this?
Thanks!
In both cases your controller action is returning 200 status code, so it's gonna hit your success callback:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});
But of course a much better and semantically correct approach is to set the proper status code when errors occur instead of just returning some 200 status code:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
and then in your AJAX call you would handle those cases appropriately:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);
// and display the error message to the user
alert(data.message);
}
}
});
Also don't forget that you have some standard way of returning your error messages you could subscribe to a global .ajaxError() handler in jQuery instead of placing this code in all your AJAX requests.

Web API: Upload files via Ajax post

I have this following snippet for uploading files via Ajax post (using Knockout js library)
ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
$(element).after('<div class="progress"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
property = ko.utils.unwrapObservable(options.property),
url = ko.utils.unwrapObservable(options.url);
if (property && url) {
$(element).change(function () {
if (element.files.length) {
var $this = $(this),
fileName = $this.val();
alert(fileName);
// this uses jquery.form.js plugin
$(element.form).ajaxSubmit({
url: url, //WEB API URL
type: "POST",
dataType: "text", //I want to upload .doc / excell files
headers: { "Content-Disposition": "attachment; filename=" + fileName },
beforeSubmit: function () {
$(".progress").show();
$(".progressError").hide();
$(".bar").width("0%")
$(".percent").html("0%");
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + "%";
$(".bar").width(percentVal)
$(".percent").html(percentVal);
},
success: function (data) {
$(".progress").hide();
$(".progressError").hide();
// set viewModel property to filename
bindingContext.$data[property](data);
},
error: function (jqXHR, textStatus, errorThrown) {
$(".progress").hide();
$("div.progressError").html(jqXHR.responseText);
}
});
}
});
}
}
}
now my problem is creating the WEB API for this.
$(element.form).ajaxSubmit({
url: url, //WEB API URL
type: "POST",
dataType: "text", //I want to upload .doc / excell files
headers: { "Content-Disposition": "attachment; filename=" + fileName },
I want to upload Word/Excell document. Can someone give me an idea how to get this done in ASP.NET WEB API?
UPDATE:
I finally made an WEB API for this
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
//return new HttpResponseMessage()
//{
// Content = new StringContent("File uploaded.")
//};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
It works ok (data successfully uploaded) but the problem is, it seems like in doesnt hit this section after the data is succesfully uploaded.
success: function (data) {
$(".progress").hide();
$(".progressError").hide();
// set viewModel property to filename
bindingContext.$data[property](data);
},
I have to inform the client of what the status of the upload.

Categories

Resources