I am using CodeIgniter, I have one field which is called as change_password_id. The user can enter the id and it will check the id exist or not in the database using the remote method of Jquery validation.
I am getting the 303 error in the network tab.
The controller is not calling from AJAX.
$(function() {
$("#reset_password_request").validate({
rules: {
change_password_id: {
required: true,
remote: {
url: "<?php echo base_url()?>Employee_control/checkemp_exist",
type: "post",
data: {
change_password_id: function() {
return $("#change_password_id").val();
}
}
}
},
},
messages: {
change_password_id: {
remote: "This emp Id is not registered with us."
}
},
submitHandler: function(form) {
// console.log(form.submit)
form.submit();
}
});
});
Controller
public function checkemp_exist(){
echo $correct_emp_id= $this->input->post('change_password_id');
/*I will add code here after some time*/
}
form
<?php echo form_open('','id="reset_password_request"'); ?>
<div class="form_group">
<input type="text" class="form_control" id="change_password_id" name="change_password_id">
<?php echo form_error('change_password_id'); ?>
</div>
<div class="btn_container">
<button class="btn_default orange_bg" type="submit"> Send request </button>
</div>
<?php echo form_close(); ?>
Related
I am trying to implement a realtime email duplication check in an application using PHP Codigniter, Ajax and Jquery. But I am not getting any successful results.
Jquery
<script type="text/javascript">
$(document).ready(function()
{
$("#email").keyup(function()
{
if($("#email").val().length >= 4)
{
$.ajax(
{
type: "POST",
url: "<?php echo site_url('stthomas/check_user');?>",
data: "email="+$("#email").val(),
success: function(msg)
{
if(msg=="true")
{
$("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/yes.png')" });
}
else
{
$("#usr_verify").css({ "background-image": "url('<?php echo base_url();?>images/no.png')" });
}
}
});
}
else
{
$("#usr_verify").css({ "background-image": "none" });
}
});
});
</script>
My Form is as Follows
<div class="form-group formgp">
<label class="col-md-4" for="Inputemail">Email :</label>
<div class="col-md-8" >
<input type="text" name="email" class="form-control" id="email" value="<?php echo set_value('email'); ?>" placeholder="Email"> <span id="usr_verify" class="verify"></span>
</div>
</div>
Controller:
public function check_user()
{
$usr=$this->input->post('email');
$result=$this->stthomas_model->check_user_exist($usr);
if($result)
{
echo "false";
}
else{
echo "true";
}
}
Model:
public function check_user_exist($usr)
{
$this->db->where("email",$usr);
$query=$this->db->get("email");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
It is not easy to guess what the problem is, but you better check the jquery ajax error detail. you have just set the success part of process in your code:
success: function(msg){
See what error you have if the ajax gets an error:
success: function(msg){
// success code
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
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
}
});
I am a bit of a noob with jQuery and am learning for Uni.
I am working on a HTML web site with an associated HTML mobile application that I will compile in phonegap build.
I have a HTML form that I want to include on both the site and the app which I have coded and is successfully validating with jQuery. I would also like to post the form data with jQuery but am struggling to find how best to achieve this.
My form looks like this
<form action="http://myaddress.com/process.php" method="post" name="jform" id="jform">
<div>
<label for="name"><b>Name:</b></label><br>
<input type="text" name="name" id="name">
</div>
<div>
<label for="dob"><b>Date of Birth:</b></label><br>
<input type="text" name="dob" id="dob">
</div>
<div>
<label for="visit"><b>Date of Visit:</b></label><br>
<input type="text" name="visit" id="visit">
</div>
<div class="labelBlock">
<b>Favourite Exhibit:</b>
<div class="indent">
<input type="radio" name="fave" id="exhibit1" value="Exhibit1">
<label for="exhibit1">Exhibit 1</label><br>
<input type="radio" name="fave" id="exhibit2" value="Exhibit2">
<label for="exhibit2">Exhibit 2</label><br>
<input type="radio" name="fave" id="exhibit3" value="Exhibit3">
<label for="exhibit3">Exhibit 3</label>
</div>
</div>
<div>
<label for="comment"><b>Comments:</b></label><br>
<textarea name="comment" id="comment" rows="10" cols="40" draggable="false"></textarea>
</div>
<div id="center-button">
<input name="submit" type="submit" id="submit" value="Submit" class="center-text">
</div>
</form>
My validation script looks like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
var name = $('#name').val();
var dob = $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[name='fave']:radio:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'process-post.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data1){
if (data1 == 'success') {
window.location.href = 'index.html';
}
else {
alert('Oops! It looks like something has gone wrong. Please try again.');
}
}
});
}}); // end ready
I really am struggling with this so would appreciate any help.
My PHP Looks like this
<?php # PROCESS JOURNAL ENTRY.
# Check form submitted.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
# Open database connection.
require ( '../connect_db.php' ) ;
# Execute inserting into 'forum' database table.
$q = "INSERT INTO journal(name,dob,visit,fave,comment,date)
VALUES ('{$_POST[name]}','{$_POST[dob]}','{$_POST[visit]}','{$_POST[fave]}','{$_POST [comment]}',NOW() )";
$r = mysqli_query ( $dbc, $q ) ;
# Report error on failure.
if (mysqli_affected_rows($dbc) != 1) { die ('Error' . mysqli_error($dbc)); } else { echo "success"; }
# Close database connection.
mysqli_close( $dbc ) ;
}
?>
Yes he is correct jquery's ajax will accomplish this or http post. You will use one of the mentioned methods to get the data from the HTML form and send it to the sever.
You will need jQuery ajax. This is a very powerful function that is used any time jQuery validation is used. It also lets you submit to the PHP file and get the results without refreshing the page.
EDIT:
Depending on the complexity of your project, ajax may be overkill. You can just normally submit the form after it is validated like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
}); // end ready
</script>
Here is the part that I add:
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
This will submit a form normally, meaning that it will run the PHP script and then refresh the page.
If you decide you want to use ajax, you can just replace $(form).submit(); with this:
var name = $('#name').val();
var dob= $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[type='radio'][name='fave']:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'http://myaddress.com/process.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data){
if (data == 'success') {
//do something
}
else {
//do something
}
}
});
The data that I am using in the success portion of the function is the value returned from the PHP script. Since you mentioned comments, I am assuming that you PHP is not returning data, but more or less a completion message. In that case, you would just have your PHP echo 'success'; if it was successful. Then fill in the "do somethings" in the jQuery.
Recently I swapped out a GoDaddy hosting and directing the requested DNS server to another mine.
The direction is pointing into a folder.
What happens is that I'm trying to make a validation by ajax login before submitting the form to actually login.
The AJAX calls and executes a php but data is not passed by POST as if they were lost in the request.
However, PHP is running in the AJAX request and even returns a message as I wanted, but the data is sent through ajax as if they got anything.
I tried to send the form by post Direct and caused the same error. I'm believing in the possibility that the POST is getting lost in directing the DNS. Is it possible?
Anyway, I'm leaving the HTML, AJAX and PHP:
Note: I'm using CodeIgniter.
HTML:
<?php echo form_open('usuarios/login', array('method' => 'post', 'id' => 'form-login')) ?>
<div class="boxform">
<label for="loginnome">Usuário ou E-mail:</label>
<input type="text" name="loginnome" required id="loginnome" placeholder="Usuário ou E-mail" title="Usuário ou E-mail">
</div>
<div class="boxform">
<label for="loginsenha">Senha:</label>
<input type="password" name="loginsenha" required id="loginsenha" placeholder="Senha" title="Senha">
</div>
<div class="boxform">
<input type="submit" class="button submit-claro" value="Logar" title="Logar">
</div>
<?php echo form_close(); ?>
AJAX:
$('#form-login').validate({
rules: {
loginnome: {
required:true,
maxlength:100
},
loginsenha:{
required:true,
maxlength:30
}
},
submitHandler: function( form ){
$.ajax({
type : "POST",
url : get_url()+"usuarios/validar_login",
dataType : 'json',
data : {
'usuario' : $('#loginnome').val(),
'senha' : $('#loginsenha').val()
},
success : function(data){
console.log(data);
if (data.usuario === false) {
$('.msg_error p').show();
$('.msg_error p').html('');
$('.msg_error p').html('Usuario inválido');
$('#loginnome').val('').focus();
}
else {
if (data.senha === false) {
$('.msg_error p').show();
$('.msg_error p').html('');
$('.msg_error p').html('Senha incorreta');
$('#loginnome p').val('').focus();
}
else {
inicia_sessao(data.url);
}
}
}
});
//return false;
}
});
PHP:
public function validar_login()
{
$usuario = $this->input->post('usuario');
$senha = $this->input->post('senha');
$return = $this->usuario->valida_login($usuario,$senha);
$return['url'] = site_url();
echo json_encode($return); die;
}
You may have to contact your provider to resolve this as it is directly / indirectly under their control.
How to reload only the page content, not the whole page after jquery ajax success function for the given php and javascript code. In that initially it displays
success
and after ajax call it will display as
failed
with reloading the whole page..
Php code :
<?php
require 'dbconnect.php';
$sql="select * from tbl_status where id='1'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
if($row['status']=='1')
{
?>
Success <div class="status" style="visibility:hidden;">0</div>
<?php
}
else
{
?>
Failed
<div class="status" style="visibility:hidden;">1</div>
<?php
}
?>
<input type="submit" class="send"/>
Javascript code :
<script type="text/javascript">
$(function(){
$('.send').click(function(){
var status=$('.status').text();
$.ajax({
type: 'POST',
url: 'http://localhost/status/updatestatus.php',
data: 'status='+status,
success : function (e)
{
var response=e;
alert(response);
},
error: function()
{
alert('error');
}
});
});
});
</script>
Try.Sorry for if there are some issues as it was written in notepad.
index.php
<?php
require 'dbconnect.php';
$sql="select * from tbl_status where id='1'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
<div id="response">
if($row['status']=='1')
{
?>
Success <div class="status" style="visibility:hidden;">0</div>
<?php
}
else
{
?>
Failed
<div class="status" style="visibility:hidden;">1</div>
<?php
}
?>
</div>
<input type="submit" class="send"/>
<script type="text/javascript">
$(document).ready(function(){
$('.send').click(function(){
var status=$('.status').text();
$.ajax({
type: 'POST',
url: 'http://localhost/status/updatestatus.php',
data: 'status='+status,
success : function (data, status)
{
$("#response").html(data.status);
},
error: function()
{
alert('error');
}
});
});
});
</script>
updatestatus.php
<?php
require 'dbconnect.php';
$sql="update tbl_status set status=$_POST['status'] where id='1'";
$res=mysql_query($sql);
$count = mysql_affected_rows();
if($count > 0){
return json_encode(array('status'=>$count));
}else{
return json_encode(array('status'=>0));
}
?>
If you are having problem with reloading the page then you can use
window.location.href=window.location.href;
Hope this helps
use load instead reload in your success
...
success : function (e)
{
$('your id or class name').load(php_file_name +'your_id_or_class_to_refresh');
var response=e;
alert(response);
location.reload();
},
....
// location.reload(); // <-- does not work so
considering your ajax is working fine... and the response you are getting is HTML
you don't need to call location.reload()..
you just need to append the response to the DOMtree..
updated
HTML
....
?> //close php tag
<div id="displayStatus"> //create new div with id displayStatus
<?php
if($row['status']=='1')
{
?>
Success <div class="status" style="visibility:hidden;">0</div>
<?php
}
else{
?>
Failed <div class="status" style="visibility:hidden;">1</div>
<?php
}
?>
</div> //end the div
JQUERY
success : function (e)
{
var response=e;
alert(response);
$('#displayStatus').html(response); //replace the content in that
},
updatestatus.php
$status= $_POST['status'];
//make you query ..update your table
if($status == '0'){
echo 'Failed <div class="status" style="visibility:hidden;">1</div>';
}else{
echo 'Success <div class="status" style="visibility:hidden;">0</div>';
}
The problem is: your jQuery part and your PHP part are not compatible.
You didn't really change your return status, just text. To signal "Failed" use some header on PHP side. For example:
in PHP:
header('HTTP/1.0 403 Forbidden');
die('Failed');
Then you ajax will raise an "error" handler instead of "success".
OR you should use only "success" handler and test returned text in in:
in JavaScript:
success: function(data) {
if (data == 'Failed') {
alert('ERROR');
location.reload();
} else {
alert('Success');
}
},
I have used this code to change the status and show the changed value on the page. This is a Javascript function that uses an Ajax request to PHP that changes the value of status in the database.
function changeStatus(divID,id,action,frontOrAdmin)
{
xmlhttp=getobject();
var query="id="+id+"&action="+action+"&frontOrAdmin="+frontOrAdmin;
$oldStatus = document.getElementById(divID).innerHTML;
document.getElementById(divID).innerHTML='<img src="images/loading_icon.gif">';
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
var response = xmlhttp.responseText;
var responseArr = response.split(",");
if(($.trim(responseArr[1])=="0")||($.trim(responseArr[1])=="1")){
document.getElementById(divID).innerHTML=responseArr[0];
}
else{
alert(responseArr[0]);
document.getElementById(divID).innerHTML=$oldStatus;
}
}
}
xmlhttp.open("GET","pass.php?type=changestatus&"+query,true);
xmlhttp.send(null);
}