3

I want to pass multiple parameters to my ajax code. Which is 3 parameters. So, I added like below

$(document).ready(function () {
        SearchText();
    });
    function SearchText() {
        $("#txt712").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "FrmAgreementMaster.aspx/GetAutoCompleteData",
                    //data: "{'username':'" + extractLast(request.term) + "'}",
                    data: JSON.stringify("{'username':'" + extractLast(request.term) + "'}", "{'taluka':'" + document.getElementById('ddlTaluka').value + "'}", "{'village':'" + document.getElementById('ddlVillage').value + "'}"),
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            },
            focus: function () {
                return false;
            },
            select: function (event, ui) {
                var terms = split(this.value);
                terms.pop();
                terms.push(ui.item.value);
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
        });
        $("#txt712").bind("keydown", function (event) {
            if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).data("autocomplete").menu.active) {
                event.preventDefault();
            }
        })
        function split(val) {
            return val.split(/,\s*/);
        }
        function extractLast(term) {
            return split(term).pop();
        }
    }

By taking reference from HERE of Darin's code.

But it is taking me to ERROR part while calling the function. How do I pass multiple parameters to use it.

update

Also, I took the ajax reference from here

Response code:-

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static List<string> GetAutoCompleteData(string username, string taluka, string village)
{
    List<string> result = new List<string>();
    using (OracleConnection ObjPriCon = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OracleConn"].ToString()))
    {

        using (OracleCommand cmd = new OracleCommand("select distinct survey_area_7_12 FROM xxcus.xxacl_pn_farming_mst WHERE survey_area_7_12  " +
                                                     "LIKE '%' || :searchtext || '%' and taluka = '" + taluka + "' and village = '" + village + "'", ObjPriCon))
        {
            ObjPriCon.Open();
            cmd.Parameters.AddWithValue(":searchtext", username.ToLower());
            OracleDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    result.Add(dr["survey_area_7_12"].ToString());
                }
            }
            return result;
        }
    }
}
Community
  • 1
  • 1
Nad
  • 4,605
  • 11
  • 71
  • 160
  • add data: JSON.stringify("{'username':'" + extractLast(request.term) + "','taluka':'" + document.getElementById('ddlTaluka').value + "','village':'" + document.getElementById('ddlVillage').value + "'}"), single json string – pawan sen Nov 09 '16 at 07:12

5 Answers5

5

You can pass multiple params like:

$.ajax({
...
data: {
    var1: val1,
    var2: val2,
    var3: val3,
    var4: val4,
    // and many more
}
...
});

In case you want to pass an array, than you can use 'JSON.stringify'.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
1

Try to pass data like this:

data: JSON.stringify([
    {username: extractLast(request.term)},
    {taluka: document.getElementById('ddlTaluka').value},
    {village: document.getElementById('ddlVillage').value}
]),

Or like this:

data: {
    username: extractLast(request.term),
    taluka: document.getElementById('ddlTaluka').value,
    village: document.getElementById('ddlVillage').value
},
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • tried both ur code, but getting into error part `error: function (result) { alert("Error"); }` – Nad Nov 09 '16 at 07:17
  • how does a query look? check in network tab. and what's in the result? – Max Koretskyi Nov 09 '16 at 07:20
  • query is smoething like this `SELECT DISTINCT survey_area_7_12 FROM xxcus.xxacl_pn_farming_mst WHERE survey_area_7_12 LIKE '%' || :searchtext || '%' AND taluka = '3' AND village = '1'` and the result is `32/0 30/2` – Nad Nov 09 '16 at 07:23
  • no, I mean HTTP query, check [the network tab](https://www.youtube.com/watch?v=AXGB4tIRNgM) – Max Koretskyi Nov 09 '16 at 07:24
  • Getting preview something like this `{Message: "Invalid JSON primitive: username.",…} ExceptionType : "System.ArgumentException" Message : "Invalid JSON primitive: username." StackTrace : " at System.Web.Script.Serialization.JavaScriptObjectDeserializer‌​.DeserializePrimitiv‌​eObject() ↵` – Nad Nov 09 '16 at 08:03
  • we need to see what goes from a browser, let's discuss in chat – Max Koretskyi Nov 09 '16 at 08:04
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127693/discussion-between-maximus-and-nad). – Max Koretskyi Nov 09 '16 at 08:04
1

You don't need multiple object, you need multiple properties in a object

 data: JSON.stringify({username: extractLast(request.term) , taluka: $('#ddlTaluka').val(), village:$('#ddlVillage').val()}),

Ps: Don't forget that you trigger the autocomplete at page ready, make sure you have values in those inputs

madalinivascu
  • 32,064
  • 4
  • 39
  • 55
  • tried this too, not woking.. Getting same `error` alert – Nad Nov 09 '16 at 07:20
  • @madalinivascu, it's funny that we suggested the solution specific to the problem and have no upvotes, while the other answer suggesting generic approach gets upvotes. go figure – Max Koretskyi Nov 09 '16 at 07:25
  • i am not familiar with .net but you are returning text instead of json, and you are sending json , does your .net function accept json as input? – madalinivascu Nov 09 '16 at 07:31
  • what response code does your xhr request have? 404 500 ? – madalinivascu Nov 09 '16 at 07:38
  • @madalinivascu: how do I check that? as of now it gives me alert as `Error`. – Nad Nov 09 '16 at 07:39
  • go to the developer tools on the tab network do a page refresh with the tab open ,after the page is fully loaded look for a request type xhr with your ajax request url you will see there the response code and the page preview as well – madalinivascu Nov 09 '16 at 07:41
  • Getting preview something like this `{Message: "Invalid JSON primitive: username.",…} ExceptionType : "System.ArgumentException" Message : "Invalid JSON primitive: username." StackTrace : " at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() ↵` – Nad Nov 09 '16 at 07:47
  • anything which I missed ? – Nad Nov 09 '16 at 08:04
  • the json seems to be invalid , try the updated answer or set processData to false – madalinivascu Nov 09 '16 at 08:07
  • are you their ? – Nad Nov 09 '16 at 08:45
  • Upvoting ur answer though. THANKS :) – Nad Nov 09 '16 at 09:29
0

The simplest way is to assign an object containing the key value pair of your data to the data attribute of your ajax call.

$.ajax({
   type: 'POST',
   url: url,
   data: {
      'name': $('#name').val(),
      'email': $('#email').val(),
      // so on...
   }
})

and then you can simply get them in your post request by the names you specify here.

Salman Ghauri
  • 574
  • 1
  • 5
  • 16
0

Please try to do this.

 $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "FrmAgreementMaster.aspx/GetAutoCompleteData",
                //data: "{'username':'" + extractLast(request.term) + "'}",

        data: JSON.stringify({
            username: extractLast(request.term),taluka:document.getElementById('ddlTaluka').value,village:document.getElementById('ddlVillage').value
        }),
                error: function (result) {
                    alert("Error");
                }
            });
Ronachai.K
  • 19
  • 1