Multiple dynamic forms submit and run function after - javascript

I'm having troubles to get my function work properly. There are actually two problems I have.
1) Sometimes the script only adds 1 of eg 7 forms.
2) When updating the page my other function is called for every form submitted instead of just once.
So I have code that creates the form(s) if for example a user clicks a button.
var pp_total_change = function(){
.. .... .
$('.pp_count').each(function(){
.........
pp_total_list_items += "<li><form action='cart/add/"+$(this).attr("labelid")+"' method='post' id='form_"+$(this).attr("labelid")+"'><span>"+$(this).attr("labelname")+"</span><span class='amt'>"+$(this).val()+"</span><span>€ "+pp_total_price.toString().slice(0,-2)+","+pp_total_price.toString().slice(-2)+"</span></form></li>";
// which results in ->
<form id="form_51847052" method="post" action="cart/add/51847052">...text...</form>
<form id="form_51847053" method="post" action="cart/add/51847053">...text...</form>
<form id="form_51847054" method="post" action="cart/add/51847054">...text...</form>
etc...
Then a function which submit the forms
$('.temp-cart .addToCart').bind('click',function(){
$('.temp-cart form').each(function(){
var qty = $(this).find('.amt').text();
var qty2 = parseInt(qty);
var url = $(this).attr('action')+'/?quantity='+qty2+'/';
$.ajax({
url: url,
type: "post",
data: $(this).serialize(),
success: function(response, textStatus, jqXHR) {},
error: function(jqXHR, textStatus, errorThrown) {},
complete: function() {
updateStuff();
}
});
});
Then a function updateStuff() that need to get fired once when all forms are done submitting.
function updateStuff(){
updateCartAjax();
$('.order .pp_count, .pp_countsum .pp_count').val(0);
$('.order .submit').popover('destroy').button('reset').animate({'opacity':'1'},200);
$("html,body").stop(true, true).animate({scrollTop: 0}, 333);
$(".pp_count").val('0');
$("#pp_order_total ul li").remove();
$("#pp_order_total ul").text('U heeft hiernaast nog geen producten geselecteerd.');
}
So the problem I'm facing is that when a users "creates" for example 7 forms then only one of those 7 forms are submitted. When I click the submit button a second time then all forms are submitted. I thought thi shas something to do with the id's but that wasn't the case.
Second how do I run the updateStuff function only once after all forms are submitted?
Any help greatly appreciated...

function deploy(){
return new Promise(function(resolve,reject){
var count= $('.temp-cart form').length;
$('.temp-cart form').each(function(){
var qty = $(this).find('.amt').text();
var qty2 = parseInt(qty);
var url = $(this).attr('action')+'/?quantity='+qty2+'/';
$.ajax({
url: url,
type: "post",
data: $(this).serialize(),
success: function(response, textStatus, jqXHR) {},
error: function(jqXHR, textStatus, errorThrown) {},
complete: function() {
count--;
if(count==0)
resolve();
}
});
});
});
}
$('.temp-cart .addToCart').bind('click',function(){
deploy().then(function(){
updateStuff();
})
}

Related

how can I delete the row from datatable in UI,though i could successfully delete from server using Ajax call

I have a data table and in each row I have a button Delete.
ON click of Delete i am making an ajax call and deleting the row from server by passing the id.
But on success of ajax call the row is not getting deleted in the table from UI.
Below si the code.
I have rendered the column for Delete
{
"data": "Action","orderable": false, "render": function(data, type, row) {
userSignum=readCookie("userSignum");
var userIDMGroups=readCookie("nfvDBGroups");
var userIDMGroupsArray=userIDMGroups.split(';')
if((jQuery.inArray(userIDMGroups,userIDMGroupsArray ) !== -1)&&(row['signumId'] == userSignum) )
{
return '<button class="btn btn-action deleterecord" id="'+row.id+'">Delete</button>'
}
else
{
return '<button class="btn btn-action deleterecord" id="'+row.id+'" disabled="disabled">Delete</button>'}
}
}
Below si the ajax call
$("#searchTable tbody").on("click", ".deleterecord", function () {
var table = $('#searchTable').DataTable();
var recordId=$(this).attr("id");
// var $row = $(this);
if(recordId!=null){
$.ajax({
type: 'POST',
url: config.vnfURL + 'vnf/delete',
dataType: "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify({"id" : recordId }),
processData: false,
success: function(response, textStatus, jqXHR) {
// table.row( $(this).parents('tr') ).remove().draw();
//$(recordId).remove();
table.row($(this).parents('tr')).remove().draw(false);
alert("record deleted");
if(jqXHR.status == "200"){
className = "alert-success";
msg = "Record has been deleted Successfully.";
} else {
className = "alert-danger";
msg = "Something wrong, please try again after sometime.";
}
$("#infoDiv").addClass(className).show();
$("#infoDiv>center>p").html(msg);
setTimeout(function() {
$("#infoDiv").removeClass(className).hide();
$("#infoDiv>center>p").html("");
// window.location = "/resources/search.html";
}, 7000);
},
please help
The reason is that this within AJAX success callback refers to XHR object, so you may assign const tr = table.row($(this).closest('tr')) outside of success callback and then do tr.remove().draw() upon successful deletion server-side.
p.s. also, note that I have used closest('tr') rather than parents('tr') as it is less error prone, since the latter may return array if your button happen to have multiple <tr> parents
Add this line on success call back of ajax
table.row( $(this).parents('tr') ).remove().draw();

How to get variable from one Ajax function to work in another Ajax function

I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.
The code in question is in the second Ajax function: data: {
'nameOutput': nameOutput.val()
}
Does anyone have any idea what I have to do?
var nameOutput;
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
nameOutput = $('#name-output').html(data);
$(nameOutput).html();
},
complete:function(){
$('#send-info').slideDown(1500);
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
alert(nameOutput.val());
$.ajax({
url: 'php/name-selection-send.php',
type: 'POST',
data: {
'nameOutput': nameOutput.val()
}
,
success: function(data) {
if (data == 'Error!') {
alert('Unable to submit inquiry!');
alert(data);
} else {
$('#success-sent').html(data);
}
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();
however I think you have to define the element like this to be a HTML element:
var nameOutput=$('<div></div>');
also in first ajax function,set the html using this:
nameOutput.html(data);
and if there is a real element with ID name-output , and you want the result to be visible, do both of these:
nameOutput.html(data);
$('#name-output').html(data);

how to pass #model.ApplicationId from html form to js

I am trying to make an auto save function that will save the form data. I am unable to pass my ApplicationId in from form to JS in order to auto save. Though with the fixed id, auto saving does work. I have the following code:
Js Code:
window.setInterval(AutoSaveDraft(id), 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
Html CODE:
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId" >
...
</form>
Basically, I want the #Model.ApplicationId to be passed to my Js, so that I can use that in my Autosaving function.
Let's say you have your JS on the same page as your html, you could simply write:
window.setInterval(function () {
var id = '#Model.ApplicationId'; // Turned C# to JS here
AutoSaveDraft(id);
}, 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
Now let's say your JS is somewhere else:
HTML:
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId" >
...
</form>
JS:
window.setInterval(function () {
var id = $("#application-form").attr('name'); // Retrieve the ID
AutoSaveDraft(id);
}, 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
That's said, I would suggest you to use data- attribute to pass that kind of data. Let's try with data-application-id.
<form asp-action="Edit" id="application-form" data-application-id="#Model.ApplicationId">
...
</form>
window.setInterval(function () {
var id = $("#application-form").data("application-id"); // Retrieve here
AutoSaveDraft(id);
}, 50000);
First off, your interval is wrong. What you are doing is calling a function and passing the result to the interval. You need to pass it a function that it can then call when needed. You are calling your function right away.
Next, all you need to do, is to use jQueries attr() method like so:
let id = 'application-form'
window.setInterval(() => AutoSaveDraft(id), 5000);
function AutoSaveDraft(id) {
let name = $(`#${id}`).attr('name')
console.log(name)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId">
</form>

Form reloading page without sending the data on submit

here's my code.
In my .js file:
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = '';
params += 'action=Send';
params += '&title='+title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
}
else
{
return true;
}
}
And in my index.php file:
<form action="" method="post" name="myform" id="myform"" >
Title: <input class="" type="text" name="title" value="" id="title"/> <br>
<input type="submit" value="Submit" onClick="javascript:Sendit();return false; ">
</form>
<?php
if ($_REQUEST["action"]=='Send')
{
$title = $_REQUEST["title"];
$sql = "INSERT INTO ...
$retval = $mysqli->query($sql, $conn);
if(! $retval ) {
echo('Could not enter data insert: ' . mysql_error());
}
else
{
//inform that everything went well
}
?>
This does not send a thing when the sunmit button is clicked. In fact, you can click the button until the end of the day that nothing happens (not even a message in the debugger)
If I delete the return false; from the onClick in the button, I click on the button and the page reloads even without filling in the title input which has to be filled in.
Ajax's success does not alert a thing and in both cases, nothing gets inserted in my database.
The insert query is correct, I've checked it.
Any ideas on how to send the data and validate?
Thanks
Use below Code to send req.
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = {};
params["action"] = 'Send';
params["title"] = title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
your validateField() function never returns true, so your if(bValidate) will never run. Javascript functions return undefined unless you explicitly return something, try this:
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
} esle {
return true;
}
}

Adding JSON object items to DIVs with same class

I've looked up a lot of examples and none really answered my question. I'm trying to iterate through a JSON file and add certain items to divs on my page.
Here's the code I've written so far. This code returns all the item values of all objects into the different divs instead of appending each item to its div. You can ignore the first for loop, it's just for adding id's to each div. I've also created an example fiddle.
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams',
dataType: 'json',
success: function(data) {
console.log(data);
var name = document.getElementsByClassName("player-name");
var gamename = document.getElementsByClassName("gamename");
var viewcount = document.getElementsByClassName("viewcount");
var date = document.getElementsByClassName("date");
var numItems = $('.stream').length;
var i = 1;
$('.stream').each(function(i) {
$(this).attr('id', (i + 1));
i++;
});
$('.stream').each(function(i, obj) {
$.each(data.streams,function(index,item) {
$(name).append(item.channel.name);
$(gamename).append(item.channel.game);
$(viewcount).append(item.viewers);
$(date).append(item.created_at);
});
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});
var name = $(".player-name"); // jQuery's $ cares about your fingers
var gamename = $(".gamename");
var viewcount = $(".viewcount");
var date = $(".date");
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams',
dataType: 'json',
success: function(data) {
console.log(data);
$.each(data.streams,function(index,item) {
// now use .eq(index) over your elements collections
name.eq(index).append(item.channel.name);
gamename.eq(index).append(item.channel.game);
viewcount.eq(index).append(item.viewers);
date.eq(index).append(item.created_at);
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("some error");
}
});

Categories

Resources