Can anyone please tell me why my submit is not being executed? The log tells me: "Validation passed, will submit form", but is not submitting?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $("#ajax-payment-form").serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest("form").submit();
} else {
console.log(msg);
}
}).fail(function() {
console.log('AJAX error');
});
});
});
Thanks for your time
thar
just do this:
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
var $this = $(this);
e.preventDefault();
// Serialize data, make AJAX call
var str = $("#ajax-payment-form").serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$this.closest("form").submit();
//....
or shorter code: (Notice de submit event)
$(function(){
$("#ajax-payment-form").submit(function(e) {
e.preventDefault();
var $form = $(this);
$.post(
url: templateDir+"/payment_form/payment_process.php",
$form.serialize(),
function(){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$form.closest("form").submit();
} else {
console.log(msg);
}
},
'json'
).fail(function() {
alert( "error" );
});
});
});
Related
Firstly, I've been stuck between method and type as if I've defined method in form so I don't have to define it in ajax, and if so? ajax gives undefined in console.
Secondly, The following code gives 405 POST method not allowed.
Also, When I do succeed trying bunch of things ajax refreshes the whole page, I want to post data to server without refreshing the page.
Any help would do!!
Controller Function
public function storeDevSkill(Request $request, $user_id)
{
$this->validate($request,
[
'dev_skill_name' => 'required',
'dev_skill_exp' => 'required',
]);
try {
$data = array(
'dev_id' => $user_id,
'dev_skill_name' => $request->dev_skill_name,
'dev_skill_exp' => $request->dev_skill_exp,
);
DevSkill::create($data);
return back();
} catch (\Exception $exception) {
return back()->withError($exception->getMessage())->withInput();
}
}
Route:
Route::post('/developer/create/skill/{user_id}', 'SuperAdminControllers\DeveloperController#storeDevSkill')->name('store.developer.skill');
Form:
<form id="form_skill" method="POST" enctype="multipart/form-data" action= "{{route('store.developer.skill',$user->user_id)}}">
Button:
<button type="submit" id="addskillSubmit" value="{{$user->user_id}}" style="display: none;" class="btn btn-primary">Save</button>
Script:
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
console.log("Ajax Call")
event.preventDefault();
var action_url = '';
var user_id = $(this).attr('value');
console.log(action_url)
$.ajax({
url: action_url,
type: "post",
data: $(this).serialize(),
// dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
// var table = $('#addskilltable').DataTable();
// table.ajax.reload();
console.log(response.success)
}
}
});
});
});
</script>
You need to pass action attribute from the form to your ajax call like so
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
console.log(response.success)
}
}
});
});
});
</script>
Give it a try and see if that changes anything.
$(document).on('submit', '#form_skill', function(e){
e.preventDefault();
var nFormId = '#'+ $(this).attr('id');
var formData = $(this).serialize();
var url = $(this).attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function (response) {
console.log(response);
$(nFormId)[0].reset();
},
error: function (jqXHR, exception) {
},
beforeSend: function () {
},
complete: function () {
}
});
});
Hope this answer help you.
My Code:
<script>
$('#form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
}
});
return false;
});
</script>
The FORM:
<form id="form" class="center" action="http://localhost/products/index.php?route=checkout/cart/add" method="post">
<input type="text" name="cname">
<input type="hidden" name="product_id" value="51">
<input type="submit">
</form>
When the form presses submit it goes to the action page which is just a JSON success message, what I want to do is redirect to a different page other than the action page, but my code does not seem to be working?
What exactly is wrong with my code, can someone help me fix it?
I would be so grateful if you could help me out, many thanks!
You aren't posting any data which makes a POST fairly useless .
Also you have no error handler either
Try:
$(function(){
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function(){
// do something when request fails - See $.ajax docs
}
})
return false;
});
});
You can used this code for error handling! You also check this question on stackOverflow for redirecting to another page using jQuery/JavaScript:
click here
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
},
});
});
You need to have separate error and success handlerS like below.
In success method you can redirect to other pages/sites (window.location.href = "http://www.EXAMPLE.com";)
var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully, //Separate method for handling success
error: showError //Separate method for handling error
};
I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});
The login form on my site is shown using an overlay/modal with jquery-modal (http://kylefox.ca/jquery-modal/examples/)
I'm using ajax + php to validate the form. If validation passes, the form should be submitted.
I can halt the submit for validation (using return false), and the validation itself is working fine. But I don't know how to submit the form
I have tried many naive variations: return true, $theform.submit(), $("body").unbind("#myloginform") and more.. but so far no luck
$("body").on("submit", "#myloginform", function() {
$theform = $(this);
$.ajax({
url: "login_check.php",
type: "POST",
cache: false,
timeout: 9000,
data: $theform.serialize(),
dataType: "json",
success: function(data) {
if (data) {
if (data.status == "ok") {
alert("success! now the form can be submitted");
// SUBMIT THE FORM (instead of the alert)
} else {
$("body #loginstatus").html(data.status);
}
} else {
alert("Error bla bla.");
}
},
error: function(e) {
alert("Error (ajax) bla bla.");
}
});
return false;
});
To submit the FORM, you can call js native submit method:
document.getElementById('myloginform').submit();
See variants:
$('#myloginform')[0].submit();
$('#myloginform').get(0).submit();
An other way would be to set context option of ajax to this:
$.ajax({
context: this,
...,
});
And then in success callback, submit FORM using:
this.submit();
EDIT: i see you are already using a variable reference, so in your case, you can use too:
$theform[0].submit();
All these snippets won't trigger jQuery submit handler, avoiding a circular reference error.
Another approach:
var checkValid = false;
$("body").on("submit", "#myloginform", function () {
$theform = $(this);
if (!checkValid) {
$.ajax({
url: "login_check.php",
type: "POST",
cache: false,
timeout: 9000,
data: $theform.serialize(),
dataType: "json",
success: function (data) {
if (data) {
if (data.status == "ok") {
alert("success! now the form can be submitted");
// Everything is OK
checkValid = true;
$theform.submit();// Next time, no validation process, just natural send of the form.
} else {
$("body #loginstatus").html(data.status);
}
} else {
alert("Error bla bla.");
}
},
error: function (e) {
alert("Error (ajax) bla bla.");
}
});
return false;
}
});
Since you're using jQuery, I would suggest that you check out the jQuery submit function
http://api.jquery.com/submit/
I am trying to post a form through AJAX in Netsuite so that I could trigger an event after the form submit without actually reloading it.
Please help me out, I am a newbie with AJAX.
Here is the code
$('#du_joinnow').submit(function(e){
e.preventDefault(); //STOP default action
var formdata = $(this).serializeArray();
$.ajaxSubmit({
type: "POST",
url: "https://forms.na1.netsuite.com/app/site/crm/externalleadpage.nl?compid=XXXXXX&formid=1&h=XXXXXXXXXXXXXX"+ formdata,
data: formdata,
success:function(data, textStatus, jqXHR) {
$('#overlay').fadeIn(); //data: return data from server
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Ajax Call Failed.");//if fails
}
});
return false;
});
Instead of $.ajaxSubmit do $.ajax
Full Code:
$('#du_joinnow').submit(function (e) {
e.preventDefault(); //STOP default action
var formdata = $(this).serializeArray();
$.ajax({
type: "POST",
url: "https://forms.na1.netsuite.com/app/site/crm/externalleadpage.nl?compid=XXXXXX&formid=1&h=XXXXXXXXXXXXXX" + formdata,
data: formdata,
success: function (data, textStatus, jqXHR) {
$('#overlay').fadeIn(); //data: return data from server
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Ajax Call Failed."); //if fails
}
});
return false;
});
Try this,
$('#du_joinnow').submit(function(e){
e.preventDefault(); //STOP default action
var formdata = $(this).serializeArray();
$.ajax({
url:"https://forms.na1.netsuite.com/app/site/crm/externalleadpage.nl?compid=XXXXXX&formid=1&h=XXXXXXXXXXXXXX" + formdata,
type:"POST",
data: formdata,
complete:function(data) {
if (data.readyState == 4)
{
if (data.status == 200)
{
$('#overlay').fadeIn();
alert(data.responseText);
}
else
{
alert("Ajax Call Failed.");
alert(data.statusText);
}
}
}
});
return false;
});