How to post webform with file to webmethod using Jquery/Ajax? - javascript

Is this even possible? I have a webform with certain textboxes etc and a file upload element. I am trying to send the data to webmethod using .ajax() method.
It seems to me that it is not possible to send file content to the webmethod in this manner. I am not even able to hit the webmethod.
script type="text/javascript">
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
data: "{'file' : " + btoa(document.getElementById("myFile").value) + ",'biddername':" + document.getElementById("txtsuppliername").value + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
</script>
HTML:
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
Code behind :
[WebMethod]
public static string RegisterSupplier(string file, string biddername)
{
// break point not hit
return "a";
}
I have been trying to find solution to this for hours now. Nobody seems to be able help me out on this. Is this even possible using this approch. If not how do I do it? Somebody suggested that I should try to submit entire form instead of passing individual values.

This can be done without any library, by using the JavaScript FileReader API. With it, modern browsers can read the content of the file using JavaScript once it has been selected by the user, and then you could proceed as you were doing (encoding it as a string, and sending it over to the server).
The code would be like this (using the one above as a reference):
// NEW CODE
// set up the FileReader and the variable that will hold the file's content
var reader = new FileReader();
var fileContent = "";
// when the file is passed to the FileReader, store its content in a variable
reader.onload = function(e) {
fileContent = reader.result;
// for testing purposes, show content of the file on console
console.log("The file content is: " + fileContent);
}
// Read the content of the file each time that the user selects one
document.getElementById("myFile").addEventListener("change", function(e) {
var selectedFile = document.getElementById('myFile').files[0];
reader.readAsText(selectedFile);
})
// END NEW CODE
var btn;
var span;
$(document).ready(function (e) {
$('#btnsave').on('click', function (event) {
Submit();
event.preventDefault();
});
})
function Submit() {
$.ajax({
type: "POST",
url: "SupplierMst.aspx/RegisterSupplier",
// changed this line too!
data: {
'file': btoa(fileContent),
'biddername': document.getElementById("txtsuppliername").value
},
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtsuppliername" type="text" /><br />
<input type="file" id="myFile">
You can run the code above, select a file (use a plain text file for testing so it's readable), and check the console to see its content. Then the rest of the code would be the same (I made a slight change to fix the parameters in the AJAX call).
Notice that sending the file like this has limits: if you use the GET method, you'll have a shorter parameter size limit, and with POST it will depend on the server settings... but I guess that you had those limits even for a file.

First of all go to App_Start>>RouteConfig.cs>>settings.AutoRedirectMode = RedirectMode.Off; and then Just Replace your function by my code it will definitely work for you,
Good Luck..
function Submit() {
$.ajax({
type: "POST",
url: "UploadImage.aspx/RegisterSupplier",
data: "{'file' : " + JSON.stringify(document.getElementById("myFile").value) + ",'biddername':" + JSON.stringify(document.getElementById("txtsuppliername").value) + "}",
async: true,
contentType: "application/json; charset=utf-8",
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});

Related

Failed to load resource: the server responded with a status of 500 using Ajax

I know this question has been asked previously, but I cannot find out what is the exact problem with my code.
function viewcalldetails(obj) {
alert("clicked");
var id = $(obj).attr("id");
$(".style-table-tab input[type='text']").val('');
setTimeout(function () {
$('.preloader-circle').show();// or fade, css display however you'd like.
}, 1000);
$.ajax({
type: 'POST',
url: pageUrl+"/LoadCallDetails",
data: '{LeadID: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: OnValuecall,
failure: function (response) {
alert(response.d);
}
});
}
function OnValuecall(response) {
$(".preloader-circle").hide();
$("#ctl00_ContentPlaceHolder1_lbrfullname").text(response.d.FirstName);
$("#ctl00_ContentPlaceHolder1_lbrphonenumber").text(response.d.MobileNo);
$("#ctl00_ContentPlaceHolder1_lbraddress").text(response.d.Address1);
$("#ctl00_ContentPlaceHolder1_lbrorganization").text(response.d.OrganizationName);
$("#ctl00_ContentPlaceHolder1_lblremail").text(response.d.PrimaryEmail);
}
Web Method:
public static UserAjax3 LoadCallDetails(string LeadID)
{
//System.Threading.Thread.Sleep(3000);
UserAjax3 oUserAjax = new UserAjax3();
//BD_CommonEmail[] ocall = BD_CommonEmail.GetEmailAll(Convert.ToInt32(LeadID)).ToArray();
BD_Leads[] ocall = BD_Leads.getCallDetails(Convert.ToInt32(LeadID)).ToArray();
if (ocall.Length == 1)
{
// oUserAjax.LeadID = oLeads.LeadID.ToString();
oUserAjax.LeadID = ocall[0].LeadID.ToString();
oUserAjax.FirstName = ocall[0].FirstName;
oUserAjax.MobileNo = ocall[0].MobileNo;
oUserAjax.OrganizationName = ocall[0].OrganizationName;
oUserAjax.Address1 = ocall[0].Address1;
oUserAjax.PrimaryEmail = ocall[0].PrimaryEmail;
}
return oUserAjax;
There are many things in question:
Where does "pageUrl" comes from?
You're awaiting a JSON result, but your method seems to return a normal object. Where do you convert to JSON?
Did you try running with a debugger in single-step mode trhough your web method?
Why is your web method static?

AJAX not sending data

I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>
You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']
Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);
Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}
change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }

jQuery autocomplete using data pulled from SharePoint list using ajax REST

I need to add autocomplete to an input textbox. The data needs to be fetched from SharePoint using AJAX / REST.
This what I've done so far:
JS
var myData = [];
var requestHeaders = {
"accept": "application/json;odata=verbose"
}
$.ajax({
url: "https://my-URL/sites/RMA-GFPLC/_api/web/lists/GetByTitle('AD_DB')/items? $select=Title,Regional_x0020_Office,Commodity,Commodity_x0020_Year,StateLookUp/Title&$expand=StateLookUp",
type: 'GET',
dataType: 'json',
async: false,
headers: requestHeaders,
success: function (data) {
$.each(data.d.results, function (i, result) {
myData.push(result.Title);
});
myDataSource(myData);
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
function myDataSource(myData){
$('#myAutoCompleteSearch').autocomplete({
source: myData,
minLength: 3
});
}
So far my code is not working, and I'm getting "Uncaught TypeError: Cannot read property 'label' of null " error in my console. I;m wonder what am I doing wrong here? Thanks!
This error occurs when a source for Autocomplete function contains an element(s) with a null value.
Solution
Add the condition for checking if value is not null:
$.each(data.d.results, function (i, result) {
if(result.Title) {
myData.push(result.Title);
}
});
Jast insert your code in
$(document).ready(function () {
//your code here
}

ASP MVC basic AJAX Json request returns null

I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.

How to Use $.ajax? when I use Its not hitting my controller Action

Can any body help me out.
I have this code
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function GOTO() {
var datastring = "id=2";
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: datastring,
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
//alert("an error occurred: " + error);
alert("Error saving data. Please contact support.");
}
});
}
function Complete(result) {
if (result == "success") {
alert("Success");
}
else {
alert("Failed");
}
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
and My Controller Code is this
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
return Json(new { foo = "bar", baz = "Blech" });
}
But it never hits my controller at all, is that Something I am doing wrong in my View?
thanks
Try passing the data like this:
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: { datastring: 'foo bar' },
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
alert("Error saving data. Please contact support.");
}
});
function Complete(result) {
if (result == "success") {
altert("Success");
// ^ beware!
You have a syntax error in your code.
Moreover, you don't need to specify the JavaScript: protocol in the onclick attribute, you're merely defining a label at that place. Even better, don't assign event listeners in HTML attributes at all, but use unobtrusive JavaScript, including a fallback for the rare case when JavaScript is unavailable.
Update: if you get the "$.ajax is undefined" error, you probably didn't include jQuery in your page. Add
<script type="text/javascript" src="path/to/jquery-X.X.X.js"></script>
To your page above the script element that uses $.ajax (or any other jQuery function).
it could be down to what data you are passing in. Your method expects a parameter called datastring but you are passing in 'id=2'.

Categories