loading a element of same file through jquery - javascript

I have a file data.php, when a user clicks update the database is updated in background with jquery but in response i want to reload the particular table whose data was updated.
my html:
<div id="divContainer">
<table id="tableContainer" cellspacing='0' cellpadding='5' border='0'>
<tr>
<td>No.</td>
<td>Username</td>
<td>Password</td>
<td>Usage Left</td>
<td>%</td>
</tr><!-- Multiple rows with different data (This is head of table) -->
my jquery:
$('#UpdateAll').click(function() {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('<div id="divContainer" />').slideUp('500').empty().load('data.php #tableContainer', function() {
$(this).hide().appendTo('#divContainer').slideDown('1000');
});
}
});
});
Everything is working fine the database is getting updated and in success #response is getting loaded with success message but the table is not refreshing.

You already have a div with an id of divContainer but you are creating this element again
$('<div id="divContainer " />').slideUp....
you need
$('#divContainer')
.slideUp('500')
.empty()
.load('data.php #tableContainer', function() {
$(this).slideDown('1000');
});

$('#UpdateAll').click(function () {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function (response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('#divContainer').slideUp('1000').load('data.php #tableContainer', function () {
$(this).hide().appendTo('#tableContainer').slideDown('1000');
});
}
});
});

Related

How to submit dynamic data without form?

I am getting data as form of Java Bean and I am inserting each value into a table.
Values are retrieved as common way at first.
But I added some Javascript source, so that I can modify the value if I click any area near it.
Now I would like to save the data in database as well if there was any change after I modify.
How can I do that?
Here is my HTML code
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-editable>${engboardVO.word}</td>
<td data-editable>${engboardVO.dialogue}</td>
<td data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
And Javascript
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
/* var $input = $('<input style="width:500px; height:100px"/>').val( $el.text() ); */
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.replaceWith($input);
var save = function() {
var $td = $("<td data-editable />").text($input.val());
$input.replaceWith($td);
};
$($input).blur(function() {
save();
})
});
You can use ajax for submitting data without form.
I can see you are using jQuery library. So I am writing code based on this library.
In HTML:
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-name="word" data-editable>${engboardVO.word}</td>
<td data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
In javascript:
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.html($input);
var field_name = $el.attr('data-name');
var save = function() {
var $val= $input.val();
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
};
$($input).blur(function() {
save();
})
});
Then in server side, you can save fieldvalue as value of fieldname in your database.
Basically what we are doing here is:
Added an attribute data-name in td tag, its value can be related to your field name in table.
Get the name of attribute in javascript using var field_name = $el.attr('data-name');.
Using post request in ajax call passed the field_name and and value of this field to server.
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
Now in server side, you need to fetch this data as you fetch normally for post request in submit of a form and save this data in database.
url is same as action you provide in form tag.
Edit:
Check now. You were replacing the td, whereas you had to replace html inside td.
Don't worry if you don't have a form or can't have it for some reasons
You can still read the inputs of your web page and use them or send them to the server.
See below a simple example:
var inputs = document.getElementsByTagName('input');
var data = []
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
data.push(inputs[index].value)
}
var json = JSON2.stringify(data);
$.ajax({
type: "POST",
url: "your-api-url",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// done code
}
});

How to empty ajax data before sending it?

I have a form, when I submit it it creates an ajax function and then creates a table out of the data in the success. But knowing that my page is dynamic (without reloading the page I call the ajax function many times), but each time the data in the success doesn't get removed before generating more data. Is that normal? How can I empty the success data variable before sending the ajax?
Function :
function submitForm() {
if ($.fn.DataTable.isDataTable("#table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
data = {}; // like this maybe?
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}
Form :
<form method="GET" action="" class="form-horizontal" id="form" onsubmit="return false;">
<button type="submit" onclick="submitForm();">Update table</button>
</form>
Table :
<table class="table table-striped display nowrap col-md-12" id="achats_table">
<thead>
<tr style="border-bottom:2px dashed #ccc"></tr>
</thead>
<tbody></tbody>
<tfoot align="right">
<tr></tr>
</tfoot>
</table>
You have to empty the table in beforeSend,
function submitForm() {
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
if ($.fn.DataTable.isDataTable("#achats_table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}

PHP Serialize on ajax array Not Working

I have the following HTML fields being created inside a PHP look
<td><input type=\"checkbox\" name=\"investigator_id[]\" id=\"investigator_id\" value=\"$name_degree[$i]\">
<td><input type=text name=\"inv_rank[]\" id=inv_rank maxlength=\"2\" size=\"2\"></td>
<td><textarea name=\"inv_comm[]\" id=inv_comm rows=2 cols=20></textarea></td>
I am trying to save the data in these fields by calling a jquery function based on clicking on this button
Here is the script that is being called. I know that the js is being called because the "alert("now")" is poping up, but the dataString is not being populated correctly. I tested this on http://jsfiddle.net/ and it worked fine, but won't work on my site.
<script>
$(document).ready(function() {
$("#submit").click(function() {
alert("now");
var dataString = $("'[name=\"investigator_id\[\]\"]', '[name=\"inv_rank\[\]\"]','[name=\"inv_comm\[\]\"]'").serialize();
alert("ee"+dataString);
$.ajax({
type: "POST",
url: "save_data.php",
dataType: "json",
data: dataString,
success: function(data){
alert("sure"+data);
$("#myResponse").html(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error.");
}
});
});
});
</script>
Try this with the help of FormID like this:
<form method="post" id="yourFromID">
//Your form fields.
</form>
JS Code:
$("#yourFromID").submit(function (e){
e.preventDefault();
var dataString = $(this).serialize();
// then you can do ajax call, like this
$.ajax({
url: 'site.com',
data: dataString,
methodL 'post',
success: function(){...}
})
return false;
});

Hide and show the child div based on condition

I have a parent div with two child.When button clicks it shows only one div based on condition.
<div id="table">
<div id="result_table" >
</div>
<div id="new">
</div>
</div>
Am assigning the data to table depends on the data retrieved from the page.So i want to hide the result _table while the new table is visible.
$('#BUTTON').click(function(){
$.ajax({
url: PAGE.PHP,
type:'POST',
dataType: 'json',
success: function(data){
$("#result_table").html(data.table);
$("#new").html(data);
}
});
});
You can check data results
$('#BUTTON').click(function(){
$.ajax({
url: PAGE.PHP,
type:'POST',
dataType: 'json',
success: function(data)
{
if(data.table)
{
$("#result_table").show().html(data.table);
$("#new").hide();
}
else
{
$("#new").show().html(data);
$("#result_table").hide();
}
}
});
});

Display 'loading' image when AJAX call is in progress

I have the following jQuery Ajax call:
$.ajax({
type: "POST",
url: "addtobasket.php",
data: "sid=<?= $sid ?>&itemid=" + itemid + "&boxsize=" + boxsize + "&ext=" + extraval,
success: function(msg){
$.post("preorderbasket.php", { sid: "<?= $sid ?>", type: "pre" },
function(data){
$('.preorder').empty();
$('.preorder').append(data);
});
}
});
I want to display an image when the ajax call is in progress. How can I do that?
Thanks,
try this :
<script type="text/javascript">
$(document).ready(function()
{
$('#loading')
.hide()
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
});
</script>
<div id="loading">
Loading....
</div>
This will show the loading image each time you are doing an ajax request, I have implented this div at the top of my pages, so it does not obstruct with the page, but you can always see when an ajax call is going on.
Something along these lines (showLoadingImage and hideLoadingImage are up to you):
// show the loading image before calling ajax.
showLoadingImage();
$.ajax({
// url, type, etc. go here
success: function() {
// handle success. this only fires if the call was successful.
},
error: function() {
// handle error. this only fires if the call was unsuccessful.
},
complete: function() {
// no matter the result, complete will fire, so it's a good place
// to do the non-conditional stuff, like hiding a loading image.
hideLoadingImage();
}
});
You can display the image just before this call to $.ajax() and then hide/remove the image in the post handler function (just before your .empty()/.append(data) calls.
It works. I have tested it.
<script type='text/javascript'>
$(document).ready(function(){
$("#but_search").click(function(){
var search = $('#search').val();
$.ajax({
url: 'fetch_deta.php',
type: 'post',
data: {search:search},
beforeSend: function(){
// Show image container
$("#loader").show();
},
success: function(response){
$('.response').empty();
$('.response').append(response);
},
complete:function(data){
// Hide image container
$("#loader").hide();
}
});
});
});
</script>
<input type='text' id='search'>
<input type='button' id='but_search' value='Search'><br/>
<!-- Image loader -->
<div id='loader' style='display: none;'>
<img src='reload.gif' width='32px' height='32px'>
</div>
<!-- Image loader -->
<div class='response'></div>

Categories