简体   繁体   中英

ajax success returning 0

I need a small help. I have designed my custom ajax function. It is a simple form which inputs 5 values validates them and then sends data through ajax to a php function and the function emails those details. Upon success a popup is shown to the user of confirmation.

I have applied the validation and i am also able to run ajax. But for some reason my success function keeps on returning 0. Please help.

Dev tools output on submit chrome: http://imgur.com/m5Ah0md

Network output on submit on chrome: http://imgur.com/R7q9WnH

My javascript

function contact_validations(){
event.preventDefault();
var name= jQuery('#contactname').val();
var cemail= jQuery('#contactemail').val();
var tel= jQuery('#contactphone').val();
var address= jQuery('#contactaddress').val();
var message= jQuery('#contactsubject').val();
var s=true;

if(name==''|| name==null ){
    jQuery('#name_err').html('Please enter your name');
    s=false;
    }else{  
        jQuery('#name_err').html('');
        }

if(cemail==''){
    jQuery('#email_err').html('Please enter email');
    s=false;
    }else{ 
        var x=cemail;
        var atpos=x.indexOf("@");
        var dotpos=x.lastIndexOf(".");
        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
            { jQuery('#email_err').html("Please Enter  Valid E-mail Address"); s= false;} 
            else{
                jQuery('#email_err').html('');
                }
        }   


if(tel==''|| tel==null ){
    jQuery('#tel_err').html('Please enter your telephone number');
    s=false;
    }else{  
        jQuery('#tel_err').html('');
        }



if(address=='' || address==null){
    jQuery('#address_err').html('Please enter your address');
    s=false;
    }else{  
        jQuery('#address_err').html('');
        }


if(message=='' || message==null){
    jQuery('#message_err').html('Please enter your message');
    s=false;
    }else{  
        jQuery('#message_err').html('');
        }
        console.log( url );


if(s)
        {
            var url = "http://localhost:9080/c/wp-admin/admin-ajax.php";
            var data = {

                "action":"contact_email" ,
                "name": name ,
                "email": cemail ,
                "tel": tel ,
                "address": address ,
                "message": message 


            }
            jQuery.ajax({
            type: "POST",
            url: url,   
            contentType: 'JSON',
            data: JSON.stringify(data),
            beforeSend: function(){
                console.log('happened');
                jQuery('#ajax-loader').show();
                jQuery('#ajax-loader').html('<img src="http://localhost:9080/c/wp-content/themes/aussie/images/ajax-loader.gif">');
                },
            success: function(result) {
                jQuery('#ajax-loader').hide();
                console.log(result);


                if(result=='0')
                {
                    console.log("No Result")
                }
                if(result=='1')
                {   
                jQuery.fancybox({
                    href: '#contact-popup'
                });
                jQuery('#contactname').val('');
                jQuery('#contactemail').val('');
                jQuery('#contactphone').val('');
                jQuery('#contactaddress').val('');
                jQuery('#contactsubject').val('');

                console.log ( s );
              } 
            }
        });


        }
}

My Javascript:

function contact_email() {



            $url = get_bloginfo('url');
            $storeemail = get_option('contactemailstored'); 
            $to = $storeemail['contactemail'];
            $subject = $url . ' - Contact';
            $name = $_POST['contactname'];
            $email = $_POST['contactemail'];
            $phone = $_POST['contactphone'];
            $address= $_POST['contactaddress'];
            $content= $_POST['contactsubject'];                                         
            $message = '<br>'.'Name:- ' .  $name . '<br>';
            $message  .= 'Email- ' . $email . '<br>';
            $message  .= 'Phone:- ' . $phone . '<br>';
            $message  .= 'Address  :' . $address  . '<br>';
            $message  .= 'Subject  :' . $content  . '<br>';


            $sent_message = wp_mail( $to , $subject, $message ); 

        if ( $sent_message ) {
            // the message was sent...
            echo '1';
        } else {
            // the message was not sent...
            echo '1';
        }

         exit;


    }
add_action('wp_ajax_contact_email', 'contact_email');

add_action('wp_ajax_nopriv_contact_email', 'contact_email');

The issue is you are converting data to json but wp expects a field called action to find the correct function, hence your return value is 0 (function is not found, no exit encountered so 0 returned).

In this instance you actually do not need json values send the form, but it will expect a json response so in your php function you should json_encode your return value.

jQuery(document).ready(function(){  

        var url = "<?php echo admin_url('admin-ajax.php'); ?>";
        var data = {

            "action": contact_email ,
            "name": name ,
            "email": cemail ,
            "tel": tel ,
            "address": address ,
            "message": message 
        }

        jQuery.ajax({
            type: "POST",
            url: url,   
            contentType: 'JSON',
            //JSON.stringify(data), -->will cause issue
            data: data,
            beforeSend: function(){
                console.log('happened');
            },
            success: function(result) {
                console.log(result);
            }
        });        
});

PHP

function contact_email() {

            // the message was sent...
      echo  json_encode(1); // if just sending 1, you can echo without json encode...
       exit;

}
add_action('wp_ajax_contact_email', 'contact_email');

add_action('wp_ajax_nopriv_contact_email', 'contact_email');

Sending Json...

If you wish you can convert the other form values to json and include in its own object key. eg

var data={};
data.action= 'hook';
data= JSON.stringify(formData);

And so on.

Thankyou very much everyone for helping. I got a lot of help. Although i have found the problem. The problem was that for wordpress i didn't need to parse data in JSON. So i used the normal type and it worked.

Also i had a syntax error on my function contact_email.. I used

$name = $_POST['contactname'];
$email = $_POST['contactemail'];
$phone = $_POST['contactphone'];
$address= $_POST['contactaddress'];
$content= $_POST['contactsubject'];   

I was capturing form data with it's original instead it should be captured by the val that has been declared in AJAX. Instead i used this and it worked:

$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['tel'];
$address= $_POST['address'];
$content= $_POST['message'];

Here's the updated code:

Jquery:

function contact_validations(){
var name= jQuery('#contactname').val();
var cemail= jQuery('#contactemail').val();
var tel= jQuery('#contactphone').val();
var address= jQuery('#contactaddress').val();
var message= jQuery('#contactsubject').val();
var s=true;

if(name==''|| name==null ){
    jQuery('#name_err').html('Please enter your name');
    s=false;
    }else{  
        jQuery('#name_err').html('');
        }

if(cemail==''){
    jQuery('#email_err').html('Please enter email');
    s=false;
    }else{ 
        var x=cemail;
        var atpos=x.indexOf("@");
        var dotpos=x.lastIndexOf(".");
        if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
            { jQuery('#email_err').html("Please Enter  Valid E-mail Address"); s= false;} 
            else{
                jQuery('#email_err').html('');
                }
        }   


if(tel==''|| tel==null ){
    jQuery('#tel_err').html('Please enter your telephone number');
    s=false;
    }else{  
        jQuery('#tel_err').html('');
        }



if(address=='' || address==null){
    jQuery('#address_err').html('Please enter your address');
    s=false;
    }else{  
        jQuery('#address_err').html('');
        }


if(message=='' || message==null){
    jQuery('#message_err').html('Please enter your message');
    s=false;
    }else{  
        jQuery('#message_err').html('');
        }


if(s)
        {
            var url = "http://localhost:9080/c/wp-admin/admin-ajax.php";

            jQuery.ajax({
            type: "POST",
            url: url,   


            data:"action=contact_email&name="+name+"&email="+cemail+"&tel="+tel+"&address="+address+"&message="+message,
            beforeSend: function(){
                console.log('happened');
                jQuery('#ajax-loader').show();
                jQuery('#ajax-loader').html('<img src="http://localhost:9080/c/wp-content/themes/aussie/images/ajax-loader.gif">');
                },
            success: function(result) {
                jQuery('#ajax-loader').hide();
                console.log(result);


                if(result=='0')
                {
                    console.log("No Result")
                }
                if(result=='1')
                {   
                jQuery.fancybox({
                    href: '#contact-popup'
                });
                jQuery('#contactname').val('');
                jQuery('#contactemail').val('');
                jQuery('#contactphone').val('');
                jQuery('#contactaddress').val('');
                jQuery('#contactsubject').val('');

                console.log ( s );
              } 
            }
        });


        }

}

PHP

function contact_email() {



            $url = get_bloginfo('url');
            $storeemail = get_option('contactemailstored'); 
            $to = $storeemail['contactemail'];
            $subject = $url . ' - Contact';
            $name = $_POST['name'];
            $email = $_POST['email'];
            $phone = $_POST['tel'];
            $address= $_POST['address'];
            $content= $_POST['message'];                                            
            $message = '<br>'.'Name:- ' .  $name . '<br>';
            $message  .= 'Email- ' . $email . '<br>';
            $message  .= 'Phone:- ' . $phone . '<br>';
            $message  .= 'Address  :' . $address  . '<br>';
            $message  .= 'Subject  :' . $content  . '<br>';


            $sent_message = wp_mail( $to , $subject, $message ); 

        if ( $sent_message ) {
            // the message was sent...
            echo '1';
        } else {
            // the message was not sent...
            echo '0';
        }

         exit;


    }
add_action('wp_ajax_contact_email', 'contact_email');

add_action('wp_ajax_nopriv_contact_email', 'contact_email');
function contact_email() {

         //your code
         exit();
         die();
}

You need to include these PHP functions exit(); and die(); at the end of the function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM