build unique table with JQuery AJAX - javascript

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>

The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>

Related

Pagination for Dropdownlist filter data in ASP.NET MVC

My default start page has no data
Then filter out the data in the database after the two drop-down list
I hope that the filtered data can be displayed in pagination if there are more than ten records.
But I don't know how to do.
I'm new in this.
Here is my javascript
<script type="text/javascript">
$(document).ready(function () {
$("#CITY").change(function () { ChangeCity(); });
$("#AREA").change(function () { ChangeArea(); });
$(document).on('submit', '#ButtonSubmit', function () {
return false;
});
})
function SetareaEmpty() {
$('#CITY').empty();
$('#CITY').append($('<option></option>').val('').text('select'));
}
function ChangeCity() {
var selectedCity = $.trim($('#CITY option:selected').val());
if ($.trim(selectedCity.length) > 0) {
ChangeArea(selectedCity);
}
else {
SetareaEmpty()
}
}
function ChangeArea(selectedCity) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSecondDDL", "Getarea")',
dataType: "json",
data: { cityName: selectedCity },
success: function (mems) {
if (mems.length > 0) {
$('#AREA').empty();
$('#AREA').append($('<option></option>').val('').text('select'));
}
$.each(mems, function (i, member) {
$("#AREA").append($('<option></option>').val(member).text(member));
});
}
});
}
function SerchallData(selectedCity) {
var selectedCity = $('#CITY option:selected').val();
var selectedValue = $('#AREA option:selected').val();
if ($.trim(selectedValue).length > 0) {
$.ajax({
url: '#Url.Action("Getmap", "Getarea")',
data: { cityName: selectedCity, areaName: selectedValue },
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Mytable>tbody').empty();
for (var i = 0; i < data.length; i++) {
var row = $('<tr><td>'>+</td><td>' + data[i].ID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Address + '</td><td>' + data[i].Phone + '</td><td>' +'</td></tr>');
$('#Mytable>tbody').append(row);
}
$('#Mytable').show(); //show filter data
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
}
}
my dropdownlist is use js to connection
filter data also
that's means after user selected city and area
data will be displayed
here is my html:
<form>
<div class="row well">
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">City</span>
<p>
#Html.DropDownList("City", (IEnumerable<SelectListItem>)ViewBag.Allcity, "Please select", new { id = "CITY" })
</p>
</div>
</div>
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-addon">Area</span>
<p> <select id="AREA" name="AREA"><option>Please select</option></select></p>
</div>
</div>
<div class="col-lg-2">
<button type="button" onclick="SearchallData()" id="ButtonSubmit" class="btn btn-primary">
<span class="glyphicon glyphicon-search"></span>search
</button>
</div>
</div>
<table id="Mytable" class="table table-bordered table-hover" style="display:none;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
//first page table will not show any data so is null
</tbody>
and my controller
public async Task<ActionResult> Index()
{
var b = new GetCollection();
var areasource = await b.GetInserchdata();
ViewBag.AllCity = areasource.Select(s => s.City).Distinct().Select(item => new SelectListItem()
{
Text = item,
Value = item
});
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connstr))
{
con.Open();
string q = "Select * from Shopmap";
SqlDataAdapter da = new SqlDataAdapter(q, con);
da.Fill(dt);
}
return View(dt);
}
//js for first selected dropdownlist
[HttpPost]
public async Task<JsonResult> GetSecondDDL(string cityName)
{
var CitySlectList = this.GetSelectList(await GetCity(), cityName);
if (string.IsNullOrEmpty(cityName))
{
return Json(new EmptyResult());
}
var AreaSlectList = await this.GetArea(cityName);
return Json(AreaSlectList);
}
//js for selected second dropdownlist then search data
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)
{
var b = new GetCollection();
List<Inserch> shop = b.GetDBdata();
var a = shop.FindAll(x => x.Address.Contains(cityName));
var Alldata = a.FindAll(x => x.Address.Contains(areaName)).AsEnumerable();
if (string.IsNullOrEmpty(areaName))
{
return Json(new EmptyResult());
}
return Json(Alldata);
}
I think it will use js to do what I want
then maybe c# code will put in
[HttpPost]
public JsonResult GetShopmap(string cityName, string areaName)->this function
please tell me what to do
I desperately need.
thank's.
Pagination for Dropdownlist filter data in ASP.NET MVC
You can achieve that in following way:
HTML
<table id="userTable_info">
<thead>
<tr>
<th>Id </th>
<th>Controller </th>
<th>Page_name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
Script:
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$('#userTable_info').hide();
//On Submit Method
$("#Submit").click(function () {
var ddlCategory = parseInt($("#ddlCategory").val());
var ddlSubCategorie = parseInt($("#ddlSubCategorie").val());
$.ajax({
type: "POST",
url: 'http://localhost:5094/Member/GetShopmap',
dataType: "json",
data: { cityName: ddlCategory, areaName: ddlSubCategorie },
success: function (response) {
console.log(response);
$.each(response, function (index, value) {
var tr = "<tr>";
tr += "<td>" + value.ulogo_id + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.page_name + "</td>";
tr += "<td>" + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
$('#userTable_info').show();
}
});
});
});
</script>
}
Output:
Note: Based on your table defination please implement the neccessary chnages. It ill work as expected.

How to create a bootstrap-table dynamically?

I'm having trouble developing a bootstrap-table by clicking a button. My goal is to add a sort feature for each columns on a table. So for my user case, when a user clicks on the button, it calls an ajax to grab a data from Database and sends back a result (it works so no worries on it). So i need to display the results as a bootstrap-table so i can use the sort feature for each column. Plus, I'm using pagination.js which uses Array of json objects and table to display the result.
When I develop the table and append it into a div, I dont see the sort feature on each columns.
It works when I create a simple hard code HTML table with Bootstrap-table attributes such as sort feature (data-sortable="true"). I believe when the page loads bootstrap detects the and its attributs that is on the html body. But when I dynamically create a bootstrap-table, the HTML table is there but not the bootstrap-table feature.
Please help. Here is my code below of how i develop the table using javascript function.
// result is a large string of result when ajax is sending a response.
function displayResult(result) {
//convert the result into Array of JSON
var splitResult = result.split("*split*");
var getLast = splitResult.length - 1;
for(var i = 0; i < splitResult.length; i++){
if(i != getLast) {
splitResult[i] = JSON.parse(splitResult[i]);
} else {
splitResult.splice(i,1);
}
}
// the .pagination is a function that is use in pagination.js
// the #page is a DIV
$('#page').pagination({
dataSource: splitResult,
pageSize: 8,
callback: function(data, pagination) {
// template method
var html = template(data);
// grab the html String and append it into the #demo DIV
$("#demo").append(html);
}
})
}
function template(data) {
// table tag with bootstrap-table attributes
var html = '<table data-toggle="table" style="width: 100%;">';
// create the table headers
html = html + '<thead><tr><th data-field="IDCODE" data-sortable="true">ID</th><th scope="col" data-sortable="true">ZIP 11</th><th scope="col" data-sortable="true">Date</th></tr></thead>'
+ '<tbody>';
// input the results of the data
if (data[0].IDCODE) {
$.each(data, function(index, item) {
html += '<trid="tr-id-2" class="tr-class-2"><td>'
+ item.IDCODE+'</td>'
+ '<td>' + item.ZIP11_ID + '</td>'
+ '<td>' + item.DEL01_TS + '</td></tr>';
});
} else {
$.each(data, function(index, item) {
html += '<tr><td>'+ item +'</td></tr>';
});
}
html += '</tbody></table>';
return html;
}
when using this approach, it just display the html table. Not using bootstrap-table. I'm trying to add a feature where a user can click on the column header to sort.
Hope this code could help you, what it does is
1. display a textBox, where I user can enter a db table name
2. The backend ( in my case Python) get information from db_name_table
3. The data is displayed dinamically in the bootstrap-table
HTML
<form method="GET" id="id1" action="{% url 'request_page' %}">
<input type="text" value="db_name_table" name="mytextbox" id='mytextbox' size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
Javascript:
$(document).ready( function(){
$('#id1').submit( function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success:function( value ){
$('#datatable').bootstrapTable({
striped: true,
pagination: true,
showColumns: true,
showToggle: true,
showExport: true,
sortable: true,
paginationVAlign: 'both',
pageSize: 25,
pageList: [10, 25, 50, 100, 'ALL'],
columns: {{ columns|safe }},
data: {{ data|safe }},
});
}
})
})
});
$(document).ready(function() {
var i = 1;
$('#tab_logic').on('focusout', 'tbody tr:nth-last-child(2) td:nth-last-child(2) input', function() {
if ($(this).val() != '' && $('#tab_logic tbody tr:nth-last-child(2) td:nth-last-child(3) input').val() != "" && $('#tab_logic tbody tr:nth-last-child(2) .product').val() != '') {
b = i - 1;
$('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
$(this).focus().select();
i++;
}
});
$('body').on('click', '#delete_row', function() {
if (i > 1) {
var id = i;
$('#tab_logic tbody tr:nth-last-child(2)').remove();
$('#tab_logic tbody tr:last').attr("id", "addr" + (id - 1));
i--;
}
calc();
});
$('#tab_logic tbody').on('keyup change', function() {
calc();
});
$('#tax').on('focusout', function() {
var total = parseInt($('#sub_total').val());
var tax_sum = eval(total / 100 * $('#tax').val());
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum+total).toFixed(2));
});
});
function calc() {
$('#tab_logic tbody tr').each(function(i, element) {
var html = $(this).html();
if (html != '') {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
$(this).find('.total').val(qty * price);
calc_total();
}
});
}
function calc_total() {
total = 0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('#sub_total').val(total.toFixed(2));
tax_sum = total / 100 * $('#tax').val();
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum + total).toFixed(2));
}

how to get the value of the clicked table row?

My question is: how do I get the value of the clicked row and column?
The code I have is this:
JS:
$.ajax({
type: 'POST',
url: url,
data: json,
success: function(data) {
var response_array = JSON.parse(data);
var columns = ['id', 'name', 'email', 'telephone', 'website', 'city'];
var table_html = ' <tr>\n' +
'<th id="id">Id</th>\n' +
'<th id="name">Bedrijfnaam</th>\n' +
'<th id="email">E-mail</th>\n' +
'<th id="telephone">Telefoon</th>\n' +
'<th id="website">Website</th>\n' +
'<th id="city">Plaats</th>\n' +
'</tr>';
for (var i = 0; i < response_array.length; i++) {
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + response_array[i][columns[j]] + '</td>'
}
table_html += '</tr>'
};
$("#posts").append(table_html);
},
error: function (jqXHR, textStatus, errorThrown) { alert('ERROR: ' + errorThrown); }
});
Here is the HTML:
<div class="tabel">
<table id="posts">
</table>
</div>
I have tried the following:
$('#posts').click(function(){
console.log("clicked");
var id = $("tr").find(".id").html();
console.log(id);
});
Sadly this will only give me the id of the first row, no matter where I click.
Any help is appreciated!
Ramon
The below approach should be able to find the ID
$('#post').on('click', function(e){
var id = $(e.target).closest('tr').find(".id").html();
console.log(id)
})
HTML content of clicked row
$('#posts tr').click(function(){
$(this).html();
});
text from clicked td
$('#posts tr td').click(function(){
$(this).text();
});
If you are using ajax and you are redrawing elements, you will not catch em via click function. You will need to add on function:
$(document).on('click','#posts tr td','function(){
$(this).text();
});
You may try to use AddEventListener for your table, it will work for sure.
Like this:
let posts = document.getlementById('posts');
posts.addEventListener('click',(e) => {
// anything you need here, for example:
console.log(e.target);
e.preventDefault();
});
As well - it will be fine not to use same IDs for elements in a grid (like id="id" which you have), it should be different.

checkboxes and number fields set by jquery appear for a split second, then suddenly disappear

I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle

AJAX responseXML empty with jQuery UI Modal Form

I have a jQuery ajax call to a SharePoint web service that I use to append "search" results to a table. With only a simple html table everything works fine and the results are added, but when I try to add the results to a jQuery UI modal form the call is returning 0 results and the responseXML appears to be null (responseText returns the expected string). I hope I've just missed something simple. Any ideas are welcome.
HTML:
<p id="myDescrip">This is a test page for CAML Web Service Queries</p>
<button id="SearchItems">Search for Transcripts</button>
<div id="dialog-results" title="Search Results">
<p id="myResults">Your search results are:</p>
<table id="SearchData" class="myTable">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Transcripts School</th>
<th>Date Received</th>
</tr>
</table>
</div>
JavaScript (jQuery/jQuery UI):
$(function() {
// Button control
$( "#SearchItems" )
.button()
.click(function() {
SearchTranscripts();
});
// Dialog control
$( "#dialog-results" ).dialog({
autoOpen: false,
resizable: false,
height:300,
width:500,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
// Query the SharePoint list
function SearchTranscripts() {
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>"
soapEnv += "<soapenv:Body>"
soapEnv += "<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>"
soapEnv += "<listName>Transcripts Log</listName>"
soapEnv += "<query><Query><Where><Or><Contains><FieldRef Name='Title' /><Value Type='Text'>Smith</Value></Contains>"
soapEnv += "<Contains><FieldRef Name='First_Name' /><Value Type='Text'>Smith</Value></Contains></Or></Where>"
soapEnv += "<OrderBy><FieldRef Name='Title' Ascending='True' /></OrderBy></Query></query>"
soapEnv += "<viewFields>"
soapEnv += "</viewFields>"
soapEnv += "<rowLimit>5000</rowLimit>"
soapEnv += "</GetListItems>"
soapEnv += "</soapenv:Body>"
soapEnv += "</soapenv:Envelope>";
$.ajax({
url: "/xxx/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
error: errorResult,
contentType: "text/xml; charset=\"utf-8\""
});
}
// Add items to the list
function processResult(xData) {
var myFname = "";
var myLname = "";
var mySchool = "";
var myDate = "";
var myID = "";
var itemUrl = "/xxx/DispForm.aspx?ID=";
var nr = 0;
$(xData.responseXML).find("z\\:row").each(function () {
myFname = $(this).attr("ows_First_Name");
myLname = $(this).attr("ows_Title");
mySchool = $(this).attr("ows_College");
var tmpd = $(this).attr("ows_Date_Received");
// Check for invalid dates
if(!tmpd){
myDate = "n/a";
} else {
myDate = tmpd.substring(5, 7).replace("0","") + "/"
myDate += tmpd.substring(8, 10).replace("0","") + "/"
myDate += tmpd.substring(0, 4);
}
myID = $(this).attr("ows_ID");
// Create the new row
var AddRow = "<tr><td><a href='" + itemUrl + myID + "'>" + myLname + "</a></td>"
AddRow += "<td>" + myFname + "</td>"
AddRow += "<td>" + mySchool + "</td>"
AddRow += "<td>" + myDate + "</td></tr>"
$("#SearchData").append(AddRow);
nr += 1;
});
$("#myResults").html($("#myResults").html() + " " + nr)
$( "#dialog-results" ).dialog( "open" );
}
// Show Error
function errorResult(xData) {
alert(xData.responseText);
}
The issue is a jQuery 1.9.1 bug with responseXML. As mentioned in my comments using version 1.8.3 "solves" the issue. You can read more info on it on the jQuery bug tracker and on this blog.

Categories

Resources