$wpdb Ajax not redirecting to main page

Question

I’m having difficulty with redirecting a page once a person submits data. I made a form, and when the user clicks ‘Add student’, the data would be encoded through json, stored in the database. The page would be would be redirected and refreshed by a custom jQuery class, which refers to a blank div with a class called “messageDiv” (first line of code dispayed below.

However, when a user submits data, they are taken a blank white page with the json string echoing a success or failure upon submission. I’m not sure why the page is not being redirected correctly, and why it takes the user to a blank json page.

How the success message is supposed to be displayed:

<div class="messageDiv"></div>

My ajax code:

jQuery(function() 
    {
        jQuery("#myForm").submit(function(event) 
        {
            event.preventDefault();
        
        // ajax function
        jQuery.ajax
            ({
                dataType: "json",
                type: "post",
                data: jQuery("#myForm").serialize(),
                url: "../admin-ajax.php",
                success:function(data) 
                {
                
                    jQuery(".messageDiv").html(data.message);
                    
                    if(data.status == 1)
                    {
                        jQuery("#myForm").trigger('reset');
                    }
                },

            });
        });
        
    });

The backend database query and connection:

if(isset($_POST['BtnSubmit']))
{
    global $wpdb;
    
    $data_array = array(
        'first_name' => $_POST['first_name'],
        'last_name' => $_POST['last_name']
        );
        
        $table_name="students";
        
        $rowResult = $wpdb->insert($table_name, $data_array, $format=NULL);
        
        
        if($rowResult == 1) 
        {        
            echo json_encode(array('message' => '<h1>Form added into the database<h1>', 'status' => 1));
        } else 
        {
            echo json_encode(array('message' => '<h1>Error Form submission<h1>', 'status' => 0));
        }
        
        die();
} 

0
John Lyons 1 month 2022-10-20T14:54:42-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse