How to call same ajax function on multiple pages with different url? - javascript

Hı gusy!
I am trying to drop ajax post function to one and use it on whole site with different url on each page.
This is my original function and how it works :
<button type="button"class="submit">send</button>
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
var form = $(this).closest('form');
$.ajax({
type:'POST',
url:'ActionPage.php',
data:form.serialize(),
success:function(vardata){
var json = JSON.parse(vardata);
if(json.status == 101){
alert(json.msg);
window.location.replace("/");
} else {
alert(json.msg);
console.log(json.msg);
}
}
});
});
});
Exp: I have multiple forms in some pages, so I need to use $(this).closest('form'); to post each form.
This is what I want to do, original function will be in scripts and included in page :
function ajaxLoader(url) {
var form = $(this).closest("form");
$.ajax({
type:"POST",
"url" : url,
data:form.serialize(),
success:function(vardata){
var json = JSON.parse(vardata);
if(json.status == 101){
alert(json.msg);
window.location.replace("/");
} else {
alert(json.msg);
console.log(json.msg);
}
}
});
}
And on the page I want to call it like this :
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
ajaxLoader("ActionPage.php", true);
});
});
I getting undefined message on all cases when I click send button, when I move $(this).closest("form"); to second function then I get undefined form error.
I have searched on site there are similar question but none of them has usefull answer. example : this one

$(this).closest("form"); does not resolve to the closest form element of the clicked button when inside your function `ajaxLoader'. Do a 'console.log( this )' in that function.
You can either inject the form directly into your function:
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
let form = $(this).closest("form");
ajaxLoader("ActionPage.php", form);
});
});
function ajaxLoader(url, form) {
...
}
Or you could use the action attribute of your form and hook to the submit event of the form directly:
$('form').on('submit', function( e ) {
e.preventDefault();
const $form = $(this);
const url = $form.attr('action');
const data = $form.serialize();
const method = $form.attr('method');
$.ajax({
url: url,
data: data,
success: function(response) {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="actionpage.php" method="POST">
<button type="submit">
submit
</button>
</form>

How this is scoped is based on the context of how it is called. You can change what this is with call/apply/bind. Basic example below.
function ajaxLoader(url) {
console.log(this, url)
var form = $(this).closest("form");
console.log(form[0]);
}
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
ajaxLoader.call(this, "ActionPage.php");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="foo">
<button class="submit">Click</button>
</form>

Related

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");
},
});
}

generic ajax form submission

ajax/javascript problem:
I have an app which consist of multiple forms. What i want to achieve is to make a generic js function to submit forms to their respective controllers by getting form id.. I m successfully getting form ids in form_id variable but m unable to use them. I tried replacing $('patient_form') with form _id and got following error: TypeError: form_id.on is not a function
Here is the following code for better understanding of the problem:
$(function () {
var form = document.getElementsByTagName("form");
var form_id = "'#" + form[0].id + "'";
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
});
The way you have it form_id is a string.
Try:
var form_id = $("#" + form[0].id);
$.ajax is a jquery function. If you want to use jquery (which in this case I think you should), then do it as follows:
$('form').on('submit', function () {
$(this).preventDefaults();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $('#patient_form').serialize(),
success: function (result) {
alert(result);
}
});
});
In addition to the other answers, you want to keep your form ID dynamic, right, so you can insert whatever values you want?
$(function () {
var form = document.getElementsByTagName("form");
// note you have to convert to jQuery object
var form_id = $("#" + form[i].id); // i, so you can put in the id for any form
form_id.on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Controllers/c_insertPatient.php',
data: $(this).serialize(), // again, keep generic so this applies to any form
success: function (result) {
alert(result);
}
});
});
});
You should set the event listener to the element, not the string of the id of the element. Also I presume you have jQuery because you are using $. Set an id on the form in the HTML. Then:
$(function () {
var form = $('#theFormId');
form.submit(function(event) {
$.post('Controllers/c_insertPatient.php', form.serialize(), function() {
alert('success');
});
event.preventDefault();
});
});

Form Submission issue, how I can get value of ID at end of my URL?

I have following code and I want to submit my Form on click button, Click function is working fine but tell me how I can Assign values of "ID" at the end of my URL as mentioned on the below code.
<script type="text/javascript">
$(document).ready(function() {
$(".btn-success").click(function(){
var ID = $(this).prev('.sendEmail').attr('id');
alert(ID);
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var form = $('#form2'); // contact form
var submit = $('#submit2'); // submit button
var alert = $('.alert'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '//mydomain.com/'+ID,
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('✔ Alert Successfully Sent!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
</script>
You need to make the ID var global:
var ID;
$(document).ready(function() {
$(".btn-success").click(function(){
ID = $(this).prev('.sendEmail').attr('id');
alert(ID);
});
});
...rest of your code
Or if you combine your document ready calls:
$(document).ready(function() {
var ID;
$(".btn-success").click(function(){
ID = $(this).prev('.sendEmail').attr('id');
alert(ID);
});
var form = $('#form2'); // contact form
var submit = $('#submit2'); // submit button
var alert = $('.alert'); // alert div for show alert message
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '//mydomain.com/'+ID,
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('✔ Alert Successfully Sent!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
This may help you understand more about variable scope

AJAX Multiple Forms With Same Submit/Click Function

I've got multiple forms (that are similar) that are passed using Ajax to appended a PHP page using this code below. However, when I click the first or second form, it only sends the data from the first form. Can I use just the one function on all forms, or is there a better way to go?
$('.col_1').click(function(){ // $('#col_1').on("click", function(){
var parent_id = $('input[name=parent_id]').val();
var child_id = $('input[name=child_id]').val(); ////
$.ajax({
type:"POST",
url: "array-2.php",
data:{parent_id: parent_id, child_id: child_id},
success: function(){
//do stuff after the AJAX calls successfully completes
}
}).done(function(data) {
$('body').append(data);
});
});
Here is the HTML I'm using.
<form name="col_1" id="columnA1" class="col_1"><div>Entrepreneur</div>
<input name="parent_id" type="hidden" id="parent_id" value="1234" />
<input name="child_id" type="hidden" id="child_id" value="abcd" />
</form>
<form name="col_1" id="columnA2" class="col_1"><div>Musician</div>
<input name="parent_id" type="hidden" id="parent_id" value="5678" />
<input name="child_id" type="hidden" id="child_id" value="efgh" />
</form>
I've seen similar threads using the submit functions but none with the click event. Thanks
You need to make your selector specific, what you have is too generic that it will select all the input[name=parent_id] and val() on the collection will return the value of the first item in the collection.
So change it to:
var $this = $(this),
parent_id = $this.find('input[name=parent_id]').val(),
child_id = $this.find('input[name=child_id]').val();
Also note that you may want to use submit event instead of click event. What you have is an event registered for the click event on the form which will keep invoking the event when you click anywhere inside the form(unless you really want to do so).
You can also use serializeObject. It will take care of all form fields:-
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and you can do:
$.ajax({
type:"POST",
url: "array-2.php",
data: $(this).serializeObject(), //This will give you the map
success: function(){
...
}
...
Demo
you should really be using the submit method and not click, your current code will fire every time the whole form is clicked on, it should look something like this:
$('.col_1').on('submit', function(e){ // fire on submit
var form = $(this);
var parent_id = form.find('input[name=parent_id]').val();
var child_id = form.find('input[name=child_id]').val();
$.ajax({
type:"POST",
url: "array-2.php",
data:{parent_id: parent_id, child_id: child_id}
}).done(function(data) {
$('body').append(data);
});
e.preventDefault();
});
Don't use the click on a form. It does not make any sense.
Just do this
<div class="col_1" data-parent_id="1234" data-child_id="abcd">Entrepeneur</div>
<div class="col_1" data-parent_id="5678" data-child_id="efgh">Musician</div>
using
$(function() {
$('.col_1').click(function(){
var parent_id = $(this).data("parent_id");
var child_id = $(this).data("child_id]");
$.post("array-2.php",{parent_id: parent_id, child_id: child_id},
function(data){
//do stuff after the AJAX calls successfully completes
$('body').append(data);
});
});
});

Categories

Resources