Young Young - 1 month ago 5
Javascript Question

How to send getJson request and submit input form at the same time

I am trying to create an input form that both displays AJAX response and submits input. However, since submit will refresh the page, AJAX response is removed immediately after the form is submitted. How do I retain the response?

Below is my code.



$('#inputButton').click(function () {
var URL = 'URLEXAMPLE';
$.getJSON(URL, function(data){

for (var i = 0; i < data.length; i++){
var info = data[i].content;
$("#jsonInfo").append(info);
};
});


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inputButton" type="submit" value="Done">
<div id="jsonInfo"></div>




Answer

Reason for code not working:

1.check your json was not closing proberly.

2.And try with apply document.ready

3.From tag not Available in your Html page.I was added the form tag.

$(document).ready(function (){
                $('#inputButton').click(function (e) {
                    var URL = 'URLEXAMPLE';
                    $.getJSON(URL, function(data){

                        for (var i = 0; i < data.length; i++){
                            var info = data[i].content;
                            $("#jsonInfo").append(info);
                        };
                      })
                   console.log('Its work')
                    e.preventDefault();
                });
});
            </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="inputButton" type="submit" value="Done">
            <div id="jsonInfo"></div>
  </form>

Comments