简体   繁体   中英

how to get form field value and send to server as json using ajax jquery

I have search form with 6 fields and 1 search button. when user fill the form deatails and click on search button, i need to send the form field values as json to server using jquery ajax.

then the server will send the search values and returns the response, then i need to populate those valuse in ui. i need sample UI code for jquery ajax . please can anyone help on this? below is my html form

<form name="NAME" id="customerDetailSearchForm" action="">
  <fieldset>
     <legend>Search Contact</legend>
     <table width="100%" cellpadding="0" cellspacing="0" class="vzuui-detailpanel">
        <tr>
           <td><label>Name :</label><input type="text" value="" /></td>
           <td><label>City :</label><input type="text" value="" /></td>
           <td><label>Phone :</label><input type="text" value="" /></td>
        </tr>
        <tr>
           <td><label>Address :</label><input type="text" value="" /></td>
           <td><label>State Prov :</label><input type="text" value="" /></td>
           <td><label>Email :</label><input type="text" value="" /></td>
        </tr>
     </table>
  </fieldset>
   <button class="vzuui-btn-red-active closeedit" type="button" id="search">Search</button>

Here you go

Convert form data to JavaScript object with jQuery

But before that you have to add name attribute for each input element.

So that name will be your json key and the data in the box will be value of that key as below

<input name='username' value='' />

Will become

{"username": "john"}

jhon is value entered in input box.

**edit (Ajax code) **

$(function() {
    $('#customerDetailSearchForm').submit(function() {
     $.post("//your URL here",JSON.stringify($('#customerDetailSearchForm').serializeObject()), function(result){

        alert("Data posted successfully!!");

    });
  });
});

or replace below line if you dont have submit button in the form

$('#customerDetailSearchForm').submit(function() {

with

$('#search').click(function() {

Here is simple Ajax Code that I use in Asp.net MVC I think This will help you,

$.ajax({
                beforeSend: function (xhr) {
                    AjaxRequestStart();
                },
                error: function (result) {
                                     },
                complete: function () {
                    AjaxRequestFinish();
                },
                url: '@Url.Content("~/Project/SaveProject")',
                type: 'POST',
                data: $('#frmAddProject').serialize(),
                success: function (result) {

                }
            });

First of all you will need to change you HTML form code to include name attribute in the textfields like below

<form name="NAME" id="customerDetailSearchForm" action="">
  <fieldset>
     <legend>Search Contact</legend>
     <table width="100%" cellpadding="0" cellspacing="0" class="vzuui-detailpanel">
        <tr>
           <td><label>Name :</label><input type="text" value="" name="name" /></td>
           <td><label>City :</label><input type="text" value="" name="city" /></td>
           <td><label>Phone :</label><input type="text" value="" name="phone" /></td>
        </tr>
        <tr>
           <td><label>Address :</label><input type="text" value="" name="address" /></td>
           <td><label>State Prov :</label><input type="text" value="" name="state" /></td>
           <td><label>Email :</label><input type="text" value="" name="email" /></td>
        </tr>
     </table>
  </fieldset>
   <button class="vzuui-btn-red-active closeedit" type="button" id="search">Search</button>

This is required because we will be using jQuery serializeArray() Method which creates an array of objects (name and value) by serializing form values.

Now the jQuery part to form the JSON data from your form and make the AJAX call.

<script type="text/javascript">
$(document).ready(function(){
  $("#search").click(function(){

     var frm = $("customerDetailSearchForm").serializeArray();
      var obj = {};
      for (var a = 0; a < frm.length; a++) {
         obj[frm[a].name] = frm[a].value;
      }
        var jsonData = JSON.stringify(obj);

    $.ajax({ 
        type: 'GET', 
        url: 'http://example.com', 
        data: jsonData , 
        dataType: 'json',
        success: function (data) { 
           // add result to UI code over here
        }
    });
  });
});
</script>

EDIT

The above javascript snippet edited to generate proper JSON value

Here i agree with @Aniket. add name first for each input type.

<form name="NAME" id="customerDetailSearchForm" action="your_url">
  <fieldset>
     <legend>Search Contact</legend>
     <table width="100%" cellpadding="0" cellspacing="0" class="vzuui-detailpanel">
        <tr>
           <td><label>Name :</label><input type="text" value="" name="name" /></td>
           <td><label>City :</label><input type="text" value="" name="city" /></td>
           <td><label>Phone :</label><input type="text" value="" name="phone" /></td>
        </tr>
        <tr>
           <td><label>Address :</label><input type="text" value="" name="address" /></td>
           <td><label>State Prov :</label><input type="text" value="" name="state" /></td>
           <td><label>Email :</label><input type="text" value="" name="email" /></td>
        </tr>
     </table>
  </fieldset>
   <button class="vzuui-btn-red-active closeedit" onclick="_submit();" type="button" id="search">Search</button>

For calling ajax, you can use this.

function _submit{
       $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'your_url',
                data: $("#customerDetailSearchForm").serialize(),
                success: function(responseData, textStatus) {
                    // you implementation logic here
                },
                complete: function(textStatus) {

                },
                error: function(responseData)
                {

                }
            });
        }

You can refer below sample ajax call on form submit

$("#customerDetailSearchForm").submit(function(e) {

             var postData = $('#conatctUs').serializeArray();
             var formURL = $('#conatctUs').attr("action");
             var formName  = $('#conatctUs').attr('name');

             $.ajax({
                    url : formURL,
                    type: "POST",
                    data : postData,
                    success:function(data)
                    {
                        if(data.status){
                            console.log(data);
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown)
                    {

                    }


            e.preventDefault(); 
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM