5

Hi I'm currently trying to get a form to post a controller using AJAX however I've had no luck so far, I have been trying to get the form to submit the values in the form to the controller on the submit of the form but it won't work does anybody know why? :

CSHTML:

@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Abintegro Search Prototype</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $("#submitsearch").click(function (e) {
            e.preventDefault();
            var form = $("#searchform");
            $.ajax({
                url: "Search/GetSearchDetails",
                data: form.serialize(),
                type: 'POST',
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        });
</script>

    <!-- Javascript function to add autocomplete search phrases for the company name text search-->
    <script>
        $(function () {
            var searchPhrases = [
                "Zep Solutions",
                "Wetherby Consultants Ltd",
                "Webmploy",
                "WATS Recruitment Ltd",
                "Vital Resources",
                "VG Charles and Co",
                "Veredus UK",
                "Venn Group",
                "VanDuo Consulting"
            ];
            $("#phrases").autocomplete({ source: searchPhrases });
        });
</script>
</head>

<body>
    <form id="searchform" name="searchform">

        <div class="company-textbox">
        <label for="companyname">Company Name</label>
        <input id="phrases" name="companyname">
        </div>

        <br />

        <div class="specialities">
            <label for="specialities-dropdown">Specialities:</label>
            <select name="specialities-dropdown">
                <option value="Consumer Products & Services">Consumer Product & Services</option>
                <option value="Support Services">Support Services</option>
                <option value="Communication & Entertainment">Communication & Entertainment</option>
                <option value="Business & Professional Services">Business & Professional Services</option>
                <option value="Public Sector">Public Sector</option>
                <option value="Not for profit">Not for profit</option>
                <option value="Sports Information">Sports Information</option>
            </select>
        </div>

        <br />

        <div class="category">
            <label for="category-dropdown">Category:</label>
            <select name="category-dropdown">
                <option value="Generalist">Generalist</option>
                <option value="Specialist">Specialist</option>
                <option value="Exec Search">Exec Search</option>
                <option value="Interim Management">Interim Management</option>
            </select>
        </div>    

        <br />

        <div class="location-dropdown">
            <label for="location-dropdown">Location:</label>
            <select name="Location">
                <option value="London">London</option>
                <option value="Bristol">Bristol</option>
                <option value="Manchester">Manchester</option>
                <option value="Birmingham">Birmingham</option>
            </select>
        </div>

        <input type="submit" value="Submit" name="submitsearch" id="submitsearch">
    </form>
</body>
</html>

Controller:

 [HttpPost]
        public string GetSearchDetails(string companyName, string specialities, string category, string location)
        {
           return liveSearchRepository.GetUserInputResults(companyName,specialities,category,location);
        }
4
  • what does form.serialize() yield? It's better if you create a poco class for your POST operation,and sens the data accordingly from your script. Commented Feb 29, 2016 at 9:43
  • Try to insert dataType: "html", as an argument in your .ajax call Commented Feb 29, 2016 at 9:44
  • What exactly isn't working? Can you debug the Javascript to verify that it should be sending the post data to your controller? Commented Feb 29, 2016 at 9:50
  • In the debugger, using Chromes debugger, the function seems to go into an endless loop on $("#submitsearch").click(function (e) { Commented Feb 29, 2016 at 9:55

3 Answers 3

2

From what I can see it looks like your form controls and your Controller action does not link up properly because your controls' names is not the same as your action's parameters.

Also change the contentType in your ajax call to JSON and convert the form data to a JSON string. That way if you output the form data to the console before submitting it via Ajax, you can see what is sent through.

Try the following modifications:

@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Abintegro Search Prototype</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $("#submitsearch").click(function (e) {
            e.preventDefault();

            var formData = JSON.stringify($("#searchform").serializeArray());

            console.log(formData);

            $.ajax({
                url: "Search/GetSearchDetails",
                data: formData,
                type: 'POST',
                contentType: 'json'
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        });
</script>

    <!-- Javascript function to add autocomplete search phrases for the company name text search-->
    <script>
        $(function () {
            var searchPhrases = [
                "Zep Solutions",
                "Wetherby Consultants Ltd",
                "Webmploy",
                "WATS Recruitment Ltd",
                "Vital Resources",
                "VG Charles and Co",
                "Veredus UK",
                "Venn Group",
                "VanDuo Consulting"
            ];
            $("#phrases").autocomplete({ source: searchPhrases });
        });
</script>
</head>

<body>
    <form id="searchform" name="searchform">

        <div class="company-textbox">
        <label for="companyName">Company Name</label>
        <input id="phrases" name="companyName">
        </div>

        <br />

        <div class="specialities">
            <label for="specialities">Specialities:</label>
            <select name="specialities">
                <option value="Consumer Products & Services">Consumer Product & Services</option>
                <option value="Support Services">Support Services</option>
                <option value="Communication & Entertainment">Communication & Entertainment</option>
                <option value="Business & Professional Services">Business & Professional Services</option>
                <option value="Public Sector">Public Sector</option>
                <option value="Not for profit">Not for profit</option>
                <option value="Sports Information">Sports Information</option>
            </select>
        </div>

        <br />

        <div class="category">
            <label for="category">Category:</label>
            <select name="category">
                <option value="Generalist">Generalist</option>
                <option value="Specialist">Specialist</option>
                <option value="Exec Search">Exec Search</option>
                <option value="Interim Management">Interim Management</option>
            </select>
        </div>    

        <br />

        <div class="location">
            <label for="location">Location:</label>
            <select name="Location">
                <option value="London">London</option>
                <option value="Bristol">Bristol</option>
                <option value="Manchester">Manchester</option>
                <option value="Birmingham">Birmingham</option>
            </select>
        </div>

        <input type="submit" value="Submit" name="submitsearch" id="submitsearch">
    </form>
</body>
</html>

EDIT

If you change the following line:

var formData = JSON.stringify($("#searchform").serializeArray());

With this piece of code:

var formData = "";
$.each($("#searchform"), function(i,v) {
    if (formData.length > 0) formData += ",";
        formData += v.name + ": '" + v.value + "'";
});
formData = "{ " + formData + " }";

The solution will be generic and you would not have to change the code if you change the names of the form field.

Sign up to request clarification or add additional context in comments.

4 Comments

[{"name":"companyname","value":"Wetherby Consultants Ltd"},{"name":"specialities","value":"Consumer Products & Services"},{"name":"categorys","value":"Generalist"},{"name":"locations","value":"London"}]
[HttpPost] public string GetSearchDetails(string companyname, string specialities, string categorys, string locations) { return liveSearchRepository.GetUserInputResults(companyname,specialities,categorys,locations); }
In the above this is the data been posted I now hit the controller but each parameter is null?
function postToAjax() { debugger; var formData = JSON.stringify($("#searchform")); console.log(formData); $.ajax({ url: "Search/GetSearchDetails", data: formData, contentType: "application/json; charset=utf-8", type: 'POST', success: function (data) { //Show popup $("#popup").html(data); } }); } </script>
1

Use this Javascript code instead of current one. I have corrected issues in post data and the correct formate is below :

<script>
        $("#submitsearch").click(function (e) {
            var postData = $(this).serializeArray();
            e.preventDefault();
            var form = $("#searchform");
            $.ajax({
                url: "Search/GetSearchDetails",
                data: postData,
                type: 'POST',
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        });
</script>

4 Comments

When I debug this code it gets to: $("#submitsearch").click(function (e) { and then steps into a file called BrowserLink where it seems to get stuck in a loop, a sample of the code: (i.log("Invalid transport: "+f+", removing it from the transports list."),t.splice(u,1));t.length===0&&(i.log("No transports remain within the specified transport array."),t=null)}else if(n.type(t)==="object"||r.transports[t]||t==="auto"){if(t==="auto"&&r._.ieVersion<=8)return["longPolling"]}else i.log("Invalid transport: "+t.toString()+"."),t=null;return t}function b(n){return
Can you please check console with browsers inspect element tool and share me the error your received .
It isn't an error it just gets stuck in a loop on a line of code in a file called 'BrowserLink'
Can you send me link to the website where you have problems.
0

To fix this issue so that the post mapped the values to the parameters I did the following:

function postToAjax() {
            debugger;
            var companyname = $('#phrases').val().toString();
            var specialities = $('#specialities').val().toString();
            var categorys = $('#categorys').val().toString();
            var locations = $('#locations').val().toString();
            var postData = $(this).serializeArray();
            var form = $("#searchform");
            $.ajax({
                url: "Search/GetSearchDetails",
                data: { 'companyname': companyname, 'specialities': specialities, 'categorys': categorys, 'locations':locations },
                type: 'POST',
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        }
   </script>

By creating variables for each value I could then map the value pairs in the data, the name of the parameter in the controller is the first part of the pair, followed by the value taken from the created variables storing the values from the form element.

1 Comment

By iterating through the controls in the form you can make it generic in order to prevent having to change the code if the form controls change or if you should add another control. Please see the edit on my answer for an example of this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.