skip to Main Content

Ajax request that returns an array in a JSON format. Loop through the returned array to spit out entries from one of the columns and display using html divs.

Problem is the results only display on the webpage for a nano-second and then disappear.

Do I need prevent default in there? Are the curly brackets etc in the correct places?

JQuery snippet:

$(document).ready(function(){
    $(":submit").click(function(e){
        var msg = $("#search").val();
        $.ajax({
            url:'search.php',
            method:'POST',
            data:{
                msg:msg
            },
            dataType: 'json',
            success: function(response) {

            for( var key of Object.keys( response ) ) {
            $( '.content' ).append( `<div class="post"><div class="post-text">${response[key].MessageText}</div></div>` );

                }
             }
        });  
    });  
});  

Html:

<form action="index.php" method="post" autocomplete="on"><pre>

<input name="msg" id="search" type="text" autofocus value= "<?php if(isset($_POST['msg'])) { 
 echo htmlentities ($_POST['msg']); }?>"></input> <span id="error"></span>

<input type="submit" id="submit" style="border:0; padding:0; font-size:0">

</pre></form>

<div class="content"></div>

2

Answers


  1. Technically the issue is when you click on submit then it refreshes the page and that’s why you see the DOM change just for a short period of time.

    Maybe you can try the following:

    $(document).ready(function(){
        $(":submit").click(function(e) {
            var msg = $("#search").val();
            $.ajax({
               // ajax call details
            });
    
            // this step should stop refreshing the page
            e.preventDefault();
        });  
    });  
    

    From event.preventDefault() documentation:

    If this method is called, the default action of the event will not be triggered.

    I hope that helps!

    Login or Signup to reply.
  2. Consider the following example.

    $(function() {
      $(":submit").click(function(e) {
        e.preventDefault();
        $.ajax({
          url: 'search.php',
          method: 'POST',
          data: {
            msg: $("#search").val()
          },
          dataType: 'json',
          success: function(response) {
            $.each(response, function(i, v) {
              var p = $("<div>", {
                class: "post item-" + i
              }).appendTo($(".content"));
              $("<div>", {
                class: "post-text"
              }).html(v.messageText).appendTo(p);
            });
          }
        });
      });
    });
    

    To prevent the form from submitting you want to apply .preventDefault() on the event. This will ensure that your code gets run and the form submit the data by default.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search