variable is not found inside ajax - ajax

<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?

You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});

Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.

Related

Laravel AJAX getting all records in one JSON request

i am trying to edit record in my database using ajax, my code is working fine, but i have to mention each column by name, how i can get same result without typing all columns name.
Edit Controller: i am using columns name [efirst,esecond etc] i want to pass everything from database without mentioning name
public function edit($id)
{
$teacher = Teacher::find($id);
return response()->json([
'status' => 'success',
'id' => $teacher->id,
'efirst' => $teacher->efirst,
'esecond' => $teacher->esecond,
]);
}
Edit.js:
jQuery(document).ready(function($) {
$(".table-container").on("click touchstart", ".edit-btn", function () {
$.ajax({
type: "GET",
url: "lists/" + $(this).attr("value") + "/edit",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
beforeSend: function() {
$('#esecond-not-found').remove();
},
success: function (data) {
$("#update-id").val(data['id']);
$("#update-efirst").val(data['efirst']);
$("#update-esecond").val(data['esecond']);
$('#update-form').show();
},
});
});
});
View:
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" name="id" id="update-id">
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<label for="esecond">esecond body</label>
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<div class="">
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
A teacher object can be passed instead of writing every table field
return response()->json([ 'status' => 'success', 'teacher' => $teacher ]);
So in order for this code to work the id of the form needs to match the name of the column
let teacher = Object.entries(data.teacher);
teacher.forEach(item => { $("#"+item[0]).val(item[1]); });
Let's say we have four inputs
<input id="data1" type="text" class="form-control">
<input id="data2" type="text" class="form-control">
<input id="data3" type="text" class="form-control">
<input id="data4" type="text" class="form-control">
and you do this
success: function (data) {
let teacher = Object.entries(data.teacher);
teacher.forEach(item => {
console.log(item)
$("#"+item[0]).val(item[1]);
});
}
the console log gives the following
(2) ["data1", "test1"]
(2) ["data2", "test2"]
(2) ["data3", "test3"]
(2) ["data4", "test4"]
you get an array of arrays that you can loop where the index position 0 is your input id and the index position 1 is your value.

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'

Passing checkbox value in ajax

Please, I need help in passing the check box value through ajax to other php file
This is my form :
<form class="form-horizontal" onsubmit="Javascript:return validate();" method="post" id="form">
<b>Jawwal Number</b>
<input name="msisdn" type="text" id="msisdn" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Username</b>
<input name="username" type="text" id="username" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Add Extra Security (Activation Code)</b>
<input type="checkbox" name="security" id="security">
<input type="submit" value="submit" class="btn btn-primary">
</form>
And this is my Ajax code :
$("#form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* set all the vars you want to post on here */
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
**'security':$('input[name="security"]').val(),**
'submit': $('input[name="submit"]').val()
};
$.ajax({
url: '/bulk2/admin/process/add_user.php',
method:'POST',
data: parameters,
success: function(msg) {
$('#test').append(msg);
}
})
});
What should I do so that I can pass the checkbox value to the other page ?
You can also use checkbox checked method.
var security = $('input[name="security"]').prop('checked'); /* it will return true or false */
and update your code
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
'security':security,
'submit': $('input[name="submit"]').val()
};
Use the method is() with property :checked.
var parameters = {
'security':$('input[name="security"]').is(':checked'),
};
This works for me.

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