Ajax submit works in Chrome/Safari but not Firefox/IE - javascript

My contact form works well in Chrome & Safari but it doesn't work in Firefox or IE. It keeps submitting as a GET. Can anyone find the problem?
<form action="#" id="contactForm">
<input type="submit" id="contactClick" class="button white" style="margin-top:-2px;" name="submit" value="Send it!">
</form>
var $contactClick = $("#contactClick"),$contactForm = $("#contactForm"),$emailText = $("#emailText"),$emailSubmit = $("#emailSubmit"),$form = $("#contactForm"), $emailSubmit = $("#emailSubmit");
$("#contactForm").submit(function(){
event.preventDefault();
$contactClick.attr('disabled', 'disabled');
$contactClick.attr('value', 'Sending . . .');
var url = "/backend/page-content/emailPOST.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $contactForm.serialize(), // serializes the form's elemWorkents.
success: function(data)
{
$emailText.text(data);
$emailSubmit.fadeIn(400);
$contactClick.removeAttr('disabled');
$contactClick.attr('value', 'SEND IT!');
var noticeLength = $emailText.text();
if(noticeLength.length > 27){ $contactForm[0].reset(); }
}
});
return false;
});

You do not have event argument in the callback function.
$("#contactForm").submit(function(event)

Related

How to disable redirection to the url specified in the form action attribute on form submitting

I have a form with the action attribute set to "/tasks/". All I want is that on submitting the form, the data go to "/tasks/", but the user is not redirected to "/tasks/", they just stay on "/" instead. Is it possible to achieve?
I tried to add "return false" and "preventDefault" to the "onclick" handler, but that's not what I need as they cancel the form submission.
<form id="add-task-form" method="POST" name="add-task-form" action="/tasks/" enctype="multipart/form-data">
<label for="name" class="field-description">*Name</label>
<input id="name" type="text"required name="name" autofocus="true"><br>
<label for="description-text" class="field-description">*Description</label>
<textarea id="description-text" name="description"></textarea><br>
<button type="submit" id="save-button" class="saveButton"><span>Add task</span></button>
</form>
$('#save-button').on( 'click', function(){
if($('input').data().length() != 0){
var data = $('#add-task-form form').serialize();
$.ajax({
method: "POST",
url: '/tasks/',
data: data,
success: function(response){
$('#add-task-form').css('display', 'none');
var task = {};
task.id = response;
var dataArray = $('#add-task-form form').serializeArray();
for(i in dataArray) {
task[dataArray[i]['name']] = dataArray[i]['value'];
}
appendTask(task);
getTasksCount();
}
});
return false;
$('#home-page').show();
$('#add-task-page').remove();
};
})
I'm new to js and jQuery and they are definitely not my strongest points, so please, advice.
It's shall work like this :
$('#save-button').click(function(event) {
event.preventDefault();
...
});
to know more about it : https://api.jquery.com/event.preventdefault/
You can do something like this.
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action','/tasks/'), $(this).serialize(), function(response){
// Do something
},'json');
return false;
});
});
quotation
if you want to prevent it all, you can use event.preventDefault(). But since you are using ajax and you don't want to reload the page, you can try to apply this code:
$("#save-button").click(function(){
$.post('{post_url}',
$("#add-task-form form").serializeArray(),
function(data){
if (data.success){
redirect = '{last}';
} else {
reload(true);
}
},"json"
);
});

Why is jquery-ajax submitting form multiple times?

I have read this: jQuery ajax form submitting multiple times
It didn't help.
If i type something on form and click the submit button then it sends one request. Second time if i type something and click it sends two requests. Third time it sends three requests and so on. Why is this? Did i do any mistake in jquery code?
Here is my code:
index.php =>
<div id="id_div_1" class="cl_div_comment_container"></div>
<form id="id_form_1" method="POST">
<input type="hidden" value="1" name="nm_hidden_post_id">
<textarea class="cl_textarea_comment" style="resize:none;" rows="1" cols="50" name="nm_comment_content"></textarea>
<input class="cl_submit_comment" type="submit" value="Comment" name="nm_submit_comment">
</form>
javascript.js =>
$(document).ready(function(){
console.log('hello');
$('input[name="nm_submit_comment"]').on('click',function(){
var frm = $(this).closest("form")[0];
var frm_id = $(frm).attr("id");
var frm_id_splitted = frm_id.split("_");
var frm_id_splitted_2 = frm_id_splitted[2];
console.log($('div#id_div_' + frm_id_splitted_2));
$(frm).on('submit',function(e){
e.preventDefault();
frm_serialized = $(this).serialize();
console.log(frm_serialized);
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function(data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
});
});
save-comment.php =>
<?php
if (session_id() == '') {
session_start();
}
echo json_encode($_POST);
?>
You are registering the event for form submit inside the code you have for the click event on the button. So every time you click the button, it will keep adding the event over and over.
This should be good enough.
$(document).ready(function(){
$('input[name="nm_submit_comment"]').on('click',function(e){
e.preventDefault();
var frm = $(this).closest("form");
var frm_id = frm.attr("id");
var frm_id_splitted = frm_id.split("_");
var frm_id_splitted_2 = frm_id_splitted[2];
var frm_serialized = frm.serialize();
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function(data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
});
Try one then on
$("#id_form_1").one('submit', function (e) {
e.preventDefault();
frm_serialized = $(this).serialize();
console.log(frm_serialized);
$.ajax({
url: "save-comment.php",
method: "POST",
data: frm_serialized,
success: function (data) {
console.log(data);
$('div#id_div_' + frm_id_splitted_2).append(data);
}
});
});
Also no need to make submit bind just serialize your nearest form and make ajax call. You are binding event inside and event performs multiple binding.
You can try this:
$(document).off().on("click","#submit",(function(e) {
e.preventDefault();
}

How to post form to two different pages with a single button click?

I have a form with a single button like below:
<form name="sampleForm" id="sampleForm" method="post" action="" enctype="multipart/form-data">
<input type="text" id="biosample" name="biosample" class="sample"/>
<input type="text" id="library" name="library" class="sample"/>
<input type="submit" name="btnAdd" id="btnAdd" class="buttonsub" value="NEXT>>">
</form>
Ajax code is:
<script>
$(document).ready(function(){
var encoded_project_id = $('#encoded_project_id').val();
$('#sampleForm').on('submit', function(){
var target = 'windowFormTarget';
window.open('', target, 'width=500,height=300');
this.setAttribute('target', target);
$.post('postdata.php', $(this).serialize(), function(){
window.location.href = 'phases.php?edit='+encoded_project_id;
}).fail(function(){
window.location.href = 'sample.php?edit='+encoded_project_id;
});
});
});
</script>
Now when button is clicked, I want to post the data from the above form in 2 pages - handler.php and postdata.php
Handler.php should open in a new javascript window and postdata.php should open in same tab and same window.
How it can be achieved?
EDIT: It would seem you are using jQuery, so change this:
$(document).ready(function () {
document.getElementById('sampleForm').onsubmit = function (e) {
var req = new XMLHttpRequest();
req.open('POST', 'test.php', true);
req.send();
}
});
to this:
$(document).ready(function(){
$('#sampleForm').on('submit', function(){
$.post('postdata.php', $(this).serialize(), function(){
console.log('success');
}).fail(function(){
console.log('error');
});
});
});
You should do two things. First add
<form target="_blank" action="handler.php"></form>
This will ensure when the submit button is clicked that the form will open a new window.
Then you need to intercept the submit like so:
document.getElementById('sampleForm').onsubmit = function(e){
//xmlHTTPRequest function
//This is where you send your form to postdata.php
}
The code above will be called first and you can send your form with the asynchronous XMLHTTPRequest object to postdata.php . After that function ends, the default behavior of the form will start and your handler.php will receive the form.
you just to need two ajax call . Do something like this
$(document).ready(function(){
// if want to stop default submission
$("#sampleForm").submit(function(e){
e.preventDefault();
});
$(document).on('click','#btnAdd',function(){
send('page1.php',{'data1':'value'});
send('page2.php',{'data1':'value'});
});
});
function send(url,data)
{
$.ajax({
url: url,
type: 'POST',
datatype: 'json',
data: data,
success: function(data) {
// success
},
error: function(data) {
alert("There may an error on uploading. Try again later");
},
});
}

sending by post php ajax

Good morning, I want to send to an external site to my two variables by post are username and password and the page I create a cache in the browser when I go to another url already be logged in code what I do is check for through PHP if the data is correct or not, if they are correct returned if, but returns no, if they are correct what I want to do is force the form to send the submit the url, the problem is that everything works fine to the point the submit the form no longer do anything, can you help me?
Thank You
My code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#submit").click(function () {
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
</script>
</head>
<body>
<form action="" method="post" id="formoid">
<div><label>Usuario:</label><input name="user" placeholder="Usuario" type="text" id="user"></div>
<div><label>Contraseña:</label><input name="pass" placeholder="Contraseña" type="text" id="pass"></div>
<div><input name="enviar" type="submit" value="Enviar" id="submit"></div>
<div><input name="btnPass" type="submit" value="¿Olvidaste tu contraseña?"></div>
</form>
</body>
Just declare the event parameter in the click handler, and then do event.preventDefault(). Doing so, the default submit action is ignored and your code will be executed instead:
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
checkout the result whether its returning "si" if its correct
try
changing code
from
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
to
$("#formoid").attr('action', 'http://xzc.tv/login');
$("#form").submit();
try using id of form
To submit try the following
$("form#formoid").submit();
$("form#formoid")[0].submit();
$("form#formoid").submit(function(e) {});

jquery ajax call after javascript validation function

I am trying to call my ajax code after my js validate() methods returns true on submit of the searchId button. But the ajax code is not executing. if I place an alert there it works fine.
Where I am doing wrong? Please help!!
here is my javascript code
<script language="JavaScript">
function validate()
{
var msg = "";
//all my field validations are here
msg += "o Name is not a valid name.\n";
if (msg > "") {
alert(msg);
return false;
}
else {
return true;
}
}
$(document).ready(function(){
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
// getting the values of both firstname and lastname
var beginDate = $('input[name="txtBeginDate"]').val();
var endDate = $('input[name="txtEndDate"]').val();
var mdnVal = $('input[name="txtMsid"]').val();
// posting the values
var dataString = 'beginDate=' + beginDate + '&endDate=' + endDate+ '&mdnVal=' + mdnVal;
alert(dataString);
var formURL = $(this).attr("action");
//alert(formURL);
$.ajax(
{
url : formURL,
dataType:'json',
async: false,
data: dataString,
beforeSubmit: validate,
success:function(data){
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
drawChart();
},
error : function(xhr, type) {
alert('server error occoured')
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
});
});
Here is my HTML code
<form name="ajaxform" id="ajaxform" action="getData.jsp" onSubmit="return validate();" method="POST">
<Table>
<input type="submit" name="action" value="Search" id="searchId">
<input type="text" name="name" id="id" size="10" maxlength="10">
//other input fields
</table>
</form>
<button class="btn btn-info" id="simple-post">Run Code</button>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
UPDATE
I have updated my code, i can submit my form, but the validation not working. I am using beforeSubmit: validate, still i dont see my validation messages. Please help.
I fxed the problem. Added a Submit button markup and removed Run Code. Changed onsubmit to onclick on the submit button. Again removed $("#simple-post").click(function() form my jquery code.This seems to be working fine now.
Thanks to this post
Validate a form with javascript before submitting with ajax?

Categories

Resources