Search code examples
jqueryjquery-uimodel-view-controllerasp.net-ajax

Send another variable using jquery/ajax


This is my code

 $(function () {
              
               
                $("#txtUserName").autocomplete({
                   
                    source: function (request, response) {
                        $.ajax({
                           

                            url: '/Home/UserNameAutoComplete',
                            data: 
                               
                                "{ 'username': '" + request.term + "'}",
  • I want to send another variable txtLastName.val()

i tried doing this

 data: { term: request.term, agency:$('#txtLastName').val())}
                               

But its giving me an error:

<title>Invalid JSON primitive: term.</title>

Solution

  • The error you reported is due to a typo:

    data: { term: request.tem, agency:$('#txtLastName').val())}
    

    You will see that request.tem does not exists. You want to call request.term.

    Assuming your script can accept it, you can do the following.

    $(function () {
      $("#txtUserName").autocomplete({
        source: function (request, response) {
          $.ajax({
            url: '/Home/UserNameAutoComplete',
            data: {
              username: request.term,
              agency: $('#txtLastName').val()
            },
            success: function(data){
              response(data);
            }
          });
        }
      });
    });
    

    I notice in your example, you're sending a text string: "{ 'username': '" + request.term + "'}" which is a little strange. If that is truely what you need to send, it would be something like:

    data: "{ 'username': '" + request.term + "', 'agency': '" + $('#txtLastName').val() + "'}"
    

    I suggest testing my first solution.