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
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:
From
event.preventDefault()
documentation:I hope that helps!
Consider the following example.
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.