Click here to Skip to main content
14,660,962 members
Rate this:
Please Sign up or sign in to vote.
Hi all,

I am planning to get Customer Id from DB by passing customer name to the controller using Ajax. And assign to CustomerId to save them in DB with another Ajax post.
but it alerts error. I could not debug. please help me to solve it.


//Save if valid
           if (isAllValid) {

               $(function () {
                       $.ajax({
                           url: '/Sale/getCustomerId',
                           type: "POST",
                           data: { input: $("[id*='Customer'] :selected").text() },
                           contentType: "application/json",
                           success: function (result) {
                               alert(result);
                           },
                           error: function () {
                               alert("error");
                           }
                       });
                       return false;
               });

               cusId = result;

               var data = {
                   AccntInvoiceNo: $('#AccountInvNo').val(),
                   SaleDate: $('#SaleDate').val(),
                   SubTotal: $('#SubTotal').val(),
                   Discount: $('#Discount').val(),
                   NetAmount: $('#NetTotal').val(),
                   CustomerId: result,
                   UserId: 1,
                   SaleType: $("[id*='Categories'] :selected").text(),
                   SaleDescs: orderItems
               }


               $(this).val('Please wait...');

               $.ajax({
                   url: '/Sale/SaveOrder',
                   type: "POST",
                   data: JSON.stringify(data),
                   dataType: "JSON",
                   contentType: "application/json",
                   success: function (d) {
                       //check is successfully save to database
                       if (d.status == true) {
                           //will send status from server side
                           alert('Successfully done.');
                           //clear form
                           orderItems = [];
                           $('#AccountInvNo').val('');
                           $('#saleDate').val('');
                           $('#orderItems').empty();
                           $('#SubTotal').val('');
                           $('#Discount').val('');
                           $('#NetTotal').val('');
                       }
                       else {
                           alert('Failed');
                       }
                       $('#submit').val('Save');
                   },
                   error: function (exception) {
                       alert('Exeption:' + exception);
                       $('#submit').val('Save');
                   }
               });
           }

       });


Sale Controller class
public JsonResult getCustomerId(string CusName)
        {
            IQueryable CusID = from p in db.Persons where ((p.FName+p.LName) == CusName) select p.Id;
            return Json(CusID, JsonRequestBehavior.AllowGet );
        }


Route config file (people is the name of table)
routes.MapRoute(
                "getCustomerId",
                "Sale/People/{name}",
                new { controller = "Sale", action = "getCustomerId" }
            );


What I have tried:

I am planning to get Customer Id from DB by passing customer name to the controller using Ajax. And assign to CustomerId to save them in DB with another Ajax post.
but it alerts error. I could not debug. please help me to solve it.
Posted
Updated 15-Sep-16 21:30pm
Comments
InbarBarkai 5-Sep-16 6:21am
   
What is the error?
Member 11883599 5-Sep-16 6:32am
   
/Sale/getCustomerId from this, I don't get value, it throws error and shows as result is undefined
InbarBarkai 5-Sep-16 8:43am
   
You're lacking basic understanding of ajax calls.
Off course the result will be undefined. You don't get it until the call is finished. This is done asynchronously.
Karthik_Mahalingam 5-Sep-16 6:38am
   
does it hit the controller action?
Member 11883599 5-Sep-16 8:10am
   
I have checked putting a break point to controller, but it did not hit, any guess ?? Coz I am new to this Ajax
Karthik_Mahalingam 5-Sep-16 8:11am
   
paste the url in address bar and check it hits the action
Member 11883599 6-Sep-16 6:12am
   
yes, I tried this way,
http://localhost:55664/Sale/getCustomerId?CusName=Kasun%20Sandaruwan
once I remove [HttpPost] tag, It hits controller and value of CusName passes successfully, but for CusId I am getting a long query. not the ID. But I already checked quering samething on SQLSever, it gives correct value.
Karthik_Mahalingam 6-Sep-16 6:14am
   
then remove the httpost
Karthik_Mahalingam 5-Sep-16 8:18am
   
run this text in chrome console window and check the value
$("[id*='Customer'] :selected").text()
Member 11883599 6-Sep-16 6:03am
   
I tried your way also, it gives this error
VM94:187 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[id*='Customer'] :selected' is not a valid selector.(…)CommandLineAPIImpl.$ @ VM94:187(anonymous function) @ VM121:1
Karthik_Mahalingam 6-Sep-16 6:05am
   
means the selector is not valid
check http://www.w3schools.com/jquery/jquery_ref_selectors.asp
Member 11883599 10-Sep-16 5:26am
   
I modified code again,
everything looks fine, but did not get value from controller to ajax call, give as undefined. I just tried returning number from controller to ajax call, still gets data value is undefined. please try to solve it,

Controller......

[HttpPost]
public JsonResult getCustomerId(string CusName)
{

var result = db.People.Where(x => x.FName == CusName).Select(x => x.Id).Distinct().ToList().FirstOrDefault();
return Json (result);
}

Ajax function.....

function getCusId(name) {
$.ajax({
url: '/Sale/getCustomerId',
datatype: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ CusName: name }),
async: true,
processData: false,
cache: false,

success : function (Data) {
return Data;
},
error : function (xhr) {
// alert("error");
return null;
},
error: function (exception) {
alert('Exeption:' + exception);
}
})
}

catching return value....

var cusid = getCusId(name);

Rate this:
Please Sign up or sign in to vote.

Solution 1

So a few things to do/check.

Based on your comments and your code, I believe your issue as to why its not even hitting the controller is 2 things:

1) you are missing the [HttpPost] verb above your controller action.

[HttpPost]
public JsonResult getCustomerId(string CusName)
        {
            IQueryable CusID = from p in db.Persons where ((p.FName+p.LName) == CusName) select p.Id;
            return Json(CusID, JsonRequestBehavior.AllowGet );
        }


2) Your route and action use different variable names than your ajax call

Current calls data line:

data: { input: $("[id*='Customer'] :selected").text() },


Your action in your controller uses CusName for the parameter, yet in your route you specify it as name. Your issue here would be that CusName would be blank as the binding is looking to bind CusName parameter in your action to a form item being posted with a name of CusName, yet in your case you are passing it in as input.

You need to choose a parameter name and stick with it. If that is name, CusName, or input.

So in your ajax call's data line change it to this

data: { CusName: $("[id*='Customer'] :selected").text() },


Change your route to this as well. One item to note here, even though you aren't utilizing the route in your ajax call, if you were to start using this route in your ajax, i believe it won't work as what you currently have got due to the third param name being used, so you need to change your route to this:

routes.MapRoute(
                "getCustomerId",
                "Sale/People/{CusName}",
                new { controller = "Sale", action = "getCustomerId" }
            );
   
v2
Comments
Member 11883599 6-Sep-16 6:21am
   
I tried the same, but getting below errors;
MasterIndex:353 Uncaught ReferenceError: result is not defined(anonymous function) @ MasterIndex:353dispatch @ jquery-2.2.3.js:4737elemData.handle @ jquery-2.2.3.js:4549
jquery-2.2.3.js:9203 POST http://localhost:55664/Sale/getCustomerId 500 (Internal Server Error)
David_Wimbley 6-Sep-16 10:08am
   
Its because your ajax call is running async. Your trying to access the variable result before it has a value.

Add async: false to your ajax call.


$.ajax({
url: '/Sale/getCustomerId',
type: "POST",
async: false
Member 11883599 10-Sep-16 5:26am
   
I modified code again,
everything looks fine, but did not get value from controller to ajax call, give as undefined. I just tried returning number from controller to ajax call, still gets data value is undefined. please try to solve it,

Controller......

[HttpPost]
public JsonResult getCustomerId(string CusName)
{

var result = db.People.Where(x => x.FName == CusName).Select(x => x.Id).Distinct().ToList().FirstOrDefault();
return Json (result);
}

Ajax function.....

function getCusId(name) {
$.ajax({
url: '/Sale/getCustomerId',
datatype: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ CusName: name }),
async: true,
processData: false,
cache: false,

success : function (Data) {
return Data;
},
error : function (xhr) {
// alert("error");
return null;
},
error: function (exception) {
alert('Exeption:' + exception);
}
})
}

catching return value....

var cusid = getCusId(name);
David_Wimbley 10-Sep-16 7:54am
   
I said do async as false not true, in your code it's set to true. Change it to false
Member 11883599 10-Sep-16 8:46am
   
I tried same, but prob is same only, debugger giving this error
Local
cusid
:
undefined
data
:
undefined
isAllValid
:
true
this
:
input#submit.btn.btn-success
Rate this:
Please Sign up or sign in to vote.

Solution 2

Hi All, Finally I found the issue. I just used Ajax calls in a function and called, which did not work. So I included to a drop-down list text change method and it works fine now. Here is total code.

$("#Customer").change(function () {
            var name = $("[id*='Customer'] :selected").text();
            $.ajax({
                url: '/Sale/getCustomerId',
                datatype: "json",
                type: "POST",
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify({ CusName: name }),
                async: true,
                processData: false,
                cache: false,

                success: function (Data) {
                    cusid= Data;
                },
                error : function (xhr) {
                    //  alert("error");
                    return null;
                },
                error: function (exception) {
                   // alert('Exeption:' + exception);
                    swal("Ooops", 'Exeption:' + exception, "error");
                }
            })       
        })



public JsonResult getCustomerId(string CusName)
       {

           var result = db.People.Where(x => (x.FName+ " " + x.LName) == CusName).Select(x => x.Id).Distinct().ToList().FirstOrDefault();

           return Json (result);
       }
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100