Why ajax request not sending? - javascript

I have sample function for create event for any inputs of html form.
Function code:
function event(form, element) {
var timer;
$(element).keyup(function () {
clearTimeout(timer);
if ($(element).val()) {
timer = setTimeout(function() {
form.submit(function (e) {
e.preventDefault();
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(),
dataType: 'json',
success : function (json)
{
console.log(json);
},
error: function(error)
{
console.log(error);
}
});
});
$(element).css("border-color","green");
setTimeout(function() {
$(element).css("border-color", "#ccddea");
}, 3000);
}, 5000);
}
});
}
Usage:
var form = $('#form');
event(form, '#name');
event(form, '#lastname');
HTML form code:
<form action="http://localhost/app/form.php" method="POST" enctype="multipart/form-data" id="form">
<div class="row bottom-mrg">
<div class="col-md-6 col-sm-6">
<div class="input-group">
<input type="text" class="form-control" name="name" placeholder="Name" id="name">
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="input-group">
<input type="text" class="form-control" name="lastname" placeholder="Last Name" id="lastname">
</div>
</div>
</div>
<button type="submit">Send</button>
</form>
My form.php code:
<?php
$name = $_POST['name'] ?? null;
if(isset($name)) {
echo $name;
}
But after timeout form not sending. When I use only form.submit() it's work but with ajax() request not working. How to send ajax request in my situation?

I found a solution and answer for my question! You can look, test and leave your opinion about the solution found.
Javascript code:
var form = $('#form');
function event(form, element) {
var timer;
$(element).on('keyup', function () {
clearTimeout(timer);
timer = setTimeout(function () {
axios({
method: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
console.log(response.data);
})
.catch(function (response) {
console.log(response);
});
$(element).css("border-color","green");
setTimeout(function() {
$(element).css("border-color", "#ccddea");
}, 3000);
}, 5000);
});
$(element).on('keydown', function () {
clearTimeout(timer);
});
}
event(form, "#name");
event(form, "#lastname");
I used axios but using ajax also possible.

Related

Remove the required attribute after the sucees of form submission

I have a form on click of submit the input box is highlighted with the red color border if it is empty. Now i have jquery ajax form submission on success of the form i will display a message "data submitted" and i will reset the form so all the input fields will be highlighted in red color. Now i want to empty the fields after the success of form submission and it should not be highlighted in red color.
HTML
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
}
else {
var ins_date = new Date($.now()).toLocaleString();
var parms = {
name: $("#name").val(),
email: $("#email").val(),
inserted_date: ins_date
};
var url2 = "http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data) {
console.log('Submission was successful.');
$(".alert-success").removeClass("d-none");
$(".alert-success").fadeTo(2000, 500).slideUp(500, function() {
$(".alert-success").slideUp(500);
});
$('.index-form')[0].reset();
console.log(data);
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="container index-form" id="index-validation" novalidate>
<input class="form-control" type="text" id="name" name="name" placeholder="Your name" required>
<input class="form-control" type="email" id="email" name="email" placeholder="Email Address" required>
<div class="invalid-feedback">Please Enter a Valid Email Id.</div>
<input type="submit" id="submit" class="btn btn-default btn-lg btn-block text-center" value="Send">
</form>
I'm not clear with your question, Do you want to reset form or remove the error class. But anyways I'll try solving out both :
SCRIPT
<script type="text/javascript">
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('index-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
$(".index-form").submit(function(e) {
e.preventDefault();
return false;
} else {
var ins_date=new Date($.now()).toLocaleString();
var parms = {
name : $("#name").val(),
email : $("#email").val(),
inserted_date:ins_date
};
var url2="http://localhost:3000/api";
$.ajax({
method: 'POST',
url: url2 + "/homes",
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
//if you are removing specific property from class
$(".alert-success").css('display', 'none');
$(".alert-success").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-success").slideUp(500);
});
$("form")[0].reset();
console.log(data);
}, error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
}
});
</script>
Jquery doesn't support any method such as reset() of javascript, So you can trigger javascript's reset() method.
Feel free to ask doubts if stuck. Happy coding....!!!!!
$(this.('.index-form').find("input[type=text]").val("");
You can just empty the form value by giving the .val() as empty, you have to give this on after your ajax response.
and also instead of using fade in and fade out just try to use hide and show function both may work like same.

Getting Internal Server Error (500) - CodeIgniter

In my CodeIgniter project I need to insert data into db table, I am having
Internal server error (500)
issues to add data to database using Ajax.
My Ajax code is below,
$("#rsvp_form").validate({
rules: {
uname: {
required: true,
minlength: 8
},
uemail: "required",
umessage: {
required: true,
maxlength: 100
}
},
messages: {
uname: {
required: "Please enter your name",
minlength: jQuery.validator.format("At least 8 characters required!")
},
uemail: "Please enter your email",
umessage: {
maxlength: jQuery.validator.format("Please enter no more than 100 characters!")
},
},
// ajax request
submitHandler: function (form) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
// loader
$(".loader").show();
// ajax request
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/Welcome/create_wish",
data: formData,
dataType: "json",
success: function (data) {
// if send data successfull
if (data.status === 'success') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-success").show("slow");
}, 300);
// if send data something wrong
} else if (data.status === 'error') {
$(".loader").hide();
$(form).fadeOut("slow");
setTimeout(function () {
$(".form-error").show("slow");
}, 300);
}
}
});
return false;
}
});
My Welcome Controller function is below : ,
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_wish' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model_wishes Model is here,
function createWish($data) {
$this->db->insert("wishes", $data);
}
welcome_message View is,
<form id="rsvp_form" action="">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
When Post Wish button is clicked getting XHR failed loading: POST and an error
POST http://localhost/CodeIgniterProj/index.php/Welcome/create_wish 500 (Internal Server Error)
Please let me know what actually force to internal server error, and how could I fix this Issue.
You are using wrong post input, please check below updated code
public function create_wish() {
$this->load->model("model_wishes");
$data = array(
'user_name' => $this->input->post('user_name'),
'user_email' => $this->input->post('user_email'),
'user_wish' => $this->input->post('user_wish')
);
$this->model_wishes->createWish($data);
}
Hope this will help you :
Your submitHandler code should be like this :
submitHandler: function (form)
{
var formData = $(form).serialize();
$(".loader").show();
console.log(formData);
$.ajax({
type: "POST",
url: "<?=site_url('Welcome/create_wish'); ?>",
data: formData,
dataType: "json",
success: function (data) {
alert(data);
}
});
}
And your controller create_wish should be like this :
public function create_wish()
{
$this->load->model("model_wishes");
$user_name = $this->input->post('uname'));
$user_email = $this->input->post('uemail');
$user_wish = $this->input->post('umessage');
$data = array(
'user_name' => $user_name,
'user_email' => $user_email,
'user_wish' => $user_wish
);
$this->model_wishes->createWish($data);
$response = array('status' => 'success');
echo json_encode($response);
}
Instead of base_url use the site_url
site_url('Welcome/create_wish')

Using Ajax for submit a form in Laravel 5.4

I have a form and I want to send values to my controller
I wrote this codes but it returns me MethodNotAllowedHttpException error,
I have a html form
I send it with POST method
My route is post too
My form:
<form method="post" id="form">
{{csrf_field()}}
<input type="text" name="fname" id="fname">
<input type="text" name="lname" id="lname">
<input type="submit" name="submit-btn" id="submit-btn">
<h4 id="head"></h4>
</form>
JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#form').submit(function () {
$.ajax({
type : 'POST',
url : '{{route('routeName')}}',
data : {
fname: $("input#fname").val(),
lname: $("input#lname").val(),
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
},
success: function(result){
$('#head').text(result.head);
}
});
});
});
</script>
My Route :
Route::post('routeName' , [
'uses' => 'SomeController#Generate',
'as' => 'routeName']);
Controller :
public function Generate(){
$resp = array();
$fname= Input::get('fname');
$lname= Input::get('lname');
$resp["status"] = "ok";
return (Response::json($resp));}
And the error is :
error
Try this:
</script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#form').submit(function (e) {
e.preventDefault(); //**** to prevent normal form submission and page reload
$.ajax({
type : 'POST',
url : '{{route('routeName')}}',
data : {
fname: $("input#fname").val(),
lname: $("input#lname").val(),
},
success: function(result){
console.log(result);
$('#head').text(result.status);
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
}
});
});
});
</script>
Add Request in controller method Generate
public function Generate(Request $request){
$resp = array();
$fname = $request->fname;
$lname = $request->lname;
$resp["status"] = "ok";
return Response::json($resp);
}
Hope it helps.
Try changing the following:
url : '{{url('routeName')}}',
and
return Response::json($resp);
don't forget to prevent the default submit event
$('#form').submit(function (e) {
e.preventDefault();
..........
and change:
$('#head').text(result.status);

Codeigniter-POST not working via ajax

I have a form, whose values I am trying to post after serializing to a controller via ajax. Below is the form:
Form
<form method="post" id="frm_reg_student" class="stop-propagation registration-form">
<input type="hidden" name="register[user_type]" value="2">
<input type="hidden" name="register[status_id]" value="1">
<div class="stud_register_error"></div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">First Name <span>*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your First Name" name="register[first_name]">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">Last Name <span class="req">*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your Last Name" name="register[last_name]">
</div>
</div>
</div>
</form>
js
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
type: "POST",
url: '<?=base_url()?>index.php/register/signup/',
data: serialData,
success: function(result) {
alert(result);
output = JSON.parse(result);
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
Controller
public function signup(){
if($_SERVER["REQUEST_METHOD"]=="POST"){
print_r($_POST);
}
}
Here, $_POST comes out to be empty, it never goes inside the loop. If you see in the JS, I have included an alert with the serialized data, which even shows me the proper serialized data. I believe it is something wrong with the way I am posting it.
Any help!
Try on ajax
$(".js-btn_reg_student").click(function(e){
var formdata = $( "#frm_reg_student" ).serialize();
$.ajax({
type: "post",
url: "<?php echo base_url('register/signup');?>",
data: formdata,
dataType: 'json',
success: function(json) {
if (json[success]) {
alert(json['post']);
} else {
}
}
});
e.preventDefault();
});
And controller
public function signup() {
$data = array(
'success' => false,
'post' => ''
);
if ($this->input->server("REQUEST_METHOD") == 'POST')
{
$data['success'] = true;
$data['post'] = $_POST;
}
echo json_encode($data);
}
Try
$('#js-btn_reg_student').click(function () {
$.ajax ({
type: 'post',
url: '<?php echo base_url(); ?>index.php/test/signup/',
data: $('#frm_reg_student').serialize(),
dataType: 'json',
success: function(result) {
if(result.status == 'success')
{
alert(result.name);
}
else
{
alert(result.status);
}
}
});
});
And in Controller
public function signup ()
{
if($this->input->post())
{
$data = array('status' => 'success');
$data['name'] = $this->input->post('register[first_name]');
}
else
{
$data = array('status' => 'failed');
}
echo json_encode($data);
}
Try it and let me know if it works or not :)
Try to use below code.
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
url: '<?=base_url()?>index.php/register/signup/',
method : 'POST',
data: serialData,
success: function(result) {
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
I think all the answers were correct in their own way. I figured out that it might be possible that it is not getting the DOM upon submit so I simply put it in document.ready and it worked!
Thanks

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Categories

Resources