Asked  1 Year ago    Answers:  5   Viewed   11 times

I want to check email availability but it's not working. and also I am new to javascript and ajax please help me.

his is my code email input with span to show output(for now there is no output)

<input class="input--style-4" id="email" type="email" name="email" required>
<span id="user-availability-status"></span>

JS

<script>
  $(document).ready(function() {
    $('#email').blur(function() {
      var email = $(this).val();

      $.ajax({
        url: 'includesemailAvailability.php',
        method: "POST",
        data: {
          email_val: email
        },
        success: function(data) {
          if (data != 0) {
            $('#user-availability-status').html('<span>Username blah not available</span>');
            $('#register').attr("disabled", true);
          } else {
            $('#user-availability-status').html('<span>Username blah Available</span>');
            $('#register').attr("disabled", false);
          }
        }
      })
    });
  });
</script>

PHP file


<?php

if (isset($_POST["email_val"])) {
    include("DbConn.php");
    $email = mysqli_real_escape_string($conn, $_POST["email_val"]);
    $query = "SELECT * FROM customer WHERE email = '" . $email . "'";
    $result = mysqli_query($conn, $query);
    echo mysqli_num_rows($result);
}

 Answers

4

You should check link I refered in comment its your complete answer.

here is a Simple example with your code.

include("DbConn.php");
    // Set alerts as array 
$error     = "";

    // I should just trrim and let you check if email is empty .lol 
if (empty($_POST["email_val"])) {
    $error .= "<p class='error'>Fill email value.</p>";

    //Check if this is a real email 
} elseif(!filter_var($_POST["email_val"],FILTER_VALIDATE_EMAIL)){
    $error .= "<p class='error'>Wrong email type.</p>";
}else{
    $email = mysqli_real_escape_string($conn, $_POST["email_val"]);

    //You should use prepare statement $email, Shame on you .lol    
    $query = "SELECT * FROM customer WHERE email = '{$email}'");
    $result = mysqli_query($conn, $query);
    echo mysqli_num_rows($result);
    $error .= "ok";
}
$data = array(
 'error'  => $error
);

This Jquery :

 $(document).ready(function(){
    $('#myform').submit(function(event){
    event.preventDefault();
    var formValues = $(this).serialize();
        $.ajax({
        url:"includesemailAvailability.php",
        method:"POST",
        data:formValues,
        dataType:"JSON",
            success:function(data){
                if(data.error === 'ok'){
                    $('#result').html(data.error);
                } else {
                    $('#result').html(data.error);
                    $('#myform')[0].reset();
                }
            }
        });
    });
});

And Html :

<form id="myform">
  <input class="input--style-4" id="email" type="email" name="email_val">
  <span id="result"></span>
  <button type="button" class="btn btn-primary">Send</button>
</form>
Thursday, April 1, 2021
 
Besnik
 
1

To get the id attribute of the first accommodation node, use;

$xml->accommodation['id']

To get the items attribute of the information node use;

$xml['items']

For example;

<?php

$str = '
  <information items="192">
    <accommodation id="30"/>
    <accommodation id="50"/>
    <accommodation id="80"/>
  </information>
';

$xml = simplexml_load_string($str);

$a = $xml->accommodation['id'];
$b = $xml['items'];

echo "$a, $b";    // Output: 30, 192

?>

The -> means children of and can be chained eg; $xml->foo->bar['id'].

Hope that helps.

Friday, May 28, 2021
 
2

Put this between <HEAD> and </HEAD> put this:

<script src="jquery-2.0.2.js"></script>
<script>
$.customPOST = function(data,callback){
  $.post('search.php',data,callback,'json');
}

$(document).ready(function() {
    $(".search").keyup(function(){
        $.customPOST({search: $.('#searchid').val(),function(response){
         if(response.success){
          var html_code  = '<div class="show" style="text-align:left;">';
              html_code += '<span class="name">' + response.final_username + '</span>';
              html_code += '&nbsp;<br/>' + response.final_email + '<br/></div>';
          $("#result").text(html_code);
          $("#result").show();
         }
    });

});
</script>

You PHP script must return a JSON response like this way :

<?php
... your code here and ....

$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);

// here we create and return our JSON response
$response = array('final_username' => $final_username, 'final_email' => $final_email);
echo json_encode($response);

?>
Saturday, May 29, 2021
 
LOKESH
 
5

Finally after getting help by thaikolja, here I am sharing the working complete example of my question in easy steps. This answer is also considered as a full basic Ajax Plugin Example. I now personally recommend keeping every file separate for better, clean and comfortable coding...

Main Plugin File:

<?php
/*
Plugin Name: WP Testing Plugin
Plugin URI: http://www.wordpress.org/WP-Testing-Plugin
Description: A Detailed Description About This Plugin.
Author: Muhammad Hassan
Version: 0.1
Author URI: http://www.wordpress.org
*/

// Calling All PHP File To Load
include('my_functions.php');

/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
    echo '
        <form id="searchForm">
            <input name="WhatToSearch" type="text" />
            <input type="submit" value="Search"/>
            <input type="reset" value="Reset"/>
            <div id="showReturnData"></div>
        </form>
    ';
}
/*__________________________________________________________________*/

/*____________WP Testing Plugin Option_____________*/
//Adding "WP Testing Plugin" Menu To WordPress -> Tools
function wp_testingPlugin() {
    //  add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function);                  Menu Under Tools
    add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", 'activate_plugins', "WP-Testing-Plugin", "wp_testingPlugin_admin");
}
add_action('admin_menu', 'wp_testingPlugin');
/*__________________________________________________________________*/
?>

my_functions.php

<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
      wp_enqueue_script( 'ajax-script', plugin_dir_url( __FILE__ ).'my_javascript.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
/****************************************************************************/
// Run Search Function
/****************************************************************************/
/* Register This Function When This File Is Loaded To Call By WordPress AJAX */
add_action('wp_ajax_nopriv_SearchFunction', 'ajaxSearchFunction'); // For Web Visitors
add_action('wp_ajax_SearchFunction', 'ajaxSearchFunction'); // For Admin User
function ajaxSearchFunction(){
    if($_POST['WhatToSearch'] == ""){
        $WhatToSearch = "Nothing";
    } else {
        $WhatToSearch = $_POST['WhatToSearch'];
    }
    echo "<div class='success'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}
?>

my_javascript.js

jQuery(document).ready(function() {
jQuery('#searchForm').on("submit",function(e) {
var incomingData = jQuery('#searchForm').serializeArray();
incomingData.push({name: 'action', value: 'SearchFunction'});
alert(JSON.stringify(incomingData));
jQuery.ajax({
type: 'post',
url: my_ajax_object.ajax_url,
data: incomingData,
success: function(response) {
jQuery('#showReturnData').html(response);
},
error: function(response) {
jQuery('#showReturnData').html('<div">Error</div>');
},
});
return false; // For Not To Reload Page
});
});

Thanks for reading this. If you like this basic example then Vote up the question and answer to help others too.

Saturday, May 29, 2021
 
davidb
 
1

try this

 echo "TRY CONNECTION";
 $conn =new mysqli($servername, $username, $password,$database);
 echo "EXECUTED CONNECTION";

or may be this

$con = mysqli_connect("localhost","my_user","my_password","my_db");
Saturday, May 29, 2021
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :