I'm trying to have this form submitted and it works. However, i can't get to show a "success" message after clicking submit button.
function signup() {
var postData={ "service" :$('input[name=service]').val(), "ent_id": $('input[name=ent_id]').val(), "name": $('input[name=name]').val(), "mail_address" : $('input[name=mail_address]').val(), "password": $('input[name=password]').val()};
postData = JSON.stringify(postData);
$.ajax({
url: 'http://domain.com/api?service=security&action=signup&request=' + postData,
type: 'GET',
});
return false;
}
Here's the form:
<form onsubmit="return signup()">
Name:<input type="text" name="name">
Email:<input type="text" name="mail_address">
Password: <input type="password" name="password" >
<input type="submit" name="submit" value="Submit">
<input type="hidden" name="service" value="wf" />
<input type="hidden" name="ent_id" value="null" />
</form>
Could someone here help me out with the codes?
This should do what you want it to do. All you need to do is use the success / error callbacks that come with jQuery.
function signup() {
var postData={
"service": $('input[name=service]').val(),
"ent_id": $('input[name=ent_id]').val(),
"name": $('input[name=name]').val(),
"mail_address" : $('input[name=mail_address]').val(),
"password": $('input[name=password]').val()
};
postData = JSON.stringify(postData);
$.ajax({
url: 'http://domain.com/api?service=security&action=signup&request=' + postData,
type: 'GET',
success: function() {
alert('successfully submitted');
},
error: function() {
alert('an error has occurred.');
}
});
return false;
}
$("form[name='myForm']").submit(function(e) {
var postData={ "service" :$('input[name=service]').val(), "ent_id": $('input[name=ent_id]').val(), "name": $('input[name=name]').val(), "mail_address" : $('input[name=mail_address]').val(), "password": $('input[name=password]').val()};
postData = JSON.stringify(postData);
$.ajax({
url: 'http://domain.com/api?service=security&action=signup&request=' + postData,
type: 'GET',
success: function(data){
//alert(data);
alert("success message");
}
});
return false;
}
<form id="myForm" name="myForm" accept-charset="utf-8">
Related
I have this search form to post using jQuery:
<form id="search-article-form" method="post">
<input type="hidden" name="token" value="LSN71T8CeWr">
<input id="searcharticle" type="text" placeholder="search..."
name="searcharticle">
</form>
jQuery snippet:
$(function () {
$('#searcharticle').keyup(function() {
var form = $('#search-article-form');
console.log('form:', form.serialize());
$.ajax({
type: "POST",
url: "/search/article/",
data: form.serialize(),
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR) {
console.log('data:', data);
$('#search-results').html(data);
}
The problem is that the form does not seem to be serialized properly, so on keyup I see only this in the console:
form: token=LSN71T8CeWr
Also on the server side, the received post parameters is empty.
So wondering what is wrong here and how to fix it?
Works fine in the attached snippet
$(function () {
$('#searcharticle').keyup(function() {
var form = $('#search-article-form');
console.log('form:', form.serialize());
});
});
function searchSuccess(data, textStatus, jqXHR) {
console.log('data:', data);
$('#search-results').html(data);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search-article-form" method="post">
<input type="hidden" name="token" value="LSN71T8CeWr">
<input id="searcharticle" type="text" placeholder="search..."
name="searcharticle">
</form>
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.
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);
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.
}
});
I want to return false from $.ajax when success is complete:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
return false;
}
});
This doesn't work. Is there a work around?
From your post I guess that you call a function that contains the $.ajax() and try to return false to that function. but you can't do that such way, because AJAX is asynchronous.
It's better to call a function from the ajax success function like following:
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
success: function(result) {
var returned = true;
if(some_condition_not_satisfied) {
returned = false;
} else {
}
// call a function
calledFromAjaxSuccess(returned);
}
});
function calledFromAjaxSuccess(result) {
if(result) {
alert('TRUE');
} else {
alert('FALSE');
}
}
Maybe you could try something like this (values 1 and 0 should be changed to the ones that you use):
success: function(result){
if(result === '1'){
// do something
}
else
return false;
}
just use asunc false it can work fine i have implemented like that only
just try it
$.ajax({
url: '' + $website_url + 'queries/voorraad_berekenen.php',
type: 'post',
data: {
aantal: $(this).parent('form').children('.quantity').val(),
item_number_1: $(this).parent('form').children('.item_number_1').val()
},
async: false, //=>>>>>>>>>>> here >>>>>>>>>>>
success: function(result) {
return false;
}
});
it is working fine try it once
<form action="yourpage" method="post" onsubmit="return matchpass();">
<div>
<label> Name</label>
<input type="text" name="name" id="name">
</div>
<div>
<label> Email ID</label>
<input type="email" name="email" id="email">
</div>
<div>
<label> Mobile No</label>
<input type="text" name="mob" maxlength="10" onkeyup="check_if_exists();" autocomplete="off" id="mob">
</div>
<div>
<button type="button" >Send</button>
</div>
<span id="err"></span>
<div>
<label> OTP</label>
<input type="password" name="otp" id="otp" maxlength="6" placeholder="****">
<span id="err2"></span>
</div>
<div>
<input type="reset" value="Reset" class="reset-btn">
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<input type="hidden" id="otpcheck"/>
<script>
function matchpass()
{
$.ajax({
type:"post",
url: "yourpage",
data:{ mobile:mob,otp:otp},
success:function(data)
{
if(data==1)
{
document.getElementById("otpcheck").value=1; //important
}else{
document.getElementById("err2").style.color = "red";
document.getElementById("err2").innerHTML = "invalid OTP Number ";
document.getElementById("otpcheck").value=0; //important
}
}
});
if(document.getElementById("otpcheck").value==0){
return false;
}
}
I face this problem. then i found the actual solution. use async : false, inside ajax call
function thisisavailavailusername(uname){
var dataString = 'username='+ uname.value;
var trueorfalse = false;
$.ajax({
type: "post",
url: "/BloodBook/checkavailableusername",
data: dataString,
cache: false,
async : false, //user this then everything ok
success: function(html){
if(html=="true"){
$('#validusername').html('Available');
trueorfalse = true;
}else{
$('#validusername').html('Not Available');
trueorfalse = false;
}
},
error: function() {
alert("Something Wrong...");
}
});
return trueorfalse;
}