I'm using CodeIgniter for my web app and I'm currently stuck with AJAX forms.
I've made an view for my "forget password" modal and it looks like this:
<form action="<?=base_url()?>users/forgot_pass" method="post" id="forget_pass_form">
<div class="form_header">
<h1>Forgot your password?</h1>
</div>
<?php if($ajax_error == 0) { ?>
<div class="front_success">
<p>Password was succesfully sent to your email address.</p>
</div>
<?php } ?>
<?php if($ajax_error == 1) { ?>
<div class="login_error">
<p>Email address was not found in the database.</p>
</div>
<?php } ?>
<div id="loading_spinner"></div>
<p><input type="text" name="to_email" placeholder="Sähköpostiosoite" class="user" style="background-postion: -200px; margin-top: 20px;" />
<input type="submit" name="to_submit" value="Lähetä salasana" class="login_submit" id="forget-pass" /></p>
</form>
And here's my controller for it:
<?php
class Users extends CI_Controller {
public function forgot_pass()
{
if(isset($_POST['to_submit'])) {
$this->load->model('user');
$email = $_POST['to_email'];
$email_addr = $this->user->get_email_address($email);
if($email_addr) {
foreach($email_addr as $row) {
$this->load->library('email');
$this->email->from('me');
$this->email->to($email);
$this->email->subject('Testing');
$this->email->message('Your password is: ' . $row['password']);
if(!$this->email->send()) {
$data['ajax_error'] = 1;
} else {
$data['ajax_error'] = 0; }
}
}
}
$this->load->view('header');
$this->load->view('index', $data);
$this->load->view('footer');
}
}
?>
I won't post my Model since I know 100% sure it works and it only contains that one method to check if email is found in the database.
Now I want to make it more dynamic by using AJAX. I want it to echo the success message inside a div if the email address was found in the database and the mail was sent
to that email address, otherwise I want it to echo out the error "User was not found in the database".
Here's my js file which for now:
$(document).ready(function() {
$("form#forget_pass_form").on('submit', function(){
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
}
});
return false;
});
});
The AJAX part itself is working, but I just don't know how to implement those messages. Any help would be much appreciated.
make your html code like this
<div class="front_success" style="display:none">
<p>Password was succesfully sent to your email address.</p>
</div>
<div class="login_error" style="display:none">
<p>Email address was not found in the database.</p>
</div>
small change in controller:-
if($this->email->send()) {
echo '1';
} else {
echo '0';
}
so what ever your controller return based on that success function will make the dive show
try to make you ajax code like this :-
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
},
success: function (data) {
//alert(data); alert it if you want to check the function output
if(data == '1'){
//if the email is send then it return 1 so that you show success msg
$("#login_success").show();
}else{
//if the email is not send then it return 0 so that you show error msg
$("#front_error").show();
}
$("#loading_spinner").hide();// hide when ajax complete
}
});
Related
I'm trying to submit form data from view to controller using Ajax post and return success message.And ajax in my view send data to function in controller successfully but controller function does not return response back to ajax success function.
my Controller - profile.php
function save()
{
$response = array();
$this->form_validation->set_rules('fname', 'Title cant be empty ', 'required');
if ($this->form_validation->run() == TRUE)
{
$param = $this->input->post();
unset($param['submit']);
$param['rid']=$this->session->userdata('id');
$profile_id = $param['profile_id'];
unset($param['profile_id']);
if($profile_id == 0)
{
$inserts = $this->profile_model->insert($param);
if( $inserts>0){
$response['status'] = TRUE;
$response['notif'] ="success add profile details";
}else{
$response['status'] = FALSE;
$response['notif'] = 'Server wrong, please save again';
}
}else{
}
}else{
$response['status'] = FALSE;
$response['notif'] = validation_errors();
}
echo json_encode($response);
}
view - profile_new_user.php
?>
<form method="POST" id="form_profile" action="<?php echo base_url().'profile/save'; ?>">
<input type="hidden" name="profile_id" value="0"><!-------event id---------->
<div class="form-group">
<label>Prefix</label>
<select name="prefix" class="form-control">
.
.
.
</div>
<div class="form-group">
<input type="submit" name="submit" value="Save" class="btn btn-info" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form_profile").submit(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: $(this).attr("action"),
dataType :'JSON',
data: $(this).serialize(),
success: function(data)
{
if(data.status){
alert('ok');
}else{
alert('not ok');
}
}
})
});
});
model - profile_model.php
function insert($data)
{
$this->db->insert('user_profile', $data);
return $this->db->insert_id();
}
after I click submit button page redirect to url - http://localhost/ptm6/profile/save and page shows
{"status":true,"notif":"success add profile details"}
in plain text.
I expect to show alert message without any redirection.
I am trying to check the entered username and email with the database to check its availability.
It checks the email perfectly fine. I am using the same code for the email but with different id tags:
Here is my form for username:
<label for="username">Desired Username</label>
<input type="text" class="form-control" id="desusername" name="desusername" placeholder="Enter username" onkeyup="checkname();" required>
<span id="name_status"></span>
Here is the function to check it:
function checkname()
{
var username=document.getElementById("desusername").value;
if(username) {
$.ajax({
type: 'post',
url: '../members/authentication/checkusername.php',
data: {
username:username,
},
success: function (response) {
$( '#name_status' ).html(response);
if(response=="OK") {
return true;
}else {
return false;
}
}
});
}
else {
$( '#name_status' ).html("");
return false;
}
}
And here is my php script to check:
<?php
require_once("../../includes/database.class.php");
if(isset($_POST['desusername'])){
$username = $_POST['desusername'];
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $database->query($sql);
if(mysqli_num_rows($result) > 0) {
?>
<div class="alert alert-danger" role="alert">
<strong>Username already exists</strong>. Please choose a different one.
</div>
<?php
}else{
?>
<div class="alert alert-success" role="alert" style="margin-top: 10px;">
<strong>Valid</strong>. You are good to go!
</div>
<?php
}
exit();
}
?>
Now, in the developers console it shows its calling the function everytime i type:
XHR finished loading: POST "http://localhost/members/authentication/checkusername.php".
But nothing is displaying in the relevant div (#name_status)..
You can't see the response because you're using the wrong index on checkusername.php.
change below code
if(isset($_POST['desusername'])){
$username = $_POST['desusername'];
to this
if(isset($_POST['username'])){
$username = $_POST['username'];
and you're good to go. :)
Make sure that
data: {
key:value,
},
You have to use key while fetching data from post request or get request.
HTML code:
<div class="small-3 columns">
<input type="submit" id="join" class="button postfix " value="Join »">
<span id="error"></span>
</div>
I am using jQuery ajax post data method to print "Subscription successful" when user clicks on join button.
jQuery code:index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#join").click(function() {
var vemail = $("#emailaddy").val();
if(vemail=='') {
alert("Please enter email address");
} else {
$.post("join.php", //Required URL of the page on server
{
// Data Sending With Request To Server
emailaddy:vemail
},
/*function(response,status){ // Required Callback Function
alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
$("#form")[0].reset();
});*/
}
$("#error").text("hello");
});
});
</script>
I have created another page which is requested by index.php.
<?php
if($_POST["emailaddy"])
{
$email = $_POST["emailaddy"];
// Here, you can also perform some database query operations with above values.
echo "Welcome ". $email ."!"; // Success Message
}
?>
You can uncomment this
/*function(response,status){ // Required Callback Function
alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
$("#form")[0].reset();
and if the response is true show a div with a "Subscription successful" text-message.
Close $.post() method properly.And set subscription message from function inside post method.Like this..
$.post("join.php", //Required URL of the page on server
{ // Data Sending With Request To Server
emailaddy:vemail
},
function(response,status){
alert(response);//alerts welcome email..
$("#error").text("Subscription successful");
$("#form")[0].reset();
});*/
First of all make a file named functions.php if you dont have one.
Then make a function SetFormMsg($msg) and one ViewFormMsg().
Code:
function SetFormMsg($msg) {
if(!isset($_SESSION)){
session_start();
}
$_SESSION['formMsg'] = $msg;
}
function ViewFormMsg() {
if(!isset($_SESSION)){
session_start();
}
if(isset($_SESSION['formMsg'])
{
$message = $_SESSION['formMsg'];
}
else
{
$message = "";
}
return $message
}
and in your html code at the end of the form make a element that contains:
*If you want all of these to work include the 'functions.php' at the beginning of both html and php/sql documents.
Try the following code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#join").click(function(){
var vemail = $("#emailaddy").val();
if(vemail=='')
{
alert("Please enter email address");
}
else{
$.post( "join.php",{ 'emailaddy': vemail})
.done(function( data ) {
$("#error").html(data);
$("#success").html('Subscription successful');
});
}
});
});
</script>
<div class="small-3 columns">
<span id="success"></span>
<input type="email" name="emailaddy" id="emailaddy">
<input type="submit" id="join" class="button postfix " value="Join »">
<span id="error"></span>
</div>
If the response is success you can use .html instead of .text
$("#error").html("Subscription successful"); for $("#error").text("Subscription successful");
Hi I am creating a login form with CodeIgniter using ajax but it is not function properly as i want. it is getting redirected to the page which I am doing through ajax but doesnot perform the do_login function. if i click login without entering any fields it does not shows fields required whereas i have given the validation code in do_login function. Please suggest me the appropriate solution for the problem how to redirect through ajax using those functions.
This is my controller user.php
class User extends CI_Controller {
public function index()
{
$this->load->view('login');
}
public function do_login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|callback_verifyUser');
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
$this->load->view('login');
}
else{
echo "loggedIn"; // where to put this echo to make it work through ajax
$data = array(
'username' => $this->input->post('username'),
'is_logged_in'=>1
);
$this->session->set_userdata($data);
redirect('user/members');
}
}
public function members()
{
if($this->session->userdata('is_logged_in')){
$this->load->view('home');
}
else{
redirect('user/restricted');
}
}
public function restricted()
{
$this->load->view('restricted');
}
public function verifyUser(){
$username=$this->input->post('username');
$password= $this->input->post('password');
$this->load->model('LoginModel');
if($this->LoginModel->login($username, $password)){
return true;
}
else{
$this->form_validation->set_message('verifyUser','Invalid Email or Password: Please enter it correctly');
return false;
}
}
public function logout(){
$this->session->sess_destroy();
redirect('user/index');
}
}
?>
This is my view file login.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="http://127.0.0.1/simple_login_comp/js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#frm_login").submit(function(event){
event.preventDefault();
$.ajax({
url: "http://127.0.0.1/simple_login_comp/index.php/user/do_login",
type: "POST",
data:
{
username: $('#username').val(),
password: $('#password').val()},
success: function(data)
{
if (data== 'loggedIn')
{
alert("you are logged IN");
//window.location.replace("http://127.0.0.1/simple_login_redirect/index.php/user/home");
//window.location.href="http://127.0.0.1/simple_login_comp/index.php/user/members";
}
else if(data== 'sorry'){
alert("sorry");
}
//else{
// alert(data);
//}
}
});
});
});
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="span12">
<div class="well">
<center><h1>Be a member of Mrwebsiter</h1></center>
</div>
</div>
</div>
<h1>Login</h1>
<p>Please fill your details to login</p>
<form action="" id="frm_login" method="post">
Username :</br>
<input type="text" name="username" id="username"/></br>
Password :</br>
<input type="password" name="password" id="password"/></br>
<input type="submit" value="Login" name ="submit"/>
</form>
<div class="row">
<div class="span12">
<div class="well">
<center><h3>copyright</h3></center>
</div>
</div>
</div>
</div>
</body>
</html>
And this is my model LoginModel.php
<?php
class LoginModel extends CI_Model {
public function login($username, $password)
{
$this->db->select('username', 'password');
$this->db->from('users');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query= $this->db->get();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
}
?>
My login form is not working, can anyone suggest me how to make it run and where have i done mistake. when i redirect it through ajax it does not validate the input through do_login function it directly redirects to the page.
here is your problem
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
$this->load->view('login');
}
change this to
if($this->form_validation->run()== false){
echo "sorry";exit
}
I suggest that you use echo json_encode($data); on you controller where $data is an associative array containing your require fields or any prompt.
On your ajax handle the callback with -
success: function(data) {
var response = eval('(' + data + ')');
// DOM codes here
} // rest of the codes here
If you're not familiar with this and you want to push this ajax thing on you login system, I suggest you check out javascript dom, callbacks and other related stuff.
On your Controller
public function do_login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|callback_verifyUser');
if($this->form_validation->run()== false){
echo "sorry"; // where to put this echo to make it work through ajax
}
else{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in'=>1
);
$this->session->set_userdata($data);
echo "loggedIn"; // where to put this echo to make it work through ajax
}
}
On your view
<script type="text/javascript">
$(document).ready(function(){
$("#frm_login").submit(function(event){
event.preventDefault();
$.ajax({
url: "http://127.0.0.1/simple_login_comp/index.php/user/do_login",
type: "POST",
data:
{
username: $('#username').val(),
password: $('#password').val()},
success: function(data)
{
if (data== 'loggedIn')
{
alert("you are logged IN");
window.location ="http://127.0.0.1/simple_login_redirect/index.php/user/members");
}
else if(data== 'sorry'){
alert("sorry");
}
}
});
});
});
</script>
I have a simple jquery modal box on my site. I'm new at jquery so I'm not sure how to keep the box open if an error is posed on the form that is being submitted. If submitted correctly redirect.
As of now when there is an error it reloads the page and have to press pop up again to view error.
Thanks in advance.
if(isset($_POST['submit'])) {
$email = $_POST['email'];
if(empty($_POST['name']) || empty($_POST['email'])) {
$error = "Please enter the info in the fields that are marked <br /> with *";
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$error_email = "Please enter a valid email address";
}else{
$success = true;
$success = "Thank You";
mysql_query("INSERT INTO watch_list
(name, email) VALUES('".$_POST['name']."', '".$_POST['email']."')")
or die(mysql_error());
header( 'Location: /watch.php' );
}
}
<div class="play_wrapper">
<div class="play">
<img src="/styles/images/lx_play.png"/>
<div id="toPopup">
<div id="popup_content">
<div class="vid_form_text">
Please enter your name and email to watch the film. <span class="green">Thank you.</span>
</div>
<?php if(isset($success)) { ?>
<div class="success_watch">Thank You!</div>
<?php } ?>
<?php if(isset($error)) { ?>
<div class="error_watch">
<?php echo $error; ?>
</div>
<?php } ?>
<?php if(isset($error_email)) { ?>
<div class="error_watch">
<?php echo $error_email; ?>
</div>
<?php } ?>
<form method="post" action="#">
<div class="form_text_sign_up_required">
All fields marked with an asterisk * are required
</div>
<div class="form_text_sign_up">
Name*
</div>
<input type="text" name="name" value="<?php if(isset($_POST['name'])) {echo $_POST['name'];} ?>" /> <br /><br />
<div class="form_text_sign_up">
Email*
</div>
<input type="text" name="email" value="<?php if(isset($_POST['email'])) { echo $_POST['email'];} ?>" /><br /><br />
<input type='submit' name='submit' value='submit' class='post'/>
</form>
</div> <!--your content end-->
</div> <!--toPopup end-->
<div class="loader"></div>
<div id="backgroundPopup"></div>
</div>
</div>
<script>
jQuery(function($) {
$("a.topopup").click(function() {
loading(); // loading
setTimeout(function(){ // then show popup, deley in .5 second
loadPopup(); // function show popup
}, 500); // .5 second
return false;
});
/* event for close the popup */
$("div.close").hover(
function() {
$('span.ecs_tooltip').show();
},
function () {
$('span.ecs_tooltip').hide();
}
);
$("div.close").click(function() {
disablePopup(); // function close pop up
});
$(this).keyup(function(event) {
if (event.which == 27) { // 27 is 'Ecs' in the keyboard
disablePopup(); // function close pop up
}
});
$("div#backgroundPopup").click(function() {
disablePopup(); // function close pop up
});
$('a.livebox').click(function() {
alert('Hello World!');
return false;
});
/************** start: functions. **************/
function loading() {
$("div.loader").show();
}
function closeloading() {
$("div.loader").fadeOut('normal');
}
var popupStatus = 0; // set value
function loadPopup() {
if(popupStatus == 0) { // if value is 0, show popup
closeloading(); // fadeout loading
$("#toPopup").fadeIn(0500); // fadein popup div
$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
$("#backgroundPopup").fadeIn(0001);
popupStatus = 1; // and set value to 1
}
}
function disablePopup() {
if(popupStatus == 1) { // if value is 1, close popup
$("#toPopup").fadeOut("normal");
$("#backgroundPopup").fadeOut("normal");
popupStatus = 0; // and set value to 0
}
}
/************** end: functions. **************/
}); // jQuery End
</script>
You'll want to handle this using AJAX. If you send the response back in JSON format, it makes it super easy to parse out if it was successful or not.
$('form').on('submit', function(e) {
var form = $('form')[0];
var data = new FormData(form);
// http://api.jquery.com/jQuery.ajax/
$.ajax({
url : 'Your URL',
data : data,
type: 'POST',
errror : function(xhr, status, err) {console.log(xhr, status, err);}, // This only gets thrown if form submits unsucessfully
success: function(response, status) {
// This assumes the response you're sending back from PHP is JSON
var data = JSON.parse(response);
if (data.error) {
// Handle form being unsuccessful
} else {
// Handle success
}
}
});
// This is to prevent the form from actually submitting.
e.preventDefault();
return false;
});