AJAX Multiple Forms With Same Submit/Click Function - javascript

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

Related

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

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>

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

Event needs multiple clicks in Jquery

I am trying to get the response from the PHP scripts but the button takes multiple clicks on firing the event. I read about that on Google but unable to understand that why it is going to happen.
Html Code
<form action="javascript:MyResults()">
<input type="submit" value="Search" id ="button1"/>
</form>
Javascript Code
function MyResults(){
$(document).ready(function(){
$("#button1").click(function(){
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
}
</script>
You are declaring $(document).ready(function() inside MyResult function . In first case it will execute the MyFunction & in second case it will execute the code inside the ready function.
Actually there is no need to the action here. Following change will work
HTML
<form id='target'>
<input type="submit" value="Search" id="button1" />
</form>
JS
$(document).ready(function() {
$("#target").submit(function() {
event.preventDefault()
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type: "POST",
async: true,
data: {
"search": searchData,
},
success: function(value) {
alert(JSON.parse(value));
$.each(value, function(index, value1) {
console.log(value1);
});
}
});
});
})
The problem is that your current code doesn't set-up the click-handler for button until the form is submitted. That first click triggers the action attribute on the <form>, which sets up the handler. The second click then calls the button handler.
Instead of your current code, you probably want HTML like this:
<form>
<input type="submit" value="Search" id ="button1"/>
</form>
Use $(document).ready(...) without the wrapper function MyResults(), and be sure to cancel the click event to stop traditional form submission:
<script>
$(document).ready(function(){
$("#button1").click(function(event){
event.preventDefault();
event.stopPropagation();
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
</script>
Here fired one event at two times.
First fired when form submit.
action="javascript:MyResults()"
Second fired after form submit which you have defined in the function part.
$("#button1").click(function(){});

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();
}

Hidden input text submit with jquery

I have a javascript var that returns the value of a input text ID "ven_prod", with the value of "ven_prod" I need to make a search in my database without submiting the page.
I can't use a javascript var in the java code, so i've setted the value in a hidden input text ID "prod_hidden", but I need to submit it to get the value with the java code and make the search...How do I do it ?
<input id="ven_prod" type="text" placeHolder="Código de Barras" autofocus>
<input id="prod_hidden" type="text" value="">
<script>
$('#ven_prod').keypress(function (e)
{
if(e.keyCode==13)
{
var table = document.getElementById('tbprodutos');
var tblBody = table.tBodies[0];
var newRow = tblBody.insertRow(-1);
var prod = document.getElementById('ven_prod').value;
var qtd = document.getElementById('ven_qtd');
var barra = prod.substring(0, 12);
var num = prod.substring(14, 16);
document.getElementById('prod_hidden').value = barra;
var ref = <%=pd.getProdutosBarra(request.getParameter("prod_hidden")).getPro_referencia()%>;
OR
var ref = <%=pd.getProdutosBarra(JS VAR 'barras HERE).getPro_referencia()%>;
if(prod.length==16) {
var newCell0 = newRow.insertCell(0);
newCell0.innerHTML = '<td>'+ref+'</td>';
var newCell1 = newRow.insertCell(1);
newCell1.innerHTML = '<td>'+num+'</td>';
var newCell2 = newRow.insertCell(2);
newCell2.innerHTML = '<td>'+qtd.value+'</td>';
var newCell3 = newRow.insertCell(3);
newCell3.innerHTML = '<td>R$ '+valor+'</td>';
var newCell4 = newRow.insertCell(4);
newCell4.innerHTML = '<td>'+barra+'</td>';
document.getElementById('ref').value = '6755';
document.getElementById('imgsrc').src = './?acao=Img&pro_id=1';
document.getElementById('valortotal').value = 'Testando novo valor';
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
} else {
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
alert("Código de barras inválido!");
}
return false;
}
});
</script>
you can make ajax call using jQuery as follows. will submit your form data as well along with hidden elements.
var form = jQuery("#YourFormID");
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data);
}
});
value of a input text named "pro_barras"
Are you sure? Look at this:
<input type="hidden" id="pro_barras">
its not the name of the input, its the ID. You can try using this:
<input type="hidden" name="pro_barras">
And now, you can use $.ajax to send the request to a new page, where you will request the data from the database. And then you'll write the response, and take it back on the first page.
What it will do depends on how you use it. I will try to ask you to simply use serialize() method by jQuery API, this will let you to create a simple URL param with the data from the form, use it as:
$.ajax({
var data = $('#formid').serialize(); // serialize the form..
url: "link/to/file.cshtml",
data: data,
success: function (datares) {
$('#resultid').html(datares); // write the result in the element
}
})
If you want to get only the value from that field you can use
var data = $('input[name=pro_barras]').val();
without submiting the page.
Your page will have to be submitted when you click on input type="submit" button. To prevent that you can use
$('#idofsubmitbutton').click(function () {
return false; // stop execution and stay on page..
}
Then the ajax will continue, other method is to remove the input type="submit" and use <button></button> which won't cause any submission.
get the value with the java code
This isn't java :) Its JavaScript, they are totally different. :)
a) You can use like that:
$("#pro_barras").bind("change paste keyup", function() {
//$('.someClass').submit();
$('#it_is_form_id').submit(); // it call form's submit function
});
The piece of code detected when input text change. To more info see also here If you want to customize form submit function
$('#it_is_form_id').bind("submit", function(){
//alert("submit");
// make here simple ajax query
return false; //<-- it is used so that default submit function doesn't work after above code.
});
Don't forget, all code will be inside
<script>
$(function() {
// your code must be here
});
</script>
b) If you don't want to use form, you can do like that:
<script>
$(function() {
$("#pro_barras").bind("change paste keyup", function() {
var text = $("#pro_barras").val();
$.ajax({
type: "POST",
url: "yourUrl",
data: text,
success: function(res){
console.log(res);
},
error: function(err){
console.log(err);
}
});
});
});
</script>
Making simple ajax query:
Using Jquery post method
https://stackoverflow.com/a/8567149/1746258
Pass entire form as data in jQuery Ajax function
You could also add a custom attribute to your input element (in Jquery):
<input type='text' id='pro_barras' customattr='myCustomInfo'/>
<script>
var customValue = $('#pro_barras').attr('mycustomvar');
alert(customValue);
</script>
Fiddle

Categories

Resources