I’m new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma">
a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information…
When i try to print in my website the required information using $('#forma').html(data);
I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
Check below code for how it is done regarding your context.
In functions.php
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
To call it:
Source: https://codex.wordpress.org/AJAX_in_Plugins