0

I am trying to save the form data using WordPress default ajax but it returns 200 but does not saving in database.

Well, i tried everything but my form does not store form data but successfully i a able to get using console log.

I am trying to add the form detail using wordpress default ajax so that i created a form at admin side. For ajax i created js file and included as admin and function for inserting data added in php file.

Now everything works fine, my page is submitting with ajex and also printed the form data , and getting all form data in console.That is also ok.

My ajax is loading but not able to save the data in database . here are some code below.

PHP code


function Adduser()
{
    if(isset($_POST["btnsave"]))
    {
        global $wpdb;

        $fname=$_POST["fname"];
        $lname=$_POST["lname"];
        $email=$_POST["eml"];
        $phn=$_POST["phn"];
        $adr=$_POST["adr"];

        $qry="insert user_data values(null,'$fname','$lname','$email','$phn','$adr')";
        $result=$wpdb->query($qry);
        if($result==true)
        {
            echo "<script> alert('Data Inserted'); </script>";
        }
        else
        {
            echo "<script> alert('Enter valid data Please '); </script>";
        }


    }

    ?>
<form action="?page=user-data" class="form" id="form" method="post" >
        <h1>Add Detail</h1>
        <label for="">Name</label>
        <input type="text" placeholder="First Name" name="fname" id="fname">

        <label for="">Last Name</label>
                <input type="text" placeholder="Last Name" name="lname" id="lname">

                <label for="">Email</label>
        <input type="text" placeholder="Email" name="eml" id="eml">

        <label for="">Phone No</label>
                <input type="text" placeholder="Phone" name="phn" id="phn">

                <label for="">Address</label>
        <textarea name="adr" id="adr" cols="30" rows="10" id="adr"></textarea>

        <input type="submit" value="SignUp" name="btnsave" id="btnsave">


    </form>
<?php

}
add_action('wp_ajax_Adduser', 'Adduser');
add_action( 'wp_ajax_nopriv_Adduser', 'Adduser' );

Js code

jQuery('.form').on('submit', function (e) {
            var ajaxurl = "/genwp/wp-admin/admin-ajax.php";
            e.preventDefault();
            var fname = jQuery('#fname').val();
            var lname = jQuery('#lname').val();
            var eml = jQuery('#eml').val();
            var phn = jQuery('#phn').val();
            var adr = jQuery('#adr').val();
            console.log(fname);
            console.log(lname);
            console.log(eml);
            console.log(phn);
            console.log(adr);

            jQuery.ajax({
              type: 'post',
              url: ajaxurl, 
              data: {
                        action : 'Adduser', // wp_ajax_*, wp_ajax_nopriv_*
                        'fname': fname,
                        'lname': lname,
                        'eml': eml,
                        'phn': phn,
                        'adr': adr,   
                    },
              success: function () {
                alert('form was submitted');
              } 
            });

          });



    });

so please help me, i am new to wordpress ajax, and can't solve this problem

1
  • 1
    what's ajex that you are talking about? Commented Aug 30, 2019 at 6:00

2 Answers 2

1

You wrote the wrong Insert query.

Replace this:

$qry="insert user_data values(null,'$fname','$lname','$email','$phn','$adr')";

with this

$qry="insert into user_data values('$fname','$lname','$email','$phn','$adr')";

or just insert with wordpress standard:

$wpdb->insert( 
'user_data', 
array( 
    'column1' => 'value1', 
    'column2' => 123 
)
);
-----------------

EDIT: Here is the right way to do this

Form:

<form action="" class="form" id="form" method="post" >
    <h1>Add Detail</h1>
    <label for="">Name</label>
    <input type="text" placeholder="First Name" name="fname" id="fname">

    <label for="">Last Name</label>
            <input type="text" placeholder="Last Name" name="lname" id="lname">

            <label for="">Email</label>
    <input type="text" placeholder="Email" name="eml" id="eml">

    <label for="">Phone No</label>
            <input type="text" placeholder="Phone" name="phn" id="phn">

            <label for="">Address</label>
    <textarea name="adr" id="adr" cols="30" rows="10" id="adr"></textarea>

    <input type="submit" value="SignUp" name="btnsave" id="btnsave">


</form>

update your jquery function:

<script>
jQuery('form#form').on('submit', function(e){
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
var eml = jQuery('#eml').val();
var phn = jQuery('#phn').val();
var adr = jQuery('#adr').val();
// calling ajax
$.ajax({
    type: 'POST',
    dataType: 'json',
    url: "<?php echo admin_url('admin-ajax.php'); ?>", 
    data: { 
        'action' : 'add_new_user',
        'fname': fname,
        'lname': lname,
        'eml': eml,
        'phn': phn,
        'adr': adr,  
    },
    success: function(data){
        if (data.res == true){
            alert(data.message);    // success message
        }else{
            alert(data.message);    // fail
        }
    }
});
});
</script>

Put this code into functions.php

add_action( 'wp_ajax_nopriv_add_new_user', 'add_new_user' );
add_action( 'wp_ajax_add_new_user', 'add_new_user' );
function add_new_user(){
global $wpdb;

$fname = sanitize_text_field($_POST["fname"]);
$lname = sanitize_text_field($_POST["lname"]);
$email = sanitize_text_field($_POST["eml"]);
$phn = intval($_POST["phn"]);
$adr = sanitize_text_field($_POST["adr"]);

$tableName = 'user_data';
$insert_row = $wpdb->insert( 
                $tableName, 
                array( 
                    'fname' => $fname, 
                    'lname' => $lname, 
                    'email' => $email, 
                    'phone' => $phn,
                    'address' => $adr, 
                )
            );
// if row inserted in table
if($insert_row){
    echo json_encode(array('res'=>true, 'message'=>__('New row has been inserted.')));
}else{
    echo json_encode(array('res'=>false, 'message'=>__('Something went wrong. Please try again later.')));
}
wp_die();
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks working fine, also my btnsave was not set, that's why form was not submitting.
Glad! it helps you. Just see my updated answer. That is the right way to using ajax.
0

You need to append the html on the page, to do that you need to use the success function of your ajax call, the function has as a param the result of the ajax call in this case named html, i use append to add the response to the page body tag

success: function(html) {
   $('body').append(html);//change the selector to your desired element
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.