im new to Javascript and im struggling with this question for a while.
I have a dynamic jquery table and my goal is to hyperlink one row of that table (the row data) to a .php page to make some queries.
My objective is something like this:
for example, in the table
data info money name ID
20161001 ... 34 test 1010
20161002 .... 20 dddd 111
20161003 ... 12 .... .....
users could press 20161001 or 20161002 and this would link to a detailed table with all the info of this day
My first problem is to reach the object inside the array of data.
Every time i try to reach data i got something like : [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
The only way i could reach them was from:
JSON.stringify(data[i])
i made a for statement but this return all the info from table and i just need the data from the row: Data.
for my dynamic table i get the headers from :
var keys=[];
for (var key in data[0]) {
keys.push(key);
}
I also try to combine this 2 ways to reach the info but no success.
My ajax code:
$.ajax({
type: 'post',
url: "data.php",
dataType: "json",
data: $(this).serialize(),
success: function(data) {
console.log(data);
$('#btn-load').click(function(e) {
var keys=[];
for (var key in data[0]) {
keys.push(key);
}
dt = dynamicTable.config('data-table', //id of the table
keys, //field names
null, //set to null for field names to be used as header names instead of custom headers
'no data...');
dt.load(data);
});
(Dynamic table with code of this page:
Dynamically update a table using javascript)
I need to reach this info, link him and pass the value into a php page.
I don't know if this method is the more appropriate so if someone can give me some lights i would appreciate.
Thanks
Assuming you want to pass the first column value of the row into your php function you can just try this.
Bind a click event to your table tr using event delegation (as you said it's a. Dynamic table) and extract the first td value on click.
$("#yourTableId").on("click","tr",function(){
var data = $(this).find("td:eq(0)").text();
alert(data); //test
});
$("#data-table").on("click","tr",function(){
var data2 = $(this).find("td:eq(0)").text();
window.open("teste.php?data2="+data2,'_blank','toolbar=0,location=no,menubar=0,height=400,width=400,left=200, top=300');
console.log (data2);
Thans for the help Reddy . This solve the problem, i pass the data trough the Window.open ;)
Related
I'm trying to set up a function using jquery/php where a user selects a checkbox in a row with a specific ID (the id matches the primary key of the row data in my database), stores each row ID into an array, and then upon clicking the "compare selected rows" button passes it to a new page where a table of results is displayed with only those selected rows.
each input looks like this
<input type='checkbox' id='$id' class='compareRow'></input>
I am pretty novice at jquery and was planning to use a variation of a previous script I had put together to display dynamic row data in a modal. I am not sure if this code is relevant at all but it also passes the row id to another php page in order to query the database. Mind you this has only been used for single queries in the past where this new function would need some sort of foreach statement at the query level in order to process the array of IDs, im sure.
Heres the script I've been trying to tweak
$(function(){
$('.compareRow').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'query.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
success : function(r)
{
other code?
});
}
});
});
});
I know that there is much more needed here but this is just what I have so far, any help would be greatly appreciated.
Update, so I've created the page and have the following:
in my compareSelected.php I have the following code:
if(isset($_POST['post_id'])){
$compare_received = $_POST['post_id'];
}
print_r($compare_receive);
It returns undefined index.
I also modified the code to change to that page after like so:
$('.compareRowButton').click(function(){
var ids = [];
//loop to all checked checkboxes
$('.compareRow:checked').each(function(){
//store all id to ids
ids.push($(this).attr('id'));
});
$.ajax({
type : 'post',
url : 'compareSelected.php', //query
data : {post_id:ids}, // passing id via ajax
success : function(r)
{
window.location = 'compareSelected.php';
}
});
});
Not sure why it won't pick up the array values.
If you're set on your current implementation, you could maintain a reference to the data returned by each ajax call in the rows array. Later, you could implement a button that fires a function to append the row data to your table. Of course, you may need to parse the data returned by the request prior to appending.
$(function(){
var rows = [];
$('.compareRow').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'query.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
success : function(data){
rows.push(data);
}
});
});
$('.displayTable').click(function(){
// append to table or divs
});
});
I would suggest you avoid a page reload here. Or, if you must, make the Ajax request on the following page. You want to avoid tightly coupling your logic between different jQuery modules. Ajax should be utilized to load data asynchronously, without requiring a page reload.
On your code. your sending ajax request everytime you click the checkbox.
better to make another button or something before sending ajax request.
$('SOME_ELEMENT').click(function(){
var ids = [];
//loop to all checked checkboxes
$('.compareRow:checked').each(function(){
//store all id to ids
ids.push($(this).attr('id'));
});
$.ajax({
type : 'post',
url : 'query.php', //query
data : {post_id:ids}, // passing id via ajax
success : function(r)
{
other code?
});
}
});
});
I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.
I have a jsp file where on a button click a bunch of rows shows up in a html table format.
The rows have checkboxes as well. When I click a checkbox and hit another button i am able to retrieve the selected row tags and push them into an array.
How can I pass this array to the servlet\scriptlet.
Array consists of tags like so: '< td > hi < /td> <td>ho</td>','< td > hi < /td> <td>ho< /td>',....
I included json2.js and tried stringify but servlet always comes back saying null when i use request.getparametervalues()
i also dont have a submit form so that rules out the submit form part of the coding.
Any and all advices very much appreciated.
code in js:
$.ajax({
type: 'POST',
url: 'book.jsp',
data: JSON.stringify({ nameParameter: colheader }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success:function(data){alert(data);},
error:function(){alert('error');}
});
Code in scriptlet book.jsp
String[] arrayData=request.getParameterValues("nameParameter");
System.out.println("########nameParameter"+arrayData);
I found a way to do it.
I add a rowid to each checkbox with the value of the primary key.
On selected a checkbox I post the rowid's to the scriptlet using the below
$.post('target.jsp', { id: selectedrows });
selectedrows is an array of selected rowids.
I set the resultset obtained into the session in the jsp.
I retrieve the resultset from the session in my scriptlet (target.jsp) and filter based on my selected rowids. That way I have all the values and need not pass the entire rowtag.
Alternatively you can query the database again with the selected rowid's, I chose not to do it as my resultset does not hold more than 100 rows.
I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}
I am currently asynchronously fetching json documents to update elements in a few html pages. My current approach seems less that elegant. For many pages I just need to update an element on the HTML page that corresponds to a key in the being returned in the json document. I'm looking for a simple jquery/javascript function that updates text boxes and other simple elements whenever an html element name in the fetching page matches a key returned in the json document.
The ideal function would fetch the json document when the html page first loads and then fetch the json document again every minute after that. The idea is to be able to update additional html elements just by adding additional name/value pairs in returned json document.
The following should do the trick. Assuming, I understood what you were requesting.
function updateElements() {
function handleJSON(data) {
for (key in data) {
if ( ! data.hasOwnProperty(key)) {
continue;
}
$('#'+key).html(data[key]);
}
};
$.ajax({
url: your_url,
dataType: 'json',
data: data,
success: handleJSON
});
};
setInterval(updateElements, 60000);
Assuming jdata contains the JSON data, the following will replace document elements
whose ids correspond to the jdata keys.
var k, kel;
for (k in jdata) {
if (jdata.hasOwnProperty (k) && (kel = document.getElementById (k))) {
k.innerHTML = jdata[k];
}
}