I am trying to submit the form using AJAX in CodeIgniter. Values of the form are getting saved in DB but the reply that has been set in the controller is not getting displayed in console.log or alert in AJAX code.
Code of form
<form class="form-signup" id="signup-form" method="post">
<input type="email" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="password" id="password">
<button type="submit" class="btn btn-primary btn-lg btn-signup col-sm-offset-1" id="submit_form">SIGN UP</button>
</form>
Script code
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'json',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});
Controller code
public function register()
{
$data = array(
'email' => $this->input->post('email'),
'password'=>$this->input->post('password')
);
$email = $data['email'];
$password = $data['password'];
$this->db->where('email',$email);
$query = $this->db->get('student');
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
return $final;
}
}
Model code
public function register_user($data1)
{
$success=$insert_data = $this->db->insert('student', $data1);
if($success)
{
$result= "success ";
}
else
{
$result= "register unsuccessful";
return $result;
}
}
As shown in the code there are 3 messages
Email already exists
Success
Register unsuccessful
In AJAX, if I do console.log or alert, I want any 1 of the above 3 messages to get displayed according to the flow.
How to display the reply on front end?
You have to use echo instead of return for success.
Please change it as follows
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
echo $final;
}
and remove that 2 variables initialized together. That is unnecessary. This is fine.
$success = $this->db->insert('student', $data1);
Hope this can help you.
The ajax that you have used has datatype as json. So if you want data to be displayed on front end either encode the reply in json or you need to change or remove the json datatype from your ajax
Please change dataType:'json' to dataType: 'text'
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'text',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});
Related
I have a big problem with Ajax-request via Laravel. I can't understand why it is not Ajax. All resources here.
It is my Ajax-request.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var nickname = "<?php echo $name_user; ?>";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.subscribe').click(function() {
jQuery.ajax({
type: 'post',
url: "{{ route('postSubscribe', '<?php echo $name_user; ?>') }}", //Путь к обработчик
data: {'user_name': nickname},
response: 'text',
success: function(data) {
console.log(data['result']);
},
error: alert('Error');
})
})
</script>
It is my web-routes.
Route::group(['middleware' => 'auth'], function() {
Route::get('/', 'AccountController#redirectToAccountPage');
Route::get('/account', 'AccountController#showAccount')->name('account');
Route::get('/account/settings', 'AccountController#showSettings')->name('settings');
Route::post('/account/settings', 'AccountController#sendSetting');
Route::get('/account/subscribe', 'AccountController#showSubscriberForm')->name('subscriber');
Route::post('/account/subscribe', 'AccountController#findUser')->name('postFindUser');
Route::get('/account/load_image', 'AccountController#showLoadImage')->name('load_image');
Route::post('/account/load_image', 'Photos\LoadPhotoController#loadPhoto');
Route::post('/account/logout', 'AccountController#logout')->name('logout');
Route::post('/user/{user_name}/', 'AccountController#subscribe')->name('postSubscribe');
Route::get('/admin', 'AccountController#showAdminPanel');
});
It's my main request.
public function subscribe(Request $request, $name_user) {
if($request->ajax()) {
$query = 'SELECT id FROM subscriptions WHERE id_subscriber = ? AND id_subscribtion = ?';
$queryFindAnother = 'SELECT id From new_users WHERE nickname = ?';
$idAnotherUser = DB::select($queryFindAnother, [$name_user]);
if(!DB::select($query, [Auth::user()->id, $idAnotherUser[0]->id])) {
$query = 'INSERT INTO subscriptions (id_subscriber, id_subscribtion) VALUES (?, ?)';
dd('Я здесь');
//id_subscriber - тот, кто подписался.
//id_subscribtion - на кого подписан.
DB::insert($query, [Auth::user()->id, $idAnotherUser[0]->id]);
return response()->json([
'result' => '1', //всё прошло успешно, я подписан
]);
}
return back();
}
dd("It's not ajax");
return back();
}
As a result I got the message "It's not Ajax". Help me please!
I think the problem is in your form
Please update your form
<form>
{!! csrf_field() !!}
<button class="subscribe" name="user" type="button">Подписаться.</button>
</form>
Here, you don't need any action or method also does not need any form
because you passing the form data as ajax
and add the type of your button as button, by default its a submit type, so its submitting the form as normally.
Make sure you have imported the Request Facade on top
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm using jQuery validation for a registration form in PHP. In my PHP my form is as follow:
<form id="register-form">
<input class="form-control" name="dispName" placeholder="Display name" type="text">
<input class="form-control" name="email" placeholder="Email address" type="email">
<input class="form-control" name="password" id="password" placeholder="Password" type="password">
<input class="form-control" name="password2" placeholder="Re-enter password" type="password">
<input class="btn btn-primary" id="submit-button" type="submit" value="Request Access">
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js"></script>
<script src="request.js"></script>
In my request.js the validation is as follow:
$.validator.addMethod("checkUserName",
function(value, element) {
var result = false;
$.ajax({
type:"POST",
async: false,
url: "check-username.php", // script to validate in server side
data: {dispName: value},
success: function(data) {
result = (data == true) ? true : false;
}
});
// return true if username is exist in database
return result;
},
"This username is already taken! Try another."
);
$("#register-form").validate({
rules: {
dispName: {
required:true,
nowhitespace: true,
lettersonly: true,
checkUserName: true
},
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
},
pw: {
required: true,
strongPassword: true
},
cpw: {
required: true,
equalTo: '#password'
}
},
messages: {
email: {
required: 'Please enter an email address.',
email: 'Please enter a <em>valid</em> email address.',
}
}
});
in my PHP validation server side:
<?php
$searchVal = $_POST['dispName'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$sql = "SELECT * FROM users WHERE dname = " . "'" . $searchVal . "'";
$stmt = $dbh->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result){
echo 'true';
}else {
echo 'false';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I keep getting This username is already taken! Try another. even i use name not in the database. I tested on check-username.php on the server using a dummy "POST" value and it worked fine. So i've got a strong feeling its with the syntax in request.js. Can anyone point me in the right direction.... Thank in advance...
you can do something like this:
$.validator.addMethod("checkUserName",
function(value, element) {
var result = false;
$.ajax({
type:"POST",
async: false,
url: "check-username.php", // script to validate in server side
data: {dispName: value},
success: function(data) {
result = (data == true) ? true : false;
if(result == true){/*here you show error according to your way*/}
}
});
},
);
var typingTimerEmail; //timer identifier
var doneTypingIntervalEmail = 1000; //time in ms, 5 second for example
var $input = $('#email');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimerEmail);
$('#submit').attr("disabled", true);
typingTimerEmail = setTimeout(doneTypingEmail, doneTypingIntervalEmail);
});
function doneTypingEmail () {
//do something
var url = "http://172.16.0.60/bird_eye_api/";
var email_exist = $('#email').val();
if(email_exist.length > 0){
$('.email_exist_msg').hide();
$('#submit').attr("disabled", false);
//$('.check_mail').css('border','1px solid #ff0000');
$.ajax({
url: url + "admin/check",
type: 'POST',
data: {'email':email_exist},
success: function (data) {
console.log(data)
if(data == 'true'){
$('#submit').attr("disabled", true);
$('.email_exist_msg').html('User with this email already exist').show();
} else {
$('#submit').attr("disabled", false);
//$('.check_mail').css('border','');
$('.email_exist_msg').html('User with this email already exist').hide();
}
},
});
}
if(email_exist.length==0){
$('.email_exist_msg').hide();
//$('.check_mail').css('border','')
}
}
You can set your custom URL to that. On Key up of your email field it will fire ajax to your URL and will check if users exists or not. Certainly return true or false. According to that in ajax success it will display message.
modal screenshot
i have a form inside bootstrap modal, i want to validate if the email already exist in database. the result direct to the blank page with this thing '{"valid":false,"msg":"Email is already taken"}'. i want the msg appear just like i figure it in screenshot.
View
<?php echo form_open('KulinerControl/isEmailExist', 'id="myform"'); ?>
<div id="msg"> </div>
<input type="text" name="email" id="email" class="input-lg formcontrol">
<button type="submit">Submit</button>
</form>
JS
$(document).ready(function(){
$('#myform').on('submit', function(e) {
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
dataType: "json",
data: "email="+email,
success: function(data){
if(data.valid){
$('#msg').html(data.msg);
}else{
$('#msg').html(data.msg);
}
}
});
});
});
Controller
function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
$msg = array(
'valid' => false,
'msg' => 'Email is already taken');
}else{
$msg = array(
'valid' => true,
'msg' => 'Username is available');
}
echo json_encode($msg);}
update controller
function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
echo "Email is already taken !";
}else{
$data = array(
'nama' => $this->input->post('nama'),
'email' => $email,
'password' => md5($this->input->post('password'))
);
$query = $this->KulinerModel->addMember($data);
redirect('/KulinerControl/');
}
}
Thanks in advance
you need to stop submitting your form at first then start checking. then if checking find its ok then submit it. i would use the following
$(document).ready(function(){
$('#myform').on('submit', function(e) {
e.preventDefault(); //<---- stop submiting the forms
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
dataType: "json",
data: "email="+email,
success: function(data){
if(data.valid){
$('#msg').html(data.msg);
$("#myform").submit(); //<---- submit the forms
}else{
$('#msg').html(data.msg);
}
}
});
});
});
I think real time email checking is better for your situation
<script>
$(document).ready(function(){
$('#email').keyup(function(){
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
data: "email="+email,
success: function(response){
$('#msg').html(response);
}
});
});
});
</script>
In Your controller
function isEmailExist()
{
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
echo "Email is already taken";
}else{
echo "";
}
}
To prevent submitting an easy trick
$(document).ready(function(){
$('#myform').on('submit', function(e) {
if ($.trim($("#msg").val()) === "") {
alert('please choose a different email id');
return false;
}
});
});
change Your Form action controller to this
function dataInsert()
{
$data = array(
'nama' => $this->input->post('nama'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password'))
);
$query = $this->KulinerModel->addMember($data);
redirect('/KulinerControl/');
}
I'm trying to make a login script that uses ajaxForm and the validate plugin, but if PHP provides an error, it doesn't know. This is my Javascript
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success: function() {
window.location="index.php";
},
error: function(e) {
alert(e);
}
});
});
Keep in mind I'm new to JS and there's probably a better way to do this. What I need is, if when the form is submitted but the username or password is wrong, I need it to not redirect, and give the error alert, but this does not work currently. I've googled this before, and checked here and so far have found nothing.
edit: using the below code, it still doesn't work:
JS
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$("#login").submit(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "/doLogin",
data : $(this).serializeArray(),
success : function(result) {
if(result.result == "success"){
window.location = "/index.php";
}else if(result.result == "failure"){
$("#alert").html("Test");
}
},
error : function() {
$("#failure").show();
$(".btn-load").button('reset');
$("#email").focus();
}
});
});
});
HTML
<div class="shadowbar">
<div id="alert"></div>
<form id="login" method="post" action="/doLogin">
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
PHP
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
header('Location: /index.php');
exit();
} else {
$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
return $error;
echo "{\"result\":\"failure\"}";
}
} else {
$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
}
echo "{\"result\":\"success\"}";
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
In your login script, you will need to return errors in json format.
For Example
In your login script, if your query finds a row in the database for that user, echo this:
echo "{\"result\":\"success\"}";
and if it fails:
echo "{\"result\":\"failure\"}";
You then can parse these in JavaScript like so:
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success: function(result) {
if(result.result == "success"){
window.location = "index.php";
}else if(result.result == "failure"){
alert('Failure!');
}
error: function(e) {
alert(e);
}
}
});
Here's an example of an Ajax script I use to log users into my site, you can use this for reference if needed. This is just to help you get an even broader understanding of what I am talking about:
I return more than just a success and failure for various reasons such as user intuitiveness, but the gist is there.
$("#loginForm").bind("submit", function() {
$("#invalid").hide();
$("#disabled").hide();
$("#error").hide();
$("#failure").hide();
$("#blocked").hide();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if(email != "" && password != ""){
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "/ajax/functions/login",
data : $(this).serializeArray(),
success : function(result) {
if(result.result == "success"){
window.location = "/account";
}else if(result.result == "failure"){
$("#invalid").show();
$(".btn-load").button('reset');
$("#email").focus();
}else if(result.result == "disabled"){
$("#disabled").show();
$(".btn-load").button('reset');
$("#email").focus();
}else if(result.result == "blocked"){
$("#blocked").show();
$(".btn-load").button('reset');
$("#email").focus();
}
},
error : function() {
$("#failure").show();
$(".btn-load").button('reset');
$("#email").focus();
}
});
}else{
$("#error").show();
$(".btn-load").button('reset');
$("#email").focus();
}
return false;
});
this is my controller function
public function verifyUser()
{
$userName = $_POST['email'];
$userPassword = $_POST['password'];
$var=array('email'=>$userName,'password'=>$userPassword);
$check=$this->mymodel->login_validation($var);
//$status = array("STATUS"=>"false");
if(count($check))
{
redirect('main/valid_login');
}
else
{
echo "<div style='border:1px solid red;font-size: 11px;margin:0 auto !important;'>Could't Authorize to the system! Try again with valid credentials.</div>" ;
}
}
this is my ajax function
<script>
function makeAjaxCall(){
$.ajax({
type: "post",
url: "<?php echo site_url('main/verifyUser');?>",
cache: false,
data: $('#userForm').serialize(),
success:function(msg)
{
$('#show_id').html(msg);
}
});
}
</script>
this is my form
<form name="userForm" id="userForm" action="">
<div id="show_id"></div>
<fieldset>
<p><label for="email">E-mail address</label></p>
<p><input type="email" id="email" placeholder="enter your email id" name="email"></p> <!-- JS because of IE support; better: placeholder="mail#address.com" -->
<p><label for="password">Password</label></p>
<p><input type="password" id="password" placeholder="*******" name="password" style="width: 328px;"></p> <!-- JS because of IE support; better: placeholder="password" -->
<p><input type="button" value="Sign In" onclick="javascript:makeAjaxCall();"></p>
</fieldset>
</form>
everything is working fine,but when i entered the valid username and password,its not redirecting to any page,so please help me on this
Send JSON data to ajax as response and handle it according to need.
Contorller:
public function verifyUser() {
$userName = $_POST['email'];
$userPassword = $_POST['password'];
$var=array('email'=>$userName,'password'=>$userPassword);
$check=$this->mymodel->login_validation($var);
//$status = array("STATUS"=>"false");
if(count($check)) {
$this->output
->set_content_type("application/json")
->set_output(json_encode(array('status'=>true, 'redirect'=>base_url('main/valid_login') )));
}
else {
$this->output
->set_content_type("application/json")
->set_output(json_encode(array('status'=>false, 'error'=>'Could't Authorize to the system! Try again with valid credentials.')));
}
}
Handle JSON data with ajax.
$.ajax({
type: "post",
url: "<?php echo site_url('main/verifyUser');?>",
cache: false,
data: $('#userForm').serialize(),
dataType: 'json',
success:function(response) {
if( response.status === true )
document.location.href = response.redirect;
else
$('#show_id').html("<div style='border:1px solid red;font-size: 11px;margin:0 auto !important;'>"+response.error+"</div>");
}
});
Controller Function:
public function verifyUser()
{
$userName = $_POST['email'];
$userPassword = $_POST['password'];
$var=array('email'=>$userName,'password'=>$userPassword);
$check=$this->mymodel->login_validation($var);
//$status = array("STATUS"=>"false");
if(count($check))
{
echo 1;
}
else
{
echo "<div style='border:1px solid red;font-size: 11px;margin:0 auto !important;'>Could't Authorize to the system! Try again with valid credentials.</div>" ;
}
}
Ajax Function
<script>
function makeAjaxCall(){
$.ajax({
type: "post",
url: "<?php echo site_url('main/verifyUser');?>",
cache: false,
data: $('#userForm').serialize(),
success:function(msg)
{
if(msg== "1")
{
//redirect here
}
$('#show_id').html(msg);
}
});
}
</script>