Ajax Request return : data Udefined After Success - c#

I am trying to do some Get_Data from dataBase Using asynchronous ajax request and WebMethod
Everything works fine , but when i want the returned value from my web method value , i got undefined value
I Know That this question is asked before
I have tried almost all advices to achieve my wanted goal , but unfortunately nothing happened .
Create Instance Outside the function than set it to the return value.
Set The dataType:"Json"
Create an instance inside the function and set it to empty string
var ReturnValue="";
Let Json object stringify my returned value
and many other steps
So please do not mark my question as duplicated value
Here is my code below :
//Javascript and Jquery Codes
$(document).ready(function() {
$("#PValidateLogin").hide();
});
function killSpaces(element) {
var characters = element.toString();
var resultText = "";
for (var i = 0; i < characters.length; i++) {
if (!(characters[i] == " ")) {
resultText += characters[i];
}
}
return resultText;
}
$("#<%=btnLogin.ClientID%>").click(function() {
var MyWantedhref;
var Result = ValidateMyLogin();
if (typeof Result === "undefined") {
alert("Something wrong with codes");
} else if (Result == "false" || killSpaces(Result).length == 0) {
alert("wrong user ");
} else {
MyWantedhref = "/Frm_Manager/frm_MenuCategory.aspx";
location.replace(MyWantedhref);
}
});
function ValidateMyLogin() {
var ReturValue;
var UserName = $("#<%=txtUserName.ClientID%>").val();
var Password = $("#<%=txtUserPassword.ClientID%>").val();
if (killSpaces(Password).length >= 4 && killSpaces(UserName).length >= 4) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
url: "frm_ValidateLogin.aspx/ValidateLogin",
data: "{'UserName':'" + UserName + "','Password':'" + Password + "'}",
success: function(data) {
ReturValue = data.d;
},
error: function(err) {
ReturValue = err.d;
}
});
}
return ReturValue;
}
And Here are the C# Code
<code>
private static OwnerAccountBO _OwnerAccountBO;
public static OwnerAccountBO OwnerAccountBO { get { return new OwnerAccountBO(); } set { _OwnerAccountBO = value; } }
[WebMethod(EnableSession = true)]
public static string ValidateLogin(string UserName, string Password)
{
string CharResult = "";
object[] UserParameters = { UserName, Password };
int Result = OwnerAccountBO.validateLogin(UserParameters);
if (Result > 0)
{
HttpContext.Current.Session["OwnerAccountID"] = Result;
CharResult += Convert.ToString(Result);
}
else
{
CharResult += "false";
}
return CharResult;
}
</code>
Please Any Help would be thankful .
And of course i want a proper explication for the wrong action or flow that i am doing to have such error

You returned a string value from the method
string CharResult = "";
object[] UserParameters = { UserName, Password };
int Result = OwnerAccountBO.validateLogin(UserParameters);
if (Result > 0)
{
HttpContext.Current.Session["OwnerAccountID"] = Result;
CharResult += Convert.ToString(Result);
}
else
{
CharResult += "false";
}
return CharResult;
so in you ajax it must be received like this
$.ajax({
success: function (data)
{
ReturValue = data; //fixed it with this
}
});
Not
$.ajax({ success: function (data)
{
ReturValue = data.d; //issue here
},
error: function (err)
{
ReturValue = err.d;
}
});

Related

Parameter in my C# controller read as null from the AJAX call

I'm trying to take input from Users through a checkbox and store it in a table in my SQL DB, I've created all the link properly and my post AJAX call works well because I was able to receive information in my DB. The problem is the parameter received in my controller is receiving a null value which is storing a null value in my table, I know that my checkbox is pulling the right information because im printing it before hand but I feel like my AJAX setup may not be stringifying it properly.
$("#submitButton").click(function() {
var results = {};
$questions = $('#optionData');
for (i = 1; i < 6; i++) {
if ($questions.find('#option' + i).prop('checked')) {
results['option' + i] = $questions.find('#option' + i).val();
}
newResult = JSON.stringify(results)
};
console.log(newResult);
$.ajax({
url: "/Home/SaveData",
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: (newResult),
success: function(data) {
if (data == null) {
alert("Something went wrong");
}
},
failure: function(data) {
alert(data.dataText);
},
error: function(data) {
alert(data.dataText);
}
});
});
[HttpPost]
public ActionResult SaveData(string Options)
{
dataInsertion dataInsertion = new dataInsertion
{
// questionID = object.QuestionId,
options = Options,
// },
// companyID = object.companyID
};
try
{
if (ModelState.IsValid)
{
DB.dataInsertions.Add(dataInsertion);
DB.SaveChanges();
// RedirectToAction("Home");
}
}
catch (Exception e)
{
Console.WriteLine("error" + e);
}
return Json(new { sucess = "true" });
}

How to get Base64 from ajax Post?

I was trying to get the base64 post in my codebehind webmethod,
but it seems like everytime I include the base64 I get an error : the server responded with a status of 500 (Internal Server Error) - it keeps on hitting the error function.
The Post works with the other strings when the base64 is not inlcuded int the data that im passing.
function event_create() {
alert("alert test : function works => onclick");
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var eventTitle = $("#eventTitle").val();
var eventDesc = $("#eventDesc").val();
var eventTimeStart = $("#eventTimeStart").val();
var eventTimeEnd = $("#eventTimeEnd").val();
var eventDateStart = $("#eventDateStart").val();
var eventDateEnd = $("#eventDateEnd").val();
var eventType = $("#eventType").val();
var eventPlace = $("#eventPlace").val();
var eventAttendee = document.getElementById("lblSelected").innerText;
var userID = sessionStorage.getItem("userID");
var imageBase64 = getBase64(document.getElementById('test').files[0]);
var data = { 'eventTitle': eventTitle, 'eventDesc': eventDesc, 'eventPlace': eventPlace, 'eventType': eventType, 'eventAttendee': eventAttendee, 'userID': userID, 'imageBase64': imageBase64};
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
url: ".../../../../Operation/insert.aspx/createEvent",
data: JSON.stringify(data),
datatype: "json",
success: function (result) {
if (result.d <= 0) {
//false alert something
alert("FALSE");
}
else if (result.d > 0) {
//true
alert(result.d);
}
else {
alert("sent but no call-back");
}
console.log(result);
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" connection to the server failed ");
console.log("error: " + errorthrown);
}
});
}
Here's the Webmethod that will get the post
[WebMethod(EnableSession = true)]
public static string createEvent(string eventTitle, string eventDesc, string eventPlace, string eventType, string eventAttendee, string userID, string imageBase64)
{
String orgID = (String)HttpContext.Current.Session["orgID"];
string response = orgID;
string path = HttpContext.Current.Server.MapPath("~/Users/Organizer/organizerData/"); // de path
//Check if directory exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = "event1" + ".jpg";// for instance
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(imageBase64);
File.WriteAllBytes(imgPath, imageBytes); //write the file in the directory
return imageBase64;
}

Ajax Response Doesn't work from server side (iis)

I try to save a file (image) on C# MVC and JS with the following function js
function Add() {
var data = new FormData();
var files = $("#txtUploadFile").get(0).files;
var cod = document.getElementById('cod').value;
var mat = document.getElementById('mat').value;
var status = document.getElementById('status').value;
var plant = document.getElementById('plant').value;
if (files.length > 0) {
if (window.FormData !== undefined) {
var data = new FormData();
for (var x = 0; x < files.length; x++) {
data.append("file" + x, files[x]);
data.append("mat", mat);
data.append("status", status);
data.append("plant", plant);
data.append("code", cod);
}
$.ajax({
type: 'POST',
url: '/Pred/Admin/AddPred',
contentType: false,
processData: false,
data: data,
success: function (response) {
if(response.msg == 1)
{
refreshTable(response.data);
}
alert('Predio agregado.');
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
}
});
}
}
}
and on the codebehind I used it
public ActionResult AddPred()
{
int isInsert=0;
string route = ConfigurationManager.AppSettings["MAPS_ROUTE"];
string[] status, plants, mats, codes;
int stat;
try
{
var requeststatus = Request.Params;
status = requeststatus.GetValues("status");
plants = requeststatus.GetValues("plant");
codes = requeststatus.GetValues("cod");
mats = requeststatus.GetValues("mat");
if (status[0] == "On")
stat= 1;
else
stat= 0;
string plant = plants[0];
string mat = mats[0];
string code = codes[0];
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var fileName = fileContent.FileName;
var path = Path.Combine(Server.MapPath(route), fileName);
path = Server.MapPath(route) + fileName;
var sqlpath = "." + route + "/" + fileName;
fileContent.SaveAs(path);
isInsert = ma.InsertPred(code, mat, stat, plant, sqlpath);
}
}
merge.preds = ma.GetPreds();
return Json(new { success = true, data = merge.preds, msg = isInsert }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("add failed");
}
}
But the server response ever is
POST myserver/Preds/Admin/AddPred 500 (Internal Server Error)
and I used console.log but I can't to get the error information, When used this code on local side, it's runs Okey, save the image and return model for refresh the front, but when put the aplication on the server, only return error, others funtions works (modal show, return model with json) but doesn't work save a image, I set permissions (write, load, modify) on the server folder,
someone give a idea for solves this problem, I don't know whats wrong
Try like this :
function getCities(id) {
$.ajax({
type: "POST",
url: "#Url.Action("Index", "Default")",
data: '{id: id }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert(response.responseData);
window.location = '/Default/YourView';//
},
error: function (response) {
alert("error!"); //
}
});
}
//In your controller
public JsonResult Index(string id)
{
merge.country= mp.Country();
merge.city= mp.City(id);
return Json("you can return an object or a string, what you want");
}

Passing response from ajax call to view in C#

I am using ajax to call an action in the controller. The code is like this
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (selectedKitchen != '') {
console.log("selected item:" + $('#kitchen').val());
$.ajax({
type: "GET",
url: "/Home/GiveInsitutionsWithoutResponsibility",
data: "id=" + selectedKitchen,
dataType:'json',
success: function (result) {
result = JSON.parse(result);
console.log(result.length);
},
error: function (error) {
console.log("There was an error posting the data to the server: ");
console.log(error.responseText);
}
});
}
});
Now what I want is to use the result coming from the server to populate a drop down on the client side. How should I do it? Is there a way for it or my approach here is wrong?
My result object is like this
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
The controller function is like this
public ActionResult GiveInsitutionsWithoutResponsibility()
{
var kitchenId = Request["id"].ToString();
Kitchen k = Kitchen.Get(kitchenId);
IEnumerable <Institution> ins = k.GetInstitutions();
IEnumerable<Institution> allIns = Institution.GetAll();
List<Institution> result = new List<Institution>();
bool contain = true;
int index = 0;
if (ins.Count() > 0)
{
for (int i = 0; i < allIns.Count(); i++, contain = true)
{
for (int j = 0; j < ins.Count(); j++)
{
if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
{
contain = true;
break;
}
else
{
index = j;
contain = false;
}
}
if (!contain)
{
result.Add(allIns.ElementAt(index));
}
}
}
else
{
for (int i = 0; i < allIns.Count(); i++)
{
result.Add(allIns.ElementAt(index));
}
}
string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
return Json(response, JsonRequestBehavior.AllowGet);
}
First your action method can be simplified to
public ActionResult GiveInsitutionsWithoutResponsibility(int ID)
{
Kitchen k = Kitchen.Get(ID);
var data = Institution.GetAll().Except(k.GetInstitutions(), new InstitutionComparer()).Select(i => new
{
ID = i.ID,
Name = r.Name
});
return Json(data, JsonRequestBehavior.AllowGet);
}
Note the Kitchen.ID is passed in the method parameter. The Linq query is used to select all Institution's then exclude any Institution's that already exist in the Kitchen, then creates a collections of anonymous object so unnecessary data is not sent to the client. The Json() method returns the data in the correct JSON format (calling JavaScriptSerializer().Serialize() is not required).
In order for .Except() to work with complex objects, you need a comparer
public class InstitutionComparer : IEqualityComparer<Institution>
{
public bool Equals(Institution x, Institution y)
{
if (Object.ReferenceEquals(x, y))
{
return true;
}
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
{
return false;
}
return x.ID == y.ID;
}
public int GetHashCode(Institution institution)
{
if (Object.ReferenceEquals(institution, null))
{
return 0;
}
return institution.ID.GetHashCode();
}
}
Next change the ajax method to
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (!selectedKitchen) {
return;
}
$.ajax({
type: "GET",
url: '#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', // don't hard code urls
data: { id: selectedKitchen }, // pass selectedKitchen to the id parameter
dataType:'json',
success: function (result) {
var select = $('YourDropDownSelector').empty().append($('<option></option>').val('').text('--Please select--'));
$.each(result, function(index, item) {
select.append($('<option></option>').val(item.ID).text(item.Name));
});
},
error: function (error) {
}
});
});
or you could use the short cut
$.getJSON('#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', { id: selectedKitchen }, function(result) {
$.each(result, .... // as above
});
Depending on the object from your controller, you could loop through your results data and .append this to your drop down list.
success: function (result) {
$.each(result, function(index, manager) {
$('select#yourId').append(
'<option value="' + result.Id + '">'
+ result.Name +
'</option>');
});
}
Your approach is fine, you will have to format the result to be added to combo box. For example, support on a page I have country and states combo box. Based on selected country, I need to populate state, so I will write following code:
$("#billingContactCountry").change(function (e) {
e.preventDefault();
var countryId = $("#billingContactCountry").val();
getStatesByCountry(countryId, "", "#billingContactState", "#billingContactZip");
});
function getStatesByCountry(countryId, stateId, stateCombobox, zipTextBox) {
$.ajax({
url: "#Url.Action("GetStatesByCountry", "Admin")",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function (xhr, status) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$(stateCombobox).html(items);
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
},
success: function (data) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
if (stateId != "") {
$('#billingContactState').val(stateId);
}
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
}
});
}
So basically interesting code is,
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
We are operating on each element returned from server to create option item for combo box.
As an aside, you should use #Url.Action as shown in example above.

JQuery.Ajax and MVC4

I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}

Categories

Resources