jquery ajax form validation not working in chrome - ajax

I have the simple task of validating a user has entered the first name. This is working in most browsers but chrome doesn't seem to be getting a response from ajaxfirstname.php. Here is the script:
jQuery(document).ready(function () {
var validatefirst_name = jQuery('#validatefirst_name');
jQuery('#first_name').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatefirst_name.removeClass('error').html('<span style="margin-left: 5px;"><img src="images/loader.gif" height="16" width="16" /></span>');
this.timer = setTimeout(function () {
jQuery.ajax({
url: "ajaxfirstname.php",
data: "action=check_first_name&first_name=" + t.value,
dataType: "json",
async: false,
type: "post",
success: function (j) {
validatefirst_name.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
});
and my html
<label for="first_name">First Name</label>
<input id="first_name" name="first_name" type="text" id="first_name" value="<?php
$name = explode(' ',$this->my->name);
echo $name[0];
?>">
<span id="validatefirst_name"></span>
I opened up the developer tool but I don't see any error on this particular script. Does anyone have suggestions on this? Does the above code look correct? Would Chrome have any issues with it? Thanks in advance.

May be its because you have used id in textbox twice ["id="first_name"].Please change this and let me know..
id="first_name" name="first_name" type="text" id="first_name" value="my->name);

Related

Success function not being called after making AJAX request codeigniter

When I make an AJAX call from view and pass form data to the controller. I get a couple of problems. First, the code inside success is never executed, and second, the page is being refreshed even though it is an AJAX call. Can anyone tell me where am I doing wrong?
I have seen a lot of questions since yesterday but none of them were able to solve my problem.
Model code
public function insert_user($name, $email) {
$data = array();
$data['name'] = $name;
$data['email'] = $email;
$data['created_at'] = date('y-m-d');
$this->db->insert('all_users', $data);
return true;
}
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$this->User_model->insert_user($name, $email);
$this->load->view('view');
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
My form looks something like this:
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
NOTE: I am able to successfully insert data into the database.
The browser is submitting the form before your AJAX code gets a chance to run/finish.
Instead of binding an event to the click event of the button, you want to bind to the submit event of the form. Then you want to cancel the browser's default action. This is done via the e.preventDefault(); method.
Also, dataType: "json" is not needed here. dataType tells jQuery what kind of data your AJAX call is returning. You generally don't need it as jQuery can automatically detect it. Plus, if you are not returning a JSON document, then this may cause a problem.
const insertForm = $(".insert-form");
insertForm.on("submit", function (e) {
const name = insertForm.find("input[type=name]");
const email = insertForm.find("input[type=email]");
e.preventDefault();
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
success: function () {
$("body").append("Request made successfully");
}
})
});
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$data = $this->User_model->insert_user($name, $email);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>Users/insert_user", // <?php echo base_url() ?>controller_name/function_name
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
form looks something like this:
<form class="insert-form" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
The page was being refreshed because I had a button that was acting as submit button on changing it to the input of the type button it does not submits the form and we don't see the page being refreshed. And also the AJAX request made also runs successfully.
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<input type="button" class="insert-btn" value="Insert Data">
</form>

Ajax Submitting form Twice

I have a form in a modal window that allows a user to resend a confirmation email. When the form is submitted, the confirmation email is sent twice, instead of once. Everything else is working exactly as it should.
Form is pretty standard:
<form enctype="multipart/form-data" id="ReMailf" name="ReMailf" role="form" data-toggle="validator">
<fieldset>
<div class="row">
<p>You may enter a different email than your original if you wish. However, the original email will remain as the main contact on your application.</p>
<label class="desc" for="prim_email"> Email </label>
<input id="prim_email" name="prim_email" type="email" class="form-control" value="<?php echo $tE['prim_email']; ?>" data-error="Please Enter A Valid Email Address" required/>
<div class="help-block with-errors"></div>
</div>
<div class="row">
<input id="submitForm" name="submitForm" class="btn btn-success" type="submit" value="Resend Conformation "/>
<input name="uniqid" type="hidden" value="<?php echo $tE['unqID']; ?>"/>
<input name="ReMAIL" type="hidden" value="ReMAIL"/>
</div>
</fieldset>
</form>
… and here's the handler:
$(document).ready(function () {
$("#ReMailf").on("submit", function(e) {
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#ReMailf").submit();
});
});
I've read a number of other post about this, and tried some of the suggestions, but nothing is working. It either doesn't submit at all, or submits twice.
This is the only form on the page...
Suggestions please?
It is because you are using a button or submit to trigger the ajax event. Use this instead:
$(document).ready(function() {
$("#ReMailf").on("submit", function(e) {
e.preventDefault(); //add this line
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
or you can just use a simple form with action and method. It will do the job

Node JS Form Sumit using Ajax

I am new in Node JS , I want to submit a form using ajax like all we are doing in PHP/CakePHP but here i am facing a problem.
HTMl code
<form role="form" action="javascript:;" id="myform">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="enter">Submit</button>
</form>
My AJAX code is
$('.btn').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
console.log(data);
console.log(JSON.stringify(data));
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err);
}
})
});
app.js code
app.post('/ajax', bodyParser(), function (req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
var input = JSON.stringify(req.body);
var data = {
name : input.name,
email : input.email
};
var query = db.query("INSERT INTO users set ?",data, function(err, rows){
console.log(query.sql);
if (err)
console.log("Error inserting : %s ",err );
res.send({'success' : true, 'message' : 'Added Successfully'});
});
});
But when i submit this form then it generate an error in node console like
SyntaxError: Unexpected token "
at parse (D:\man_node\node_modules\body-parser\lib\types\json.js:83:15)
I think that, I am not 100% sure, that you should replace var data = $('#myform').serialize(); with var data = $('#myform').serializeArray();

Stop codeigniter from redirection

Is it possible to make codeigniter not to redirect after a failed login attempt and show a message on the same login box.
My login box is a popup type, which appears after I have clicked on the login button and disappears after clicking on the background.
Controllers
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run()){
$data=array(
'email' => $this->input->post('email'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
redirect('site/members');
}else {
$this->main();
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
}
I was trying to change elses with error messages but it still redirected to another page.
Html:
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
<script>
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>site/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password").val()
},
success: function(response) {
if(response == 'success'){
location.href = 'site/members';
} else {
$("#errors").show();
}
}
});
}
</script>
If you want to have the alert in the modal, you'll want to check the data with ajax (javascript or jquery). For example you'd have something like this:
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>your_controller/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password).val()
},
success: function(response) {
if(response == 'success'){
location.href = <where you want to send them>;
} else {
$("#errors").show();
}
}
});
}
And your HTML would look something like:
<div class="hide" id="errors">Incorrect username/password.</div>
<input type="email" id="email" />
<input type="password" id="password" />
The class="hide" is meant to be something CSS related where you would have something like "display: none;".
Then in your controller you'd check like this:
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
The echoed response is what will be sent to your ajax success function.
Edit:
You need to not use the form submission for the above to work, because with that method we don't want to submit the form, we want to pass the data from it.
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
I've also changed the javascript function above to be viewed as a function.
use
window.location.href = '/redirectpage'

AJAX form submission issue in Internet Explorer

For some reason the newsletter sign-up form bar I'm creating is not working as it should in IE. In fact, it's not working at all. If you visit the link below in Chrome or Firefox it works like it should, but in any version of IE it doesn't.
Anyone have any leads to fix this?
Here's the code, summarized:
$(function() {
$('#name').textboxhint({
hint: 'First Name'
});
$('#email').textboxhint({
hint: 'Email Address'
});
$("#submitButton").click(function() {
// VALIDATE AND PROCESS FORM
var name = $("#name").val();
var email = $("#email").val();
var dataString = 'name='+ name + '&email=' + email;
// HANDLE DATA: SHOW ERROR IF FIELDS ARE BLANK
if (name=='' || name=='First Name' ){
$('.errorIconName').show();
return false;
}
if (email=='' || email=='Email Address'){
$('.errorIconEmail').show();
return false;
}
else {
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(){
$('#signupWidget').fadeOut(400).hide();
$('#thankyouText').fadeIn(700).show();
$('.errorIcon').fadeOut(200).hide();
$('#signupWrap').delay(3000).fadeOut(800);
}
});
}
return false;
});
});
and...
<form action="" method="post">
<span id="sprytextfield1" class="pr20">
<input name="name" id="name" type="text"/>
<div class="errorIconName" style="display:none"></div>
</span>
<span id="sprytextfield2" class="pr20">
<input name="email" id="email" type="text"/>
<div class="errorIconEmail" style="display:none"></div>
</span>
<span>
<input type="submit" name="widgetButton" id="submitButton" value="SUBMIT"/>
</span>
</form>

Resources