Akshay
Akshay

Reputation: 391

Send form data to another page in JSON format

Hello I'm trying to submit my form in the JSON format which redirects to the new page. I am using the json.serialize plugin to serialize my form data. When the click the submit button the page redirects and all the data is lost. I don't want to pass the data in url, can we pass the data with some other method.

Here is my code -

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.serializeJSON/2.9.0/jquery.serializejson.min.js"></script>

 <form id="form" method="post" action="otherpage.jsp">
<table>
  <thead>
    <tr>
      <th>Field 1</th>
      <th>Field 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" name="field1[]">id1</td>
      <td><input type="hidden" name="field2[]">dsda</td>
    </tr>
    <tr>
      <td><input type="text" name="field1[]">id2</td>
      <td><input type="hidden" name="field2[]">dsda</td>
    </tr>
  </tbody>
</table>
<button type="button" name="button" id="button">Submit</button>
</form>

Javascript -

  <script>
  $("#button").click(function(e){
    var jsonForm = $("#form").serializeJSON();
    var jsonFormString = JSON.stringify(jsonForm);
    localStorage.setItem('jsonFormData', JSON.stringify(jsonForm));
    $("#form").submit();
    var localObj = JSON.parse(localStorage.getItem(jsonFormData));
    console.log(localObj);
  });
 </script>

Upvotes: 0

Views: 787

Answers (2)

Udara Kasun
Udara Kasun

Reputation: 2216

In Html

   <button type="submit" name="button" id="button">Submit</button>

In script

$("#form").submit(function(){
    var jsonForm = $("#form").serializeJSON();
    var jsonFormString = JSON.stringify(jsonForm);
    localStorage.setItem('jsonFormData', JSON.stringify(jsonForm));        
});

in otherpage.jsp Script

$(document).ready(function(){   
    var localObj = JSON.parse(localStorage.getItem('jsonFormData')); 
    console.log(localObj);  
    alert(localObj.field1);
});

Example Codepen

Upvotes: 0

cli-ish
cli-ish

Reputation: 776

You are missing the ´e.preventDefault()´ function which disables the submit.

Upvotes: 1

Related Questions