How to refresh a table without creating a separate jsp? - javascript

I have a table and one search fields, based on what is entered in the search fields the contents of the table are refreshed and if nothing is entered in the search fields the full table is loaded. Here when the user clicks on Go button the ajax call is made.
Currently, I have two jsp as below:
MAIN JSP
<script type="text/javascript">
$(document).ready(function() {
$( "#go-user" ).click(function() {
var userId = $('#usrId').val();
alert(userId);
$.ajax({
url: 'popUserSelect', // action to be perform
type: 'POST', //type of posting the data
data: { userId: userId }, // data to set to Action Class
dataType: 'html',
success: function (html) {
alert(html);
$('#load-user').html(html);
//document.getElementById("leftDiv").innerHTML=html; //set result.jsp output to leftDiv
},
error: function(xhr, ajaxOptions, thrownError){
alert('An error occurred! ' + thrownError);
}
});
return false;
});
});
</script>
<s:form theme="simple">
User Id : <s:textfield name="userId" id="usrId" theme="simple"/>
<s:submit action="popUserSelect" key="Go"></s:submit>
</s:form>
<div id="load-user">
<table width="100%">
<thead>
<tr>
<th>Select</th>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<s:iterator value="userSupList" >
<tr>
<td><input type="radio" class="RadioButton" name="userRadio" value='<s:property value="USR_AMLUSERNAME"/>' /></td>
<td><s:property value="USR_AMLUSRID"/></td>
<td><s:property value="USR_AMLUSERNAME"/></td>
<td><s:property value="USR_ROLEID"/></td>
<td><s:property value="USR_LOCATIONID"/></td>
</tr>
</s:iterator>
</tbody>
</table>
</div>
<input type="button" value="Submit" onclick="buttonClick('SubmitUser')"/>
<input type="button" value="Cancel" onclick="buttonClick('Close')"/>
Refresh Jsp:
<table width="100%">
<thead>
<tr>
<th>Select</th>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<s:iterator value="userSupList" >
<tr>
<td><input type="radio" class="RadioButton" name="userRadio" value='<s:property value="USR_AMLUSERNAME"/>' /></td>
<td><s:property value="USR_AMLUSRID"/></td>
<td><s:property value="USR_AMLUSERNAME"/></td>
<td><s:property value="USR_ROLEID"/></td>
<td><s:property value="USR_LOCATIONID"/></td>
</tr>
</s:iterator>
</tbody>
</table>
Is there any way that I can avoid using two jsp for refreshing and refresh the jsp on the same main jsp itself?

You have to give your table an ID:
<table width="100%" id="myTable">
...
</table>
And adapt your AJAX call:
$.ajax({
url: 'originalPage', // use original page here
type: 'POST',
data: { userId: userId },
dataType: 'html',
success: function (html) {
// get the content of #myTable from the AJAX result
var tableContent = $("#myTable", html).html();
// set the content of #myTable to the result of the AJAX call
$('#myTable').html(tableContent);
},
error: function(xhr, ajaxOptions, thrownError){
alert('An error occurred! ' + thrownError);
}
});
jQuery can take the target to use as second parameter, which is used in $("#myTable", html). This way, it does not search the current document for #myTable, but the document returned from the AJAX call.
The disadvantage of this that the whole original page needs to be loaded through AJAX, although only one minor part of it is used.

Related

How to use buttons with different Values but same ID for jQuery?

I have a table which generated by PHP and MySql. One of the column will have buttons which will have values which will be used for sending a data to another PHP file using AJAX. But I am now facing a problem that id(s) can have only unique value.
Will it be possible to use same ID for buttons with different values.
Here is a dummy data of HTML (Output given by PHP).
<table>
<tr>
<th>Serial No.</th><th>File Name</th><th>Action</th>
</tr>
<tr>
<td>1</td><td>Physics Notes</td><td><button id="request" value="1">Download</button></td>
<tr>
<tr>
<td>2</td><td>Chemistry Notes</td><td><button id="request" value="2">Download</button></td>
<tr>
<tr>
<td>3</td><td>Mathematics Notes</td><td><button id="request" value="3">Download</button></td>
<tr>
</table>
Now I want when any of the buttons in the 3rd columns are clicked, their values to be receive in the jQuery variable "file".
And then the values will be sent to a PHP file via AJAX.
Here is my jQuery and AJAX code.
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#request").on("click",function(e){
e.preventDefault();
var file = $(this).val();
$.ajax({
url : "downloadfile.php",
type : "POST",
data : {file:file},
success : function(data){
alert("Thank you for using our service");
}
});
})
});
</script>
As said in Comment, an ID shall always be unique. So use class in your case.
<td><button class="request" value="2">Download</button></td>
and
$(".request").on("click", function(e) {
Note Please note that you haven't closed your tr they are missing /
Demo
$(document).ready(function() {
$(".request").on("click", function(e) {
e.preventDefault();
var file = $(this).val();
$.ajax({
url: "downloadfile.php",
type: "POST",
data: {
file: file
},
success: function(data) {
alert("Thank you for using our service");
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Serial No.</th>
<th>File Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>Physics Notes</td>
<td><button class="request" value="1">Download</button></td>
</tr>
<tr>
<td>2</td>
<td>Chemistry Notes</td>
<td><button class="request" value="2">Download</button></td>
</tr>
<tr>
<td>3</td>
<td>Mathematics Notes</td>
<td><button class="request" value="3">Download</button></td>
</tr>
</table>

Javascript Get Value from Classes

I'm trying to use this for my class homework, I am still learning.
This script is made to check if a site down or not.
What I'm trying to achieve is to use this same script and get statuses for every website on the table without using script all over again all 3 websites.
I added classes but I do not know how to get them to script. I commented on script so it will be easier for you to understand. Any solution for this? Any input would be appreciated.
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td>Google</td>
<td id="website"></td> <!-- This is already working. -->
</tr>
<tr>
<td>Twitter</td>
<td id="website" mywebsite="https://Twitter.com"></td> <!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td>Facebook</td>
<td id="website" mywebsite="https://Facebook.com"> <!-- This is what I'm trying to achive. -->
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
var site = 'https://google.com';
// var site = 'https://google.com';
$.ajax
({
url: site,
dataType: "jsonp",
statusCode: {
200: function (response) {
$('#website').html('yes');
console.log(response);
},
404: function (response) {
$('#website').html('no');
console.log(response);
}
}
});
</script>
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td>Google</td>
<td class="website" data-mywebsite="https://google.com"></td> <!-- This is already working. -->
</tr>
<tr>
<td>Twitter</td>
<td class="website" data-mywebsite="https://twitter.com"></td> <!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td>Facebook</td>
<td class="website" data-mywebsite="https://facebook.com"> </td>
</tr>
</tbody>
</table>
$(document).ready(function(){
$(".website").each(function(){
var site = $(this).attr("data-mywebsite");
var thissr = $(this);
$.ajax
({
url: site,
dataType: "jsonp",
statusCode: {
200: function (response) {
thissr.html('yes');
},
404: function (response) {
thissr.html('no');
}
}
});
});
});
Try this code. Here is a fiddle
You need to use class and loop through each of them to send AJAX request.
As you know Ajax is an asynchronous call to server,
So if you want to execute ajax call in loop and want to update something based on your ajax call, then you must need a context for which you are calling ajax,
Try something like below,
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td>Google</td>
<td class="website" data-mywebsite="https://google.com"></td> <!-- This is already working. -->
</tr>
<tr>
<td>JQuery</td>
<td class="website" data-mywebsite="http://jquery.com/"></td> <!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td>Stackoverflow</td>
<td class="website" data-mywebsite="https://stackoverflow.com/"> <!-- This is what I'm trying to achive. -->
</tr>
</tbody>
</table>
$(document).ready(function(){
$(".website").each(function(){
var site = $(this).attr("data-mywebsite");
var thissr = $(this);
$.ajax
({
url: site,
dataType: "jsonp",
context : thissr,
statusCode: {
200: function (response) {
$(this.context).html('yes');
},
404: function (response) {
$(this.context).html('no');
}
}
});
});
});
https://jsfiddle.net/cdL997a6/1/

Ajax Get HTML Value

I'm trying to use this for my class homework, I am still learning.
This is a simple script that check if a site down or not.
What I'm trying to achieve is to use this same script and get statuses for every website on the table without using script all over again. Any solution for this? Any input would be appreciated.
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td>Google</td> <!-- This is already working. -->
<td id="website"></td>
</tr>
<tr>
<td>Twitter</td>
<td id="website" mywebsite="https://Twitter.com"></td> <!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td>Facebook</td>
<td></td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
var site = 'https://google.com';
// var site = 'https://google.com';
$.ajax
({
url: site,
dataType: "jsonp",
statusCode: {
200: function (response) {
$('#website').html('yes');
console.log(response);
},
404: function (response) {
$('#website').html('no');
console.log(response);
}
}
});
</script>
Instead of using id="website" because an id is an unique value, use class="website" in your html.
<td class="website"></td>
IN your jQuery the change is simple instead of using # use . is used for references to classes (ie. website), like so:
$(".website").html("yes");
Don't forget to modify all locations. This will execute for all places where class="website" is defined.
Put your url on data attribute and loop to get value from td like this.
$('table > tbody > tr').find('td').each(function() {
var site = $(this).data('url');
$.ajax({
url: site,
dataType: "jsonp",
statusCode: {
200: function(response) {
$('#website').html('yes');
console.log(response);
},
404: function(response) {
$('#website').html('no');
console.log(response);
}
}
});
});
<table>
<thead>
<tr>
<th style="width:250px">Website</th>
<th style="width:250px">Is it live</th>
</tr>
</thead>
<tbody>
<tr>
<td data-url='https://google.com'>Google</td>
<!-- This is already working. -->
</tr>
<tr>
<td data-url="https://twitter.com/">Twitter</td>
<!-- This is what I'm trying to achive. -->
</tr>
<tr>
<td data-url="https://www.facebook.com/">Facebook</td>
</tr>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

Table with two buttons. One jQuery-ajax doesn't replace <tbody> of <table>, but instead redirects browser to ajax url

EDIT: I originally simplified my code, hoping to isolate my problem, but I see I need to show the unsimplified code to discover my problem; so I'm replacing the HTML and JavaScript with the "full version", and have edited my description to include new information.
I have a table with two Buttons.
One button works fine: it triggers a jQuery overlay form so the user can enter data for a new row. AJAX then removes the "old" < tbody > and replaces it with a new < tbody > (with the new row added). That works fine. --critically, it also stores the new row into a database.
The other button is responsible for removing rows that have been checked by the user. jQuery AJAX does remove the selected rows from the database, but instead of replacing the "old" < tbody > with the new (now smaller) one, it loads the AJAX url into the browser, which shows the raw new set of rows that were intended to be put into the < tbody >. Using the back button and F5-ing shows that the rows were indeed removed.
I don't know how to 'blend' these buttons into one table.
Here is the jQuery:
// opens a pop-up form as an overlay (id: #box_form) that has its own buttons
$('#addy').click(function(e){
//e.preventDefault();
$('#box_form').dialog('open');
});
$( "#datepicker" ).datepicker(
{altFormat: "yy-mm-dd"}
);
$('#box_form').dialog({
autoOpen: false,
height: 340,
width: 400,
modal: true,
buttons: [
{
text: "Cancel",
click: function() {
$(this).dialog("close");
}
},
{
text: "Submit",
click: function() {
var symbol = $("#symbol").val();
var quant = $("#quant").val();
var price = $("#price").val();
var datepicker = $("#datepicker").val();
var fee = $("#fee").val();
var account = $("#account").val();
var owner = $("#owner").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'symbol='+ symbol + '&quant='+ quant + '&price='+ price + '&datepicker='+ datepicker + '&fee='+ fee + '&account='+ account + '&owner='+ owner;
if(symbol==''||quant==''||price==''||datepicker==''||fee==''||account=='')
{
alert("Please Fill All Fields");
}
else
{
$.ajax({
type: "POST",
url: "addPurch.php",
data: dataString,
cache: false,
success: function(result){
//document.getElementById("stocktablebody").innerHTML = result;
$("#stockstable tbody").html(result);
}
});
//close this little input form overlay
$( this ).dialog( "close" );
}
return false;
}
}
]
});
$('#selectAll').click(function(event){
$(this).closest('table').find('td input:checkbox').prop('checked', this.checked);
});
$('#removie').submit(function(event){
event.preventDefault();
var remove = $("#remove[]").val();
var owner = $("#owner").val();
var dataString = 'remove='+ remove + '&owner='+ owner;
//var url = "removePurch.php"; //$(this).attr('action');// this attribute's action (specified in <form> tag)
$.ajax({
type: "POST",
url: "removePurch.php",
data: dataString,
cache: false,
success: function(result){
//document.getElementById("stocktablebody").innerHTML = result;
$("#stockstable tbody").html(result);
}
});
return false;
});
Here is the HTML:
(First big div is for the Add button's jQuery pop-up; Second big block is the actual table.)
<!-- Pop-up form hidden by JavaScript until button is clicked -->
<div id="box_form" title="Add a purchase">
<form id="addsymbol" action="addPurch.php" method="POST"
name="addstock" enctype="multipart/form-data">
<input type="hidden" name="owner" id="owner" value="me" />
<table class="popuptable">
<thead>
<tr>
<td class="right"><label for="symbol">Symbol:</label></td>
<td><input type="text" name="symbol" id="symbol"></td>
</tr>
<tr>
<td class="right">
<!-- for="..." Specifies which form element a label is bound to -->
<label for="quant">Quantity:</label>
</td>
<td><input type="text" name="quant" id="quant"></td>
</tr>
<tr>
<td class="right"><label for="price">Price for each: </label>
</td>
<td><input type="text" name="price" id="price"></td>
</tr>
<tr>
<td class="right"><label for="fee">Fee: </label></td>
<td><input type="text" name="fee" id="fee"></td>
</tr>
<tr>
<td class="right"><label for="datepicker">Date
Purchased: </label></td>
<td><input type="text" name="datepicker" id="datepicker">
<!-- had real trouble getting data to POST, just made all names,ids === and it worked -->
</td>
</tr>
<tr>
<td class="right"><label for="account">Which account:
</label></td>
<td><select name="account" id="account">
<option value="note">must fix fee functionality</option>
<option value="FidelityIndividual">Fidelity Individual</option>
<option value="FidelitySEP">Fidelity SEP</option>
<option value="FidelityRoth">Fidelity Roth</option>
<option value="ScottradeIRA">Scottrade IRA</option>
</select></td>
</tr>
</thead>
</table>
</form>
</div>
<!-- Table with two buttons (Add-a-row and Remove-a-row), and a checkbox for each row, and a checkbox to "check all rows" -->
<table id="stockstable" class="center">
<thead>
<tr>
<th colspan="2">
<!-- this just triggers form to come up. Form has its own buttons -->
<input type="submit" id="addy" value="Add a stock purchase">
</th>
<th colspan="3">Activity Today</th>
<th colspan="2">Change Since Purchase</th>
<th colspan="3">Cost Basis</th>
<th colspan="3">Purchas Details</th>
<form action="removePurch.php" method="post"
enctype="multipart/form-data">
<input type="hidden" name="owner" id="owner" value="me" />
<th><button id="removie">Remove</button></th>
</tr>
<tr>
<th>Name</th>
<th>Symbol</th>
<th>Price</th>
<th>$ change</th>
<th>% change</th>
<th>Quantity</th>
<th>Purchase Price</th>
<th>Total Cost</th>
<th>Total % Change</th>
<th>Total $ Change</th>
<th>Fee</th>
<th>Account</th>
<th>Purchase Date</th>
<th><input type="checkbox" name="remove[]" id="selectAll"
value="all"></th>
</tr>
</thead>
<tbody>
<tr>
<td>International Business Machines</td>
<td>ibm</td>
<td>166.95</td>
<td>+3.10</td>
<td>1.86</td>
<td>1,986.88%</td>
<td>$158.95</td>
<td>8</td>
<td>8</td>
<td>71.00</td>
<td>7.00</td>
<td>note</td>
<td>07/16/2015</td>
<td><input type="checkbox" name="remove[]"
value="55a3436f5490c4ed4cbbe1a5"></td>
</tr>
<tr>
<td>Facebook, Inc.</td>
<td>fb</td>
<td>87.95</td>
<td>+2.07</td>
<td>2.35</td>
<td>999.38%</td>
<td>$79.95</td>
<td>8</td>
<td>8</td>
<td>71.00</td>
<td>7.00</td>
<td>note</td>
<td>07/30/2015</td>
<td><input type="checkbox" name="remove[]"
value="55a346745490c4ee4cbbe1a6"></td>
</tr>
</tbody>
</form>
</table>
I don't need the < form > tag in the table at all because JS has access to all the elements in the DOM.
in $('#removie').click(function(event) (I changed it from submit to click because it's no longer a form, but just a button), the checkboxes have to be "unpacked" or "discovered" by JavaScript, and put into a JavaScript array like so:
var remove = [];
$(':checkbox:checked').each(function(i){
remove[i] = $(this).val();
});
...it somehow knows which checkboxes, even though I removed the < form > tag.
The rest in that jQuery function is the same as the original question.
In the PHP, the checkbox data is received via POST only as a comma separated value, and has to be exploded into an array (oh, or not, depending on your code, really) like so:
$remove = explode(',', $_POST['remove']);
Profit.

I'm using jquery's $.Ajax method to pull json data but it won't render it to the page

I can get part of the data to render to the page (specifically: request, ack, and return_info) however it will not render my user data (user_id, name, session_token, photo_url). I need all user data stored to render in a table.
$(document).ready(function () {
$.ajax({
url: "http://url/getaccount",
type: 'GET',
dataType: "json",
data: {
'account': 'all'
},
}).then(function (data) {
$('.request').append(data.request);
$('.ack').append(data.ack);
$('.return_info').append(data.return_info);
$('user_id').append(data.user_id);
$('.name').append(data.name);
$('.session_token').append(data.session_token);
$('.photo_url').append(data.photo_url);
});
console.log();
});
Html
<table class="table table-striped">
<tr>
<td><b>User</b>
</td>
<td><b>Turbo User ID</b>
</td>
<td><b>Name</b>
</td>
<td><b>Session Token<b></td>
<td><b>Request</b>
</td>
<td><b>Ack</b>
</td>
<td><b>Return Info<b></td>
</tr>
<tr>
<td class="photo_url"></td>
<td class="user_id"></td>
<td class="name"></td>
<td class="session_token"></td>
<td class="request"></td>
<td class="ack"></td>
<td class="return_info"></td>
</tr>
</table>
I will be using this for several hundred users. I am not sure if I will need a for loop of not. Thank you!
<table id="myTable" class="table table-striped">
<thead>
<tr>
<th><b>User</b></th>
<th><b>Turbo User ID</b>
</th>
<th><b>Name</b>
</th>
<th><b>Session Token<b></th>
<th><b>Request</b>
</th>
<th><b>Ack</b> </th>
<th><b>Return Info<b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
$(document).ready(function () {
$.ajax({
url: "http://url/getaccount",
type: 'GET',
dataType: "json",
data: {
'account': 'all'
},
}).then(function (data) {
for(var i = 0; i < data.accounts.length; i++){
$('#myTable tbody').append("<tr>");
$('#myTable tbody').append("<td class=\"photo_url\">" + data.accounts[i].photo_url + "</td>");
$('#myTable tbody').append("<td class=\"user_id\">" + data.accounts[i].user_id + "</td>");
//etc...
$('#myTable tbody').append("</tr>");
}
});
console.log();
});

Categories