Select value into the textbox FROM ajax using php - javascript

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);
}
});
});
});​

Related

How to add php form validation with ajax error handling

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
}
});
});

Ajax not returning results

Alright so I have this code which basically finds the user inside the table users and displays it in alert, but it seems that I am doing something wrong. The log shows "Function is not set" and the alert itself displays that.
This is the HTML form I have for it
<center><form method='POST' >
<input id="search_fix" type="text" name="search" placeholder="Search..">
<input type="submit" name="submit_menu_search" style="display: none;">
</form></center>
This is the ajax processing
$(document).ready(function() {
$("#search_fix").keyup(function() {
var search_text = $(this).val();
if(search_text != '') {
$.ajax({
url:"handler.php",
method:"POST",
data:{"function":"search_ajax", search:search_text},
dataType:"text",
success:function(data){
$('#search_result').html(data);
console.log(data);
alert(data);
}
});
}
else {
}
});
});
And these are my PHP functions that I used to basically search for the term
public function search_ajax($term) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($term);
$result = $sql->query("SELECT ime FROM users WHERE ime LIKE '%".$term."%'") or die (mysql_error());
if($result->num_rows >= 1){
while($row = $result->fetch_assoc()) {
echo $row['ime'];
}
}
}
if(isset($_POST['function'])) {
switch($_POST['function']) {
case "search_ajax": {
require_once "assembly/user.php";
$user = new User();
$user->search_ajax($_POST['search']);
break;
}
default: {
echo "Unknown AJAX function handler";
break;
}
}
}
else {
echo "Function is not set";
}
It sounds like you're using a version of jQuery before 1.9.0. The method: option didn't exist in the older versions, it was called type:. That's why you're seeing the parameters appended to the URL, because type: "GET" is the default.
So change
method: "POST",
to:
type: "POST",
try this:
$.ajax({
url:"handler.php",
method:"POST",
data:'{"function":"search_ajax", search:search_text}',
dataType:"text"
})
.done(function(data){
$('#search_result').val(data);
console.log(data);
alert(data);
} ) ;

API Validation Before Proceeding

I'm working with Instagram's api, and I must validate a profile before form is submitted:
<button type="button" id="clickMe">Run It!</button>
<div id="data">
</div>
<script type="text/javascript">
$('#clickMe').click(function() {
$.ajax({
method: 'get',
url: 'php-script.php',
data: {
'username': '217380759',
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
</script>
php-script.php:
$access_token = "...";
$username = "...";
$url = 'https://api.instagram.com/v1/users/' . $username . '?access_token=' . $access_token;
$api_response = file_get_contents($url);
$record = json_decode($api_response);
$code = $record->meta->code;
if($code == 200) {
//user is valid, continue to next page
} else {
echo "invalid";
}
Any suggestions on verifying Instagram user, allowing user to continue without hitting submit again?
Just try this code :
success: function(data) {
if(data != 'invalid') {
location.href = "YOUR NEXT PAGE URL";
}
}

simple ajax call to database to verify email php codeigniter

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>

Ajax login issues

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.

Categories

Resources