1

I have a php function that I call using ajax and then handle the response with ajax. However, I want to prevent the page from reloading.

I have index.php containing a call to function1(), and it includes ajaxcall.js and jquery

Then my functions.php:

function function1(){
echo '
            <form id="myform" action="" method="post" enctype="multipart/form-data">    
            <input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this)" placeholder="type an anime name" title="Type in a name">
            </form>
            <div id="table_recentanime" class="hscroll">   
            <table dir="ltr"   id="myTable">';
    // echo some table rows

}


if (isset($_POST['callyoukai_search'])) {
    //echo "!!!" . $_POST['callyoukai_search'] . "the post value in php!!!!!!";
     //echo 
     youkai_search($_POST['callyoukai_search']);
}

function youkai_search ($search_word){
// use $search_word to do a database query
return $result;
}

my ajaxcall.js

function searchfiltersajax(search_word){
    if(event.key === 'Enter') {
        console.log("yes");
        console.log(search_word.value);
document.getElementById("myform").addEventListener("Keypress", function(event){
        event.preventDefault()
      });

       jQuery.ajax({
        url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
        type: 'post',
        data: { "callyoukai_search": "1"},
        success: function(response) { var container = document.getElementById("myTable");
        container.innerHTML = response;
        console.log('php gave javascript '); console.log(response); console.log('php gave javascript '); }
    });

    console.log ("done");
    }


}

My ajax call works fine. It calls the php function with the desired search_word, and the search results replaces the div content just like I want. However, right after this, the page reloads.

How do I prevent the reload? I tried preventDefault(), but the way I used it didn't work.

Thanks in advance

kyle
  • 691
  • 1
  • 7
  • 17
user206904
  • 504
  • 4
  • 16
  • if I didn't see it wrong, your ajax should be inside your `addEventListener` 's callback – Tsuna Jan 30 '19 at 19:38

2 Answers2

2

Inlining event handlers is a bad practice. But if you need it at least add the event keyword. Change from:

to:

<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"

Moreover, don't add the same event handler (i.e.: Keypress) inside another: in this way you are adding more and more times the same event handler. Instead, use the event parameter.

I'd suggest to use the addEventListener() or .on():

$('#myInput').on('keydown', function(e) {
      searchfiltersajax(this, e);
});

The snippet:

function searchfiltersajax(search_word, e) {
    if (event.key === 'Enter') {
        e.preventDefault();
        console.log("yes");
        console.log(search_word.value);


        jQuery.ajax({
            url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
            type: 'post',
            data: {"callyoukai_search": "1"},
            success: function (response) {
                var container = document.getElementById("myTable");
                container.innerHTML = response;
                console.log('php gave javascript ');
                console.log(response);
                console.log('php gave javascript ');
            }
        });

        console.log("done");
    }
}
<form id="myform" action="google.com" method="post" enctype="multipart/form-data">
    <input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"
           placeholder="type an anime name" title="Type in a name">
</form>
<div id="table_recentanime" class="hscroll">
    <table dir="ltr" id="myTable">
        <tbody>
        </tbody>
    </table>
</div>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • 1
    thanks for giving a code snippet with a slight modification to fix the issue + suggesting a better solution/practice. – user206904 Feb 01 '19 at 16:48
  • I tried "jQuery('#myInput').on('keydown' ...." as suggested but it didn't work. any idea? and thanks in advance. P.S I'm using wordpress that's why I replaced the $ with jQuery – user206904 Feb 02 '19 at 17:22
  • 1
    did you wrap it in [dom ready](https://learn.jquery.com/using-jquery-core/document-ready/)? – gaetanoM Feb 02 '19 at 19:05
1

The function searchfiltersajax takes one parameter named search_word. The first if-statement then checks an event-variable. This variable is declared nowhere in your code, so the code inside the if-statement will never get executed.

To verify this I would recommend to add debugger; as first statement inside the searchfiltersajax function. Then open the debugging console in the browser and reload the page. Do not forget to remove the debugger; statement once you are finished. If you know how to set breakpoints in the javascript debugger, you should not use debugger; statements at all.

As far as I understand you try to prevent a form to be submitted to the server but send an ajax call instead. There are several answers on StackOverflow for this topic, e.g. Prevent users from submitting a form by hitting Enter . You could use a code like this to achieve your goals (taken from the link):

$(document).on("keypress", "form", function(event) { 
    return event.keyCode != 13;
});

Last but not least, I would suggest not to include raw HTML sent by any server (even your own) to your page:

container.innerHTML = response;

Instead try to send a JSON object containing the information you wish to present and transform this object into HTML elements via JavaScript. This way you have a cleaner interface for data exchange and have to change on piece of code to change styling or other presentation aspects.

DwightKendall
  • 194
  • 1
  • 3
  • thanks for giving a good solution, and explaining the problem that caused the issue. I up voted your answer. I was going to use JSON but I didn't use it just to reduce the number of possible issues, I will add it in the final version. – user206904 Feb 01 '19 at 16:51