Tearing my hair out over this. I have a 40 rows of simple forms that are being generated dynamically from a mysql database. Each form has a unique ID based on the database ID. After clicking submit the results get updated in the database and inserted into the div (#result).
Works the first time perfectly. However after the first time the script won't serialize the updated form data. The ID is fine (checked via alert) but the formData is empty (also checked via alert).
Thinking I need to re-target the form somehow? Any help would be greatly appreciated. Thanks.
$('#result').on('click', '.submitform', function () {
var id = $(this).attr('id');
var formData = $('#'+id+'-form').serialize();
$.ajax({
type: "POST",
url: "ajax-process-form.php",
data: formData,
cache: false,
success: function(server_response){
$("#result").html(server_response).show();
}
});
return false;
});
Just reasoning... I might be wrong...
This code
$('#result').on('click', '.submitform'
binds to the click event on result and filters .submitform, then executes with this being the .submitform
when the success comes from the server, you are rewriting #result
$("#result").html(server_response)
if server_response does not contain a .submitform then next calls to the first onclick event will not execute because .submitform does not exist anymore inside #result
If this is the error, then to solve, use another div to show the result instead of #result or bind click to another separated, not contained within div
Arrgh - it was the structure after all. Although it worked the first time the table structure prevented it from working a second time. I have no idea why ... but there you go. Thanks for the help!
Related
I have an html table with id:#mytable in my asp.net-4.5 webpage, which is created in the c# site and sending to the aspx. In this Html table, at the end of each row there is a DELETE button like below:
...
html.Append("<td><input type=\"button\" runat=\"server\" value=\"Delete\" onclick=\"deleteRow(this)\" /></td>");
When this button is clicked, deleteRow(this) function is triggered with the code below:
btn.parentNode.parentNode.parentNode.removeChild(row);
When this line above runs, the regarding row is being immediately deleted and I do not see the row in the screen anymore.
This html table is represented as a datatable (javascript) like below:
$('#myTable').on('error.dt', function (e, settings, techNote, message) {
console.log('An error has been reported by DataTables: ', message);
}).DataTable({ fixedColumns: true,
"columnDefs": [{
"width": '60%',
"defaultContent": "-",
"targets": "_all"
}]
});;
This is also working well, my html table turns into a datatable. My problem is, after I delete a row from the table, if I change the sorting, or entry limit per page (10 by default) etc., I start to see the row I have just removed on the page, inside the table. It seems like my deleteRow function deletes the row not permanently. How can I fix this issue? Any help will be so appreciated.
EDIT: I needed to refresh the page after delete button click with JS: document.location.reload(true) and page_load re-reads the data, to fix the issue. Thanks #NTR and #J E Carter II
EDIT2: Using $('#myTable').DataTable().rows(row).remove().draw(false); while removing the row fixed the issue without the need of re-read data from DB. Check my answer.
As #NTR and #J E Carter II stated, re-reading the data solves the issue perfectly. However my main purpose here is not to re-read the data from the DB, I was looking for a solution providing that and found something. All I did is to change the row btn.parentNode.parentNode.parentNode.removeChild(row); into $('#myTable').DataTable().rows(row).remove().draw(false); and it works perfectly, after the table is refreshed the removed data is not seen on the screen. Here is the complete ajax function:
var row = btn.parentNode.parentNode;
$.ajax({
type: 'POST',
url: 'DataManagementPage.aspx/DeleteRowFromMyDatabase',
data: JSON.stringify({ id: id, grId:grID, city: city }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg)
{
$('#myTable').DataTable().rows(row).remove().draw(false);
}
});
The topic #NTR provided also offers a solution in server side: Deleting specific rows from DataTable
EDIT: Please note that DeleteRowFromMyDatabase returns true after the removal in DB.
Javascript is a client side technology it does not have the ability to communicate with a database. Your table is generated from the database with your server side .NET code. To accomplish what you want, you need to also delete the row in your database. To communicate with your server side code, you can use AJAX : AJAX introduction. AJAX is a big subject, you might have to do additional research.
So, in your deleteRow function you will have to delete the row client side like you are doing now and then, using ajax, delete the row server side.
Hope it helps !
You will have to reinitialize the data table with a fresh ajax call or mutated object. Your removal code is only taking out the rendered row, not the data that drives it, so when you call a redraw with sort, it is correctly rendering the state of the model, regardless of what mutations have occurred in the DOM.
I know you say you don't want to reread the data, but that is the correct thing to do. The remote data is the source of truth for your rendered datatable.
I'm having a problem getting modified text from input. The input is loaded with some text I get from a database and with an option i should take the onlyread attr off and change the values. Thats ok but when i click on the save button after writing something else in the inputs, it gets the old values with .val(). How can i get the new ones?
The code is something like this.
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
$.ajax({
type: "POST",
dataType: "html",
success: doSomething,
timeout: 4000,
error: someProblems,
url: "modules/mod.php",
data: {anInput: anInput, otherInput: otherInput}
});
I added the AJAX code just to mention that i need the values to do something. AJAX is working.
I know this can be done with a form but that will reload the page and I don't want that.
Sorry for my rusty English and thanks :)
EDIT: Perhaps I'm not correctly speaking when saying "change the values" what I'm doing is selecting the text and writing something else.
I show some information with the inputs, click a button that allows me to modify, type some new text in the inputs and then click "save"
HTML is genereted by another AJAX
<div class="infoVideo">
<input id="anInput" value="someTextFromDataBase">
<input id="otherInput" value="someTextFromDataBase">
<input type="button" id="btnMod">
<input type="button" id="btnSave">
</div>
If I erase and type something else in the input .val() is getting old someTextFromDataBase
Edit: As per a guess in my comments, there was more than one #anInput in the page so the code was only retrieving the value from the first one which was not the one being edited. The solution is to not have any duplicate id values in the HTML of the page.
I suspect that your code isn't really like you show. You are probably doing these:
var anInput = $("#anInput").val(); //gets old value
var otherInput = $("#otherInput").val(); //gets old value
only once and then trying to use anInput and otherInput much later when the form fields have already changed. You can get the current values by not caching those and just retrieving the current values when you need them by changing this:
data: {anInput: anInput, otherInput: otherInput}
to this:
data: {anInput: $("#anInput").val(), otherInput: $("#otherInput").val()}
That way, you are always retrieving the latest and greatest values right before your Ajax call.
Please confirm format of data returned by mod.php. The AJAX block is expecting to receive HTML formatted text dataType: 'html', -- but you are sending json, so is that what you are expecting back?
If this note doesn't reveal the solution, then please show us your doSomething function - that's where the returned data is handled.
Probably you've tried this already, but what happens if you do this:
var anInput = $("#anInput").val(); //gets old value
alert(anInput);
var otherInput = $("#otherInput").val(); //gets old value
alert(otherInput);
$.ajax({ //etc });
I am using jQuery ajax method to insert the data to database.
Able to insert the data successfully, and returning the newly inserted id.
Here the problem is, I am appending the new row immediately after submit (prior to insertion of database)
Keeping in mind that, the data will be inserted from background, without causing any delay to the user.
He must be able to keep adding rows, and they must be saved to DB in background.
$('#add-new-row').live('submit', function(){
var obj = $(this),
newdata = obj.find('.newdata');
$('#target').append('<div>newdata.val()+'</div>');
$.ajax({
url: '/insert/insertrow',
data: $(this).serialize(),
dataType: 'json'
// other settings
success: function(response) {
alert(response.id); // response contains the newly inserted id
}
});
}
But I need to attach the ID of new row to html for further processing.
Hence I am struck, to add this response.id to new row as one attribute.
In the above jQuery event I am appending the new row to the target as
<div>New row</div>
It should become something like this after it got inserted to database.
<div rowid="123">New row</div>
Any suggestions to achieve this scenario.
How about putting this in the success:
$("#target div:last-child").attr("rowid", response.id)
I have 2 Drop Downs in a HTML form. The first dropdown needs to be populated with a list of usernames present in the DATABASE.
Secondly, Depending upon the selection made in the first drop down, I then need to run another JS script to make another call to the DB to retrieve the list of associated addresses to that username.
Can you please let me know whats the best way to achieve this objective?
1) How can I run a JSscript before the HTML form loads to return that list?
2) Should I get both the usernames and associated addresses in one Db call or just get the usernames first and then use onChange event on the first dropdown to execute the second call?
Any code would be most appreciated.
Thanks
well if you have all the info in same table then why dont you get all data in one go by querying as to the DB and then sort and put up data in the elements the way you want.
the other way will need to query DB 2 times.
here you can create your HTML to server call OR you can make HTML locally.
i have created options for selectbox at server and innerhtml to locally.
<select id="selectbox1" onchange="getData(this)"></select>
<select id="selectbox1"></select>
$(document).ready(function() {
$.ajax({
url: 'http://localhost/getUsername.php',
success: function(data) {
$('#selectbox1').html(data);
alert('Load was performed.');
}
});
});
function getData(selData) {
$.ajax({
url: 'http://localhost/getSecoundCall.php?id='+selData,
success: function(data) {
$('#selectbox2').html(data);
alert('Load was performed.');
}
});
}
Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?
I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed: