On blur of an e-mail textbox, I want it to do an ajax call back and verify if the e-mail is already in use.
The call is finding the webmethod, however, it's returning a null value. I trimmed the code and I'm getting a null value with the following:
function chkEmail(email) {
var prom = $.Deferred();
console.log(email);
$('#emailCheckGIF').show();
$('input[type="submit"]').prop('disabled', true);
$.ajax({
url: 'emailAvailable',
data: { 'email': email },
success: function (data) {
console.log(data + ' good');
prom.resolve(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown + ' error');
prom.reject(errorThrown);
}
});
return prom;
}
My simplified web method
public function emailAvailable($email = null) {
echo json_encode($email);
}
In the firefox dev tools, it says the email param is being passed correctly and the response from the service is NULL
If I remove the json_encode it comes over as a blank string.
Please Try This --
My Controller --
public function checkEmail()
{
$email = $_POST['email'];
$result = $this->federation_model->checkEmail($email);
echo json_encode($result);
}
My Model --
public function checkEmail($email)
{
$this->db->where('user_email', $email);
$result=$this->db->get('users')->row_array();
if(is_array($result))
{
return $result;
}
else
{
return false;
}
}
My View --
<div class="col-md-4">
<input name="assoc_email" id="assoc_email" type="email" class="form-control"/>
<span id="line2" class="text-left"></span>
</div>
My Script --
<script type="text/javascript">
$(document).ready(function(){
$('#assoc_email').keyup(function(){
var email = $('#assoc_email').val();
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// my ajax function will call after enter the valid email
if(email == "" || !filter.test(email))
{
$('#line2').html("");
$('#submit_assoc').attr('disabled', false);
}
if(filter.test(email) && email != "")
{
$.ajax({
url:"<?php echo base_url(); ?>federation/checkEmail",
type:"post",
data:"email="+email,
success: function(data){
var result = JSON.parse(data);
if(result == "")
{
$('#line2').html("<?php echo $this->lang->line('email'); ?> <?php echo $this->lang->line('available'); ?> ");
$('#line2').css('color', 'green');
}
else
{
$('#line2').html("<?php echo $this->lang->line('email'); ?> <?php echo $this->lang->line('already'); ?> <?php echo $this->lang->line('exists'); ?>");
$('#line2').css('color', '#f3565d');
}
}
});
}
});
});
</script>
Related
I am trying to check if value exist in database in my CodeIgniter website using AJAAX. I have written the following code:
<input id="username" name="pincode" type="text" class="form-control" placeholder="Enter Pincode">
<input id="prodid" name="prodid" value="<?php echo $prodid;?>" type="hidden">
<button type="button" onclick="check_if_exists();" class="btn btn-primary">Check</button>
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {
username: username,
prodid: prodid
},
success: function(response) {
if (response == true) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
function filename_exists()
{
$username = $this->input->post('pincode');
$prodid = $this->input->post('prodid');
$exists = $this->product->filename_exists($prodid);
if ($exists) {
return true;
} else {
return false;
}
}
function filename_exists($prodid)
{
$this->db->select('*');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
I am only getting the message that the value doesn't exist even if the value is there in database.
You are using AJAX not the form submission method, so in back-end post() method won't work
To transfer a value from server in php, one method is echo, but return is wrong here.
Please rewrite your code like this
View
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
var transfer = [username,prodid];
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {result: JSON.stringify(transfer)},
success: function(response) {
if (response) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
Controller
function filename_exists()
{
$post = json_decode($_POST['result']);
$username = $post[0];
$prodid = $post[1];
$exists = $this->product->filename_exists($prodid);
echo $exists;
}
Modal
function filename_exists($prodid)
{
$this->db->select('id');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
if($query->num_rows()) return true;
}
enter code here
I'm trying to establish a simple connection between Javascript and my database using ajax and PHP. Javascript is supposed to receive a name from an HTML form, modify it and post it to PHP to check whether the name is already in the database and return true/ false back to javascript for further use.
Everything works fine as long as I don't add the part of code that connects to the database. Calling only the PHP file in Chrome also works and it will correctly print true or false.
As soon as I connect both together, nothing works. Neither success nor error will execute any of the code inside their functions.
JS1 + PHP1: Nothing happens
JS1 + PHP2: Correctly shows result in Alert1 and Alert2
PHP1 alone: Correctly prints either true or false
JS1
var boo = false;
if(str.length > 1) boo = true;
if (boo)
$.ajax ({
url: 's5Check.php',
type: 'post',
data: { str : str },
success: function( result ) {
alert(result); //Alert1
if(result != false){
boo = false;
alert(str + " already exists!"); //Alert2
} else {
boo = true;
alert(str + " doesn't exist!"); //Alert3
}
},
error: function( e ) {
alert("Error: " + e); //Alert4
}
});
PHP1
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$temp = mysqli_real_escape_string($con, $_POST['str']);
$check = "SELECT id FROM handle WHERE name = '$temp'";
$result = $con -> query($check);
if($result->num_rows > 0) {
echo true;
} else{
echo false;
}
} else{
echo "error";
}
?>
PHP2
<?php
echo $_POST['str'];
?>
Thanks.
echo true will output 1. echo false will output nothing. You're not checking for either of these in your success function.
Using JSON is a simple solution to this, and allows for easy enhancement to more complex results.
JS:
$.ajax({
url: 's5Check.php',
type: 'post',
data: {
str: str
},
dataType: 'json',
success: function(result) {
alert(result); //Alert1
if (result === false) {
boo = false;
alert(str + " already exists!"); //Alert2
} else if (result === true) {
boo = true;
alert(str + " doesn't exist!"); //Alert3
} else if (result === "error") {
alert("Error");
} else {
alert("Unknown problem");
}
},
error: function(jqXHR, txtStatus, e) {
alert("Error: " + e); //Alert4
}
});
PHP:
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$check = "SELECT id FROM handle WHERE name = ?";
$stmt = $con->prepare($check);
$stmt->bind_param("s", $_POST['str']);
$result = $stmt->execute();
$response = $result->num_rows > 0;
} else{
$response = "error";
}
echo json_encode($response);
?>
How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});
I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});
When submitting my form I need to check in the database whether chassis and pin exists. If it exists i need to display a pop up message through Ajax. This is my code. But i am not getting any pop up message if the data has been inserted or if there is any error.Can you guys help me figure out where I am going wrong? Thanks in advance for your help.
AJAX CODE :
<script type="text/javascript">
$(document).ready(function () {
$("#user_submit_form").submit(function () {
var user_data = $("#user_submit_form").serialize();
if ($('#chassis').val() == '') {
alert('Please enter chassis');
} else if ($('#pin').val() == '') {
alert('Please enter pin');
} else
{
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function (user_data) {
if (user_data == "Data inserted") {
alert("Data inserted");
} else {
alert("fail!");
}
}
}); // End ajax method
}
});
});
</script>
PHP CODE:
<?php
session_start();
$hostname = '*****';
$database = '****';
$username = '****';
$password = '*****';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT chassis,pin FROM checking_chassis WHERE chassis="'.$chassis.'" && pin="'.$pin.'" ');
if(mysql_num_rows($sql) == 1)
{
echo "Data inserted";
}
else
{
echo "Error";
}
?>
first do this after submitting and check
$("#user_submit_form").submit(function(e){
e.preventDefault();
});
and when alerting return false;
OR
pass data like this
$data = array(
'status' => 1,
'message' => 'Data inserted'
);
echo json_encode($data);
and in success function use
var json = $.parseJSON(user_data);
alert(json.message);
I am trying this now but I don't think that the value is getting returned. It is just printing the content of the else statement
<script type="text/javascript">
$(document).ready(function (){
$("#user_submit_form").submit(function(){
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
var pincode = new Array();
pincode = $('#pincode').val().split("");
if($('#chassis').val() =='')
{
alert('Please enter chassis');
}
else if($('#pin').val() =='')
{
alert('Please enter pin');
}
else
{
$.post("validate_user.php",{"chassis":$('#chassis').val(),"pin":$('#pin').val(),"title":$('#title').val(),"fname":$('#fname').val(),"lname":$('#lname').val(),"email":$('#email').val(),"mobile":$('#mobile').val(),"dob":$('#dob').val(),"anniversary":$('#anniversary').val(),"company":$('#company').val(),"designation":$('#designation').val(),"home_business":$('#style').val(),"add1":$('#add1').val(),"add2":$('#add2').val(),"city":$('#city').val(),"state":$('#state').val(),"pincode":$('#pincode').val()},function(data) {
if(data == true)
{
alert("Error");
}
else
{
alert("Success");
}
});
}
});
});
</script>