0

I am new with ajax. I have this php function already from functions.php

function checkUserEmailExistent($email){
   ...
   return $boolean;
}

and this is for my views views.html

<input type='text' name='email' id='email'>

this is for the script.js

jQuery( "#email" ).blur(function() {
        jQuery.ajax({
            type: 'POST',
            url: 'url',
            dataType: 'json',
            data: { 'value' : $(this).val() },
            success : function(result){

            }
        });
    });

my issue is how can I call my php function in ajax to connect it to my html. when it blur it check the email value if it is exist or not.

4
  • just create a new php file which will receive your json data from POST array, call you method providing its received value and return a result. Commented Apr 7, 2015 at 6:42
  • Within your ajax function url : path_to_controller/checkUserEmailExistent Commented Apr 7, 2015 at 6:42
  • check this example it will help you beski.wordpress.com/2009/05/16/… Commented Apr 7, 2015 at 6:43
  • Put your entire javascript in $(document).ready(function(){"Your code here"}) Commented Apr 7, 2015 at 6:44

5 Answers 5

1

work in WordPress

JS SCRIPT

jQuery( "#email" ).blur(function() {
    jQuery.ajax(
                    {
                        url: ajax_url,
                        type: "POST",
                        dataType: "json",
                        data: {
                            action: 'checkUserEmailExistent',
                            email: $(this).val(),
                        },
                        async: false,
                        success: function (data)
                        {
                            if (data.validation == 'true')
                                jQuery('.email-massage').html('<div class="alert alert-success"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Success!</strong>  successfully</div>');
                            else
                                jQuery('.email-massage').html('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Oops!</strong> Something went wrong.</div>');

                        },
                        error: function (jqXHR, textStatus, errorThrown)
                        {
                            jQuery('.email-massage').html('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>Oops!</strong> Something went wrong.</div>');
                        }
                    });
});

WP SCRIPT in functions.php

    add_action('wp_ajax_checkUserEmailExistent', 'checkUserEmailExistent');
        add_action('wp_ajax_nopriv_checkUserEmailExistent', 'checkUserEmailExistent');

        function checkUserEmailExistent() {
        $email = $_POST['email']; // get email val
        /*if() your condition
$email = 1;
else
$email = 0;
*/

    if ($email == 1):
                $email_val= 'true';
            else:
                $email_val = 'false';
            endif;
            echo json_encode(array("validation" => $email_val));
            die;
    }

in function.php Enqueue file after add this code like this

wp_enqueue_script('themeslug-default', get_template_directory_uri() . '/js/default.js', array('jquery'));
wp_localize_script('themeslug-default', 'ajax_url', admin_url('admin-ajax.php'));
Sign up to request clarification or add additional context in comments.

5 Comments

what shoul be the value of ajax_url then?
what is the 'admin-ajax.php' ?
now I get it.. but I always get an error on ajax, it always return to false. so I tried to alert(data + ' | '+ data.validation); inside the script.. and I got 0 | undifined? please help me.. thanks in advancs
I also put wp_die() at the end of my php function but still I got 0 on the ajax data
you give me live URL so i will check it.
0

Set url to the php file where you have checkUserEmailExistent function. Then:

function checkUserEmailExistent($email){
   ...
   return $boolean;
}
 return checkUserEmailExistent($_REQUEST['value']);

Comments

0

I give the example for validation.This will help you to check

Email id<input type="text" name="email" id="email" size=18 maxlength=50  onblur="javascript:myFunction(this.value)">

You need to add the script

  <script>
   function myFunction(em) {
if(em!='')
{   

  var x = document.getElementById("email").value;

   var atpos = x.indexOf("@");
  var dotpos = x.lastIndexOf(".");
  if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
    alert("Not a valid e-mail address");
   document.getElementById("email").value = "";
  return false;
  exit();
  }   
           var email=$("#email").val();

  $.ajax({
type:'post',
    url:'email_client.php',
    data:{email: email},
    success:function(msg){
 if (msg.length> 0) {
alert(msg);
document.getElementById("email").value = "";
 }
 }
        });


     }          }
               </script>

Create a page 'email_client.php' and add the code

 <?php
  $s=$_POST['email'];
  include "config.php";
$echeck="select email from client where active=0 and       email='".$_POST['email']."'";  //change your query as you needed
  $echk=mysql_query($echeck);
  $ecount=mysql_num_rows($echk);

   if($ecount>='1' && $s!='0')
    {
   echo "Email already exists";
   }

?>

Comments

0

You would call it in your url parameter. However, you'll need to manage your AJAX handler in the PHP script.

AJAX

jQuery( "#email" ).blur(function() {
    jQuery.ajax({
        type: 'POST',
        url: 'functions.php',
        dataType: 'json',
        data: { 'value' : $(this).val() },
        success : function(result){
            if (result.success) {
                //handle success//
            } else if (result.failure) {
                //handle failure//
            }
        }
    });
});

PHP

function checkUserEmailExistent($email){
   ...
   return $boolean;
}

if ($_POST['value']) {
    $status = checkUserEmailExistent($email);
    if ($status === true) {
        echo json_encode (array('status' => 'success'));
    } elseif ($status === false) {
        echo json_encode (array('status' => 'failure'));
    }
}

Comments

0

you don't call your server function inside Ajax you only send your data in JSON format to the server on getting this data,server will route(if MVC) it to specific function and return a response to client in JSON format so now inside Ajax you perform operation on success (what to do next ) and in case of failure show the error

How server will route it to specific function that depend on framework you use, but i think they simply use regexp to match with URL

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.