How to pass/generate table with parameters from one page to another - javascript

Hi i having a scenario where i am generating a dynamic table along with the dynamic button and when ever user clicks that button it has to get that row value and it has generate another dynamic table by taking this value as parameter .Till now i tried generating a dynamic table and with button and passed a parameter to that function here i stuck how to pass /accept a parameter to that function so that by using ajax call it can generate another dynamic table.
$.ajax({
type: 'GET',
url: xxxx.xxxxx.xxxxx,
data: "Id=" + clO + Name_=" + cl+ "",
success: function (resp) {
var Location = resp;
var tr;
for (var i = 0; i < Location.length; i++) {
tr = tr + "<tr>
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Amount + "</td>";
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Name + "</td>";
tr = tr + '<td><input type="button" class="nav_button" onclick="test(\'' + Location[i].Amount + '\',\'' + Location[i].Name + '\')"></td>';
tr = tr + "</tr>";
};
document.getElementById('d').style.display = "block";
document.getElementById('Wise').innerHTML = "<table id='rt'>" + "<thead ><tr><th style='height:20px'>Amount</th>" + "<th style='height:20px'>Name</th>""</tr></thead>"
+ tr + "<tr><td align='left' style='height:20px'><b>Total:"+ TotBills +"</b></td><td style='height:20px' align='right'><b></b></td></tr>" +
"</table>";
document.getElementById('Wise').childNodes[0].nodeValue = null;
},
error: function (e) {
window.plugins.toast.showLongBottom("error");
}
function test(value,val1,val2) {
navigator.notification.alert(value + ";" + val1 + ";" + val2);
// here i have to pass the another ajax by basing on the the onclick
}
so here in the function i have to pass the parameters and have to display in the new page and how is it possible ?

To pass data from a page to another your best bet is localStorage and SessionStorage;
SessionStorage - Similar to a cookie that expires when you close the browser. It has the same structure as the localStorage, but there is no way to change its permanence time, whenever closing will be deleted.
LocalStorage - This is similar to a cookie, but it never expires, so while there were records in the AppCache for that domain, the variable will exist (unless the user creates a routine to remove it).
Both attributes were added by HTML5. The above items called web storage. But there are other forms of local storage through HTML5, such as WebSQL database, Indexed Database (IndexDB), as well as conventional files (File Access).
Ex:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Is it what you meant ?

It's unclear what you're after, but I think I see where you're headed. From the code you included, it seems like you want something like this instead:
// This will take the user to a separate page, passing your parameters
function test(val1,val2) {
window.location.href("/UrlGoesHere?Amount=" + val1 + "&Name=" + val2);
}
Another option, based on what you've said, is to redraw the table. You could do that with something like this:
function test(val1,val2) {
$.ajax({
type: 'GET',
url: "/UrlGoesHere",
data: "Amount=" + val1 + "&Name=" + val2,
success: function (resp) {
// redraw table here
}
});
}

Related

PHP generated option list only appearing on first Ajax dynamically generated container

I am having an issue where my php generated select/option list is not applying to all of my dynamically generated blocks/containers. It only adds the PHP select to the last container/block instance, despite being called for each container. When troubleshooting with alerts it seems to run through all of the iterations prior to adding the containers/blocks and generating the select, hence why it always appears on the last only-
n = -1
function addDiv() {
n++;
So, a brief overview - on page initialize the code will get how many entries are in the database within a certain criteria and apply that number to 'length', which then runs the function addDiv() that many times. Usually, when adding a block one at a time via button it will populate the created block with a Select/list of Options via php in the addDiv() function, however when automating this with a loop ( the initialize() function ) the above issue occurs.
$( document ).ready(function() {
initialize();
});
function initialize() {
$.ajax({
url: 'get-entries.php',
type: 'POST',
dataType: 'text',
cache: false,
success: function(data) {
result = data;
var arrayJson = JSON.parse(data);
console.log(arrayJson);
length = arrayJson.length;
console.log(length);
for(var i = 0; i < length; i++) {
addDiv();
};
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
};
here is the addDiv related code with some redactions to make it easier to read.
var n = -1;
function addDiv() {
n++;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + n).html(data);
});
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}
and finally here is the contents of the PHP file for generating the option list based off of json data -
<?php
$json = file_get_contents("../ticker/full.json");
$decode = json_decode($json, true);
sort($decode);
echo '<select name="coinname">';
foreach($decode as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
?>
I know this is messy and may require a bit of an in depth read through, so I appreciate anyone taking the time to look.
Is there anything glaringly obvious that can help nudge me in the right direction? I have tried breaking the 'addDiv()' calls within initialize() by wrapping 'addDiv()' with a setTimeout function, but no joy.
it should work with this (I named the arguments differently for comprehension, but index and index_t can all be named n):
var n = -1;
function sendToGenerator(index){
var index_t = index;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + index_t).html(data);
}
);
}
function addDiv() {
n++;
sendToGenerator(n);
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}

Javascript dynamic switch doubling Ajax calls

I am having a problem with a jQuery click function. When a user clicks a HTML button, my jQuery dynamically loads some styled checkbox's/toggle switches based upon their corresponding on/off state stored in a database.
I then added a click function to each dynamically loaded toggle switch so that when a user clicks it, it updates the database with the new state, it then, with Ajax, calls the GetAllSwitches function again loading the current state of the switches from the DB back into the resultScreen.
It works, updates the state in the DB correctly, but the program remembers previous 'clicks' and runs them all again followed by the new click state every time a user clicks. So on the first click it makes 1 http request, 2nd 2, 3rd 4, 4th 8 etc. The problem being after a few clicks the ajax calls become huge.
I'm not that experienced in Javascript so I am aware my code is verbose and I am clearly missing something, but are there any fixes or better approaches to this?
In summary what I want to achieve is:
User clicks allSwitches
Ajax call to a database which returns all objects with a toggle switch on screen
Have the toggle switch's clickable which updates the database with new state
Allow the switches to be clicked as many times as the user likes only making one update to the DB
HTML
<fieldset>
<legend> Get All Lights Dynamically</legend>
<input type="button" value="Show All" id="allSwitches"/>
</fieldset>
<fieldset>
<div id='resultScreen'></div>
</fieldset>
JavaScript
$(document).ready(function(){
$("#allSwitches").click(function(){
$.ajax({
url: 'GetAll',
type: 'GET',
dataType: 'text',
success: function(data) {
getAllSwitches(data)
});
});
});
function getAllSwitches(data){
var tr;
myData = $.parseJSON(data);
for(var i = 0; i < myData.length; i++){
tr = $('<tr/>');
if(myData[i].state=="On"){
tr.append('<div id="togs' + i + '">' + '<label class="switch">' +
'<input type="checkbox" class="' + myData[i].lightName +'" checked>' +
'<div class="slider round"></div>'
+'</label>' + '</div>');
tr.append("<td>" + myData[i].lightName +
" is " + myData[i].state + "</td>");
$('#resultScreen').append(tr);
var className = '.' + myData[i]lightName;
var lightName = myData[i].lightName;
var state = "Off";
upTog(className, lightName, state);
} else if (myData[i].state=="Off"){
tr.append('<label class="switch">' +
'<input type="checkbox" class="' + myData[i].lightName +'" >' +
'<div class="slider round"></div>'
+'</label>');
tr.append("<td>" + myData[i].lightName +
" is " + myData[i].state + "</td>");
$('#resultScreen').append(tr);
var className = '.' + myData[i].lightName;
var lightName = myData[i].lightName;
var state = "On";
upTog(className, lightName, state);
}
}
}
function upTog(className, lightName, state){
$(document).on('click', className, function() {
$.ajax({
url: 'UpdateLight?lightName=' + lightName + "&state=" + state,
type: 'POST',
dataType: 'text',
success:function(data){
$.ajax({
url: 'GetAll',
type: 'GET',
dataType: 'text',
success: function(data) {
$('#resultScreen').empty();
getAllSwitches(data);
}});
}
})
});
}
Many thanks.
The easiest way to do it is to unbind the previous click before set the new one.
Change upToge() body like this:
$(className).unbind( "click" );
$(className).on('click', function () {
/* Your ajax call here */
});
You're adding the click handler to the className, which is not changing when you empty the #resultsScreen div. You can see how the handlers pile up in this jsbin: http://jsbin.com/hizigutogi/edit?js,console,output (fill the div, click the red box, empty it, fill it again, and click it a few more times)
Try passing the reference to the jQuery object tr into upTog and adding the click handler onto it directly, instead of attaching it to the class name.

How to pass a specific object to a function through an html link?

Currently I am working on a site where I receive a list of objects from a data base and I am listing them in a pop-up table. I'd like one column of the table to list the object id and another to list links which call a function for that specific object. My issue is that I do not know how to do this when appending this data to a table.
Any ideas?
var tableContent ="<tr>";
for( var i =0; i<results.length ; i++)
{
tableContent += "<td>" + results[i].get("id") + "</td>"
tableContent += "<td>" + "<a>Open ID Contents</a>" + "</td>"
//I want this link to pass results[i] to a function^
}
tableContent += "</tr>"
$("#List").append(tableContent)
You can construct your a items in this way:
var $a = $('<a class="hasPopupData">...</a>');
$a.data('popup', { /*Your data goes here */ });
$a.appendTo($parent);
And then handle clicks using code like this:
$parentTable.on('click', 'a.hasPopupData', function(){
var $a = $(this),
data = $a.data('popup');
createPopup(data);
return false;
});
Note that jQuery attaches data to DOM node in ‘native’ presentation, without converting them to JSON first.
There are a variety of ways. A simple way is to pass the variable as JSON.
var js = "afunction('" + JSON.stringify(results[i]) + "');return false;"
tableContent += "<td>" + '<a onclick="' + js + '">Open ID Contents</a>' + "</td>"

displaying a jquery variable on another page

Ok, so I have a table with each row having check boxes at the start of each table row. When a user clicks the table rows he/she wants to display and hits the submit button I want those table rows to show up on another page. I am doing this by creating a variable just like this:
$('#submit').click(function(){
var data;
var title = $('#dimTableTitle td').html();
data = '<table id="dimTable">';
data += '<tbody>';
data += '<tr id="dimTableTitle">' + '<td colspan="100">' + title + '</td>' + '</tr>'
data += '<tr id="dimHeading">';
$("#dimHeading").find('td').each(function(){
data += '<td>' + $(this).html() + '</td>';
});
$('#dimTable tr').has(':checkbox:checked').each(function(){
data += '<tr>'
$(this).find('td').each(function(){
data += '<td>' + $(this).html(); + '</td>'
});
data += '</tr>'
});
data += '</tr>'
data += '</tbody>';
data += '</table>';
});
The variable 'data' displays just fine on the original page but when I try and load it into a new div or other container on a different page I only receive the entire table, not the selected table rows. I want to display that new variable onto a new page that pops up when a user clicks on the submit button. Any help would be appreciated.
You can send data with post method, (async)
jQuery.ajax({
url: "a.php?" + params,
async: false,
cache: false,
dataType: "html",
success: function(html){
returnHtml = html;
}
});
Note 1: Source code is written just to give you ideas.
Local storage is the way to go.
http://www.w3schools.com/html/html5_webstorage.asp

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources