How to render search results in a different page with Ajax - javascript

I have a web page configured with the search form in one php page and the table with search results in another and I have the following javascript function that renders the table with the search results:
function createRestaurantsTable() {
var table = document.createElement('table');
var str = '<table cellspacing="1" class="tablesorter">';
str += '<thead><tr><th>Nome</th><th>Morada</th><th>Distancia</th></tr></thead>';
for ( var i=0; i< restaurantArr.length; i++){
str += '<tr><td><center class="IDcell">' + restaurantArr[i].name + '</center></td><td><center>' + restaurantArr[i].address + '</center></td><td><center>' + restaurantArr[i].distance.toFixed(2) + ' m</center></td></tr>';
}
str += '</table>';
str += "<div id='pager' class='pager'>";
str += "<form>"
str += "<img src='Tools/jquery.tablesorter/addons/pager/icons/first.png' class='first'/>";
str += "<img src='Tools/jquery.tablesorter/addons/pager/icons/prev.png' class='prev'/>"
str += "<input type='text' class='pagedisplay'/>";
str += "<img src='Tools/jquery.tablesorter/addons/pager/icons/next.png' class='next'/>";
str += "<img src='Tools/jquery.tablesorter/addons/pager/icons/last.png' class='last'/>";
str += "<select class='pagesize'>"
str += "<option selected='selected' value='5'>5</option>"
str += "<option value='10'>10</option>";
str += "<option value='15'>15</option>";
str += "<option value='20'>20</option>";
str += "<option value='25'>25</option>";
str += "<option value='30'>30</option>";
str += "<option value='35'>35</option>";
str += "<option value='40'>40</option>";
str += "<option value='45'>45</option>";
str += "<option value='50'>50</option>";
str += "</select>";
str += "</form>";
str += "</div>";
document.getElementById('restaurants_table').innerHTML = str;
$("table").tablesorter({headers: { 0:{ sorter: false }, 1:{ sorter: false }, 2: { sorter: false }}, widthFixed: true ,widgets: ['zebra']}).tablesorterPager({container: $("#pager")});
$('tr').click(function(event) {
var id = $(this).find(".IDcell").html();
if(id) {
window.location = "index.php?action=register_details&details_view_id=" + id + "&operation=v";
}
});
}
I have a lot more JavaScript code but i think this is enough to show my problem.
How do i render the table if the search form is in another php page?
Thanks in advance!

Firstly, you might want not to mix three techniques and try to use just one:
Writing HTML as string can be replaced with JQuery. For instance:
$("<div>").attr("id", "pager").append(...)
Addressing element by Id by native javascript can be replace with JQuery. (The first technique is faster, but this is rather about simplicity and using one technique instead of mixing them. For inst.:
$("#restaurant_table).html(insertedHtml);
You might event want to generate your pager like this:
$("<div>").attr("id", "pager").append(...).appendTo("#restaurant_table");
I guess you should address the tablesorter at least by its class:
$("table.tablesorter")
If you generate the structures on-the-fly, you might rather use "live" binder instead of the click binder - the click binder will address only those, which are already constructed by the browser:
$("table.tablesorter tr").live("click", function(event) {...});

You would probably pass the table/form to the other page with a POST.

Related

How to add a dropdown list to each rows with values using jquery datatable in asp.net c#

I want to add the dynamic dropdown list to each row when I click the add button and I have written this below code to achieve this and values are coming but not like dropdown list
example code is :-
var ddlInputParameters = $("<select class='input-small' id='ddltype'></select>");
$.each(data.d, function (key, value) {
if (value.Type == "inputparameters") {
//var option = $("<option />");
var option = $("<option></option>");
option.html(value.TypeData);
option.val(key);
ddlInputParameters.append(option);
}
});
//Initially When the page is loaded I'm checking the length and adding the records to jquery table
if ($("#EntryParametersTableDataID,#EntryParametersTableRightDataID tbody").children().children().length == 1) {
var trd = "";
trd += "<tr>";
//trd += "<td hidden='hidden'><button class = 'btn btn-danger btn-sm'> delete </button></td>";
trd += "<td>";
//trd += "<select class='input-small' id='ddltype'><option value='1'>Pts</option><option value='2'>%</option></select>";
trd += ddlInputParameters.html(); //Here I want to add(bind)that dropdown list
trd += "</td>";
trd += "<td>";
trd += "<select class='input-small' id='ddlexit'><option value='1'>None</option><option value='2'>Sq Off Leg</option><option value='3'>Sq Off Strategy</option><option value='4'>Partial Exit</option></select>";
trd += "</td>";
trd += "<td><input type='text'> </td>";
trd += "<td><input type='text'> </td>";
trd += "<td><input type='text'> </td>";
trd += "<td><input type='text'> </td>";
trd += "</tr>";
$("#EntryParametersTableRightDataID tbody").append(trd);
}
Output is coming like values not like dropdown list this :-
Suggest me where I did the mistake and how can I achieve this.
I'm very new to this jQuery logics.
Try using ddlInputParameters.outerHTML() instead of ddlInputParameters.html() in trd += like below.
trd += ddlInputParameters.outerHTML(); //Here I want to add(bind)that dropdown list
The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.
The outerHTML attribute is not worked in my scenario and I have changed the existing logic like below and it's work well to me
var optionsdata = '';
$.each(data.d, function (key, value) {
if (value.Type == "inputparameters") {
optionsdata += "<option value="+key+">"+value.TypeData+"</option>";
});
var ddlInputParameters = "<select class='input-small' id='ddltypeauto'>" + optionsdata + "</select>";
And I have added this ddlInputParameters to <td> like this trd += ddlInputParameters;

Issue in display special characters fetched from AJAX call

Using AJAX, I fetch data, and I have to dynamically append that data as rows in html table.
There are some special characters which are not being displayed in table. Though, they are currently shown if printed using 'alert' or with html tag.
Here is my code:
var mytext = '';
var color = "black";
for (t in events) {
mytext += '<tr style="color:'+color+';">';
mytext += '<td style="color:blue;"> <a onclick=\'load_iframe(' + events[t].event_id + ',"' + events[t].signature +'");\'>';
mytext += $('<div/>').html(events[t].signature).html();
mytext += '</a> </td>';
mytext += '<td>' + events[t].start_time + '</td>';
mytext += '<td>' + events[t].end_time + '</td>';
mytext += '</tr>';
}
$('#events_table > tbody:last').append(mytext);
The value of events[t].signature being shown in table is "venci\u00f3_humano".
If I print it using html/alert it shows correctly. : venciĆ³_humano
Can anybody please tell me how to fix this?
Thanks alot!
I think you should put character encoding in head tag of the page.
<meta charset="UTF-8">
Thanks
The following code working fine.
var mytext = '';
var color = "black";
mytext += '<tr style="color:grey;">';
mytext += '<td style="color:blue;"> <a onclick=\'load_iframe(7 ,"venci\u00f3_humano");\'>';
mytext += $('<div/>').html('venci\u00f3_humano').text();
mytext += '</a> </td>';
mytext += '</tr>';
$('#events_table').append(mytext);
jsfiddle

Why is nan being added to data?

I make an ajax call to a servlet which sends JSON data. I parse it with JSON.parse() and put it into a string to display in table tag in html. But with every row cell data it is showing NaN. I have checked the data there is no NaN.
Here's the code.
var dataFromJSON = JSON.parse(result);
var count = dataFromJSON.count;
var str = "<table id='customers'><tr><th>LOGGED DATE</th></tr>";
for (var i = 0; i < count; i++) {
str += "<tr><td>" + dataFromJSON.records[i].common.logged_date +
+"</td>";
str += "</tr>";
}
str += "</table>";
$("#data").html(str);
The data in dataFromJSON.records[i].common.logged_date is 2016-02-23 10:11:43, but the table shows 2016-02-23 10:11:43NaN.
Please help.
Here:
str += "<tr><td>" + dataFromJSON.records[i].common.logged_date+
+ "</td>";
You have two + right after another. The browser tries to interpret this whitespace as a number
Remove one of the +.
You have put ++ please use only +
var dataFromJSON = JSON.parse(result);
var count = dataFromJSON.count;
var str = "<table id='customers'><tr><th>LOGGED DATE</th></tr>";
for (var i = 0; i < count; i++) {
str += "<tr><td>" + dataFromJSON.records[i].common.logged_date +"</td>"; //chnage here
str += "</tr>";
}
str += "</table>";
$("#data").html(str);

Javascript InnerHTML Output Wrong

function test()
{
var formHTML ="";
var frmid ="test123";
var options = ["Test1", "Test2", "Test3", "Test4", "Test5"]
formHTML += "<select id='" + frmid + ">";
console.log(options);
for ( i = 0; i < options.length; i++) {
var temp = options[i];
var temp2 = "<option value='" + temp + "'>" + temp + "</option>";
console.log(temp2);
formHTML += temp2;
}
formHTML += "</select>";
console.log(formHTML);
document.getElementById("injected").innerHTML+=formHTML;
}
Above is my function to make a select element in my page, when i call this function there is a very strange issue, it only dispalys options test2,test3,test4,test5 and not one...
When i print out formHTML using console.log it shows..
<select id='test123><option value='Test1'>Test1</option>
<option value='Test2'>Test2</option>
<option value='Test3'>Test3</option>
<option value='Test4'>Test4</option>
<option value='Test5'>Test5</option>
</select>
But if you run the code and look at the source code the HTML element is not correct the first element looks like
<option value='test1'> Test1
Missing the close option tag,
I have tried debugging and changing code around but this issue has left me confused.
Is there something missing is there better way of going about this? I am trying to store it all in one string before manipulating the DOM for speed reasons.
All help is appreciated, Thanks
YOu have an error in this line
formHTML += "<select id='" + frmid + ">";
Change that to
formHTML += "<select id='" + frmid + "'>";

jQuery scope or race condition in AJAX/getJSON

I have a piece of jQuery code which invokes several getJSON() calls in quick succession:
var table = $("table#output");
for (var i in items) {
var thisItem = items[i];
$.getJSON("myService", { "itemID": thisItem }, function(json) {
var str = "<tr>";
str += "<td>" + thisItem + "</td>";
str += "<td>" + json.someMember + "</td>";
str += "</tr>";
table.append(str);
});
}
When I run this against a laggy server, the table gets populated with the expected json.someMember values (they arrive out of order: I don't mind that), but the thisItem column is populated with an unpredictable mixture of values from various iterations.
I'm assuming this is something to do with scope and timing - the callback function is reading thisItem from a wider scope? Am I right? How do I prevent this?
My current workaround is for the JSON service to return a copy of its inputs - which is unsatisfying to say the least.
Seems like a scoping issue due to the loop. Try this:
var table = $("table#output");
for (var i in items) {
var thisItem = items[i];
$.getJSON("myService", { "itemID": thisItem }, (function(thisItem) {
return function(json) {
var str = "<tr>";
str += "<td>" + thisItem + "</td>";
str += "<td>" + json.someMember + "</td>";
str += "</tr>";
table.append(str);
}
})(thisItem));
}
Edit: all I did was scope thisItem to the $.getJSON callback.
Javascript does not use block for scope. Scope is only based on functions.
If you want a new scope, you have to declare a new internal function and run it immediately, this is the only way to create a new scope in Javascript.
var table = $("table#output");
for( var i in items )
{
(function(){
var thisItem = items[i];
$.getJSON("myService", { "itemID": thisItem }, function(json)
{
var str = "<tr>";
str += "<td>" + thisItem + "</td>";
str += "<td>" + json.someMember + "</td>";
str += "</tr>";
table.append(str);
});
})();
}

Categories