Passing more then 1 value to webmethod using FormData via Ajax - ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.

This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};

You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

Related

ajax call returning promis and resolve it by the calling function to its value

By now i read somewhere around 6 pages containing documentations and stackoverflow answers but I don't get the method.
My function is by now after reading all the stuff built like this:
async function getFToken(postId){
const response = await $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{
action:'get_f_token',
postId: postId,
},
success:function(response) {
}
});
return response;
}
and in my other function is like this:
function getFeedback(postId){
$(".show_company").hide();
$(".show_feedback").show();
$.ajax({
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data:{
action:'get_feedback',
postId: postId,
},
success:function(response) {
var postTitle = '';
for (i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
var test = getFToken(387);
alert(Promise.resolve(test));
};
$("#result").html(postTitle);
}
});
}
is there any chance, that this is a bigger issue because i call a async in another Ajax call trying to retrieve the value? I'm trying to get the string from the first ajax call and hand it to the second function in the ajax call to attach it to the posts i retrieve from WordPress
The alert is giving me [object Promise] but how do i get the value passed from the php script?
php-scrtipt:
//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
if(isset($_POST['postId'])){
$postId = $_POST['postId'];
}
$fToken = get_post_meta($postId, 'fToken', true);
echo $fToken;
wp_die();
}
Don't use success callbacks when you can use async/await:
async function getFToken(postId) {
return $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'get_f_token',
postId: postId,
}
});
}
async function getFeedback(postId) {
$(".show_company").hide();
$(".show_feedback").show();
const response = await $.ajax({
// ^^^^^
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data: {
action: 'get_feedback',
postId: postId,
}
});
let postTitle = '';
for (const i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
const test = await getFToken(387);
// ^^^^^
alert(test); // no Promise.resolve, you don't want to alert a promise
}
$("#result").html(postTitle);
}

AJAX dont call WebMethod but returns HTML

I had read a lot of questions here on Stackoverflow about AJAX calls to WebMethods, and I tried a lot of things and nothing works.
My AJAX method doesnt call the WebMethod on server side but returns success and the entire HTML of the page.
This is the AJAX:
$("[id*=butLogin]").click(function () {
var obj = {};
obj.pEmail = "EMAIL"; //$.trim($("[id*=txtName]").val());
obj.pPassword = "PASSWORD"; //$.trim($("[id*=txtAge]").val());
$.ajax({
type: "POST",
url: "login.aspx/logOn",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
failure: function (msg) {
alert(msg.d);
},
error: function (msg, merr, derr) {
alert(msg.d);
}
});
return false;
});
And this is the WebMethod:
[System.Web.Services.WebMethod]
public static string logOn(string pEmail, string pPassword)
{
return "logged";
}
I believe is a simples mistake.
Thanks for your help.

Passing HttpPostedFileBase and other variables in ajax POST to mvc controller

I have been trying to post a file and some variables to my controller action using ajax, but I am getting null parameters for both of my variables.
Below is my ajax call
$("#btn-upload").on("click", function () {
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
var Data = formData+"&rows="+rows;
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: Data,
cache: false,
contentType: false,
processData: false,
success: function (result) {
if (result=='True') {
$(".alert-success").show();
}
else {
$(".alert-danger").show();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$(".alert-danger").show();
},
});
});
and my controller action is
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile, int? rows)
{
var excelUtility = new ExcelUtilityService();
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}
If I pass only the file parameter in my ajax call it works fine but when I try to do it with multiple parameters e.g 'rows' in my code, both of the parameters become null in my controller action while post.
In order to add values to a FormData object, you need to use .append().
Modify your script to
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....
Using the script modification from Stephen:
$("#btn-upload").on("click", function ()
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
formData.append('rows', rows); // modify
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: formData, // modify
cache: false,
contentType: false,
processData: false,
success: function (result) {
....
If linking to parameters directly doesn't work with the formData.append() method above, I would recommend accessing them via:
Request["key-used-to-append"]
Example with your controller (rows variable assignment):
[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile)
{
var excelUtility = new ExcelUtilityService();
var rows = Request["rows"];
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}

How to implement Antiforgerytokens with partial views in mvc4?

I am trying to implement antiforgerytoken in my project. I am able to implement it when making ajax call below.
function docDelete(id) {
var _upload_id = $("#docId").val();
var _comments = $("#name").val();
var forgeryId = $("#forgeryToken").val();
$("#dialog-form").dialog("open");
$.ajax({
type: 'GET',
cache: false,
url: '/DeleteDocument/Delete',
dataType: 'json',
headers: {
'VerificationToken': forgeryId
},
data: { _upload_id: _upload_id, _comments: _comments },
success: function (data) {
$('#dialog-form').dialog('close');
$('#name').val('');
$('#dvSuccess').val(data);
Getgridata(data);
}
});
}
above code works fine. But in some cases i am making ajax request as below.
var forgeryId = $("#forgeryToken").val();
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
headers: {
'VerificationToken': forgeryId
},
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}
Above code does not send any token to below method.
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = string.Empty;
string formToken = string.Empty;
string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
if (!string.IsNullOrEmpty(tokenValue))
{
string[] tokens = tokenValue.Split(',');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken); // this validates the request token.
}
}
In layout.cshtml i have implmented code to get token.
<script>
#functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + "," + formToken;
}
}
</script>
<input type="hidden" id="forgeryToken" value="#GetAntiForgeryToken()" />
The variable tokenValue catching null each time. So what i understood is through headers i am not able to send token value. I tried many alternatives. So anyone suggest me how can i overcome this issue? Thank you in advance.
I tried as below still i am getting null value.
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
alert(token);
var forgeryId = JSON.stringify($("#forgeryToken").val());
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
cache: false,
headers: headers,
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}

Send JSON string to a C# method

In my ASP.NET page I have the following method:
public static void UpdatePage(string accessCode, string newURL)
{
HttpContext.Current.Cache[accessCode] = newURL;
}
It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var dataToSend = [ {accessCode: code, newURL: url} ];
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {"items":dataToSend},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However this doesn't seem to work. Could anybody help me figure out where the bug is?
UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response.
You could look at the HTTP return code and check that it was 200 OK or you could modify the web method:
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result
}
Edit:
It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly.
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}

Resources