0

I managed to get my Wordpress jQuery wired properly. Everything gets inserted to the database as expected, but for some reason, it is still refreshing the whole page?

php/html (Wordpress Page Template):

<?php
if(isset($_POST['send']))
{
   send_projectmessage($projectid, $userid, $projectmessage);
}
?>
<html>
<body>
<div id="messages">
<?php 
$messages = load_projectmessages($projectid);
        foreach ($messages as $message) { /*echo the messages and put in a nice div*/ }
?>
</div>
<form id="form-pm" method="post" enctype="multipart/form-data" action="">
            <textarea name="projectMessage" rows=3 id="project-message"></textarea>

            <input type="submit" name="send" value="send message">
</form>

JS:

$('#form-pm').on('send', function(e) {

        e.preventDefault();

        var ajaxRequest =
        $.ajax({
            url: admin_ajax.ajax_url,
            type: 'post',
            data: { 
                action: 'send_projectmessage',
                projectid: 'projectid',
                userid: 'userid',
                projectmessage: 'projectmessage'
                }, 
            contentType: 'application/json; charset=utf-8',
            dataType: 'json' });

        ajaxRequest.done(function() { } );
        ajaxRequest.fail(function(jqXHR) { alert('You are fail. ' + jqXHR); } );

        return false;
    });

functions.php

function send_projectmessage($projectid, $userid, $message) {
    global $wpdb;
    $wpdb->insert('tbl_messages', array(
        'project_id' => $projectid,
        'user_id' => $userid,
        'message_body' => $message
    ));
    return false;
    wp_die();
}
add_action('wp_ajax_send_projectmessage', 'send_projectmessage');

I have the e.preventDefault(); and also return false. My message gets inserted properly into the MySql table, but the whole page still reloads!

1

You use wrong js event. You register your callback with this code:

$('#form-pm').on('send', function(e) {

But there is no event called send on form. It should be submit. Here’s fixed version of that line:

$('#form-pm').on('submit', function(e) {
  • I actually have 2 forms, 1 submit button already has a name=submit, and for this form I have <input type="submit" name="send" value="send message">, so when I use 'submit' I get a Bad Request 400 – Rollor Feb 20 '19 at 18:38
  • 1
    Name has nothing to do with this. When the form is submitted, then you can handle submit js event. It doesn’t depend on the name of submit button... – Krzysiek Dróżdż Feb 20 '19 at 18:39
  • Gotcha. Thank you. I think this answers my original question. Now I have to deal with the Bad Request 400 – Rollor Feb 20 '19 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.