AJAX responseXML empty with jQuery UI Modal Form - javascript

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.

Related

build unique table with JQuery AJAX

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>

Search function to include space

I am trying to build a search function that would allow me to search Word 1 Word 2 ... Word 'n'.
The code below allows me to search through table rows. Results are presented when there is a 1:1 match (Ignoring case). I would like to search using combinations separated by spaces.
Table data sample as below.
AAA_BBB_CCC_DDD.pdf
EEE_FFF_GGG_HHH.pdf
HTML
<script>
$(function(){
$(function(){
var requestUri = "<<URL>>/_api/web/GetFolderByServerRelativeUrl('<<Folder>>')/Files?$filter=(substringof(%27.pdf%27,Name)%20or%20substringof(%27.PDF%27,Name))&$top=1000";
$.ajax({
url: requestUri,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
},
success: onSuccess,
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="Table" style="width:100%"><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + [i+1] + '</td>';
tableContent += '<td>' + objItems[i].Name + '</td>';
tableContent += '<td>' + "<a target='iframe_j' href='<<URL>>" + objItems[i].ServerRelativeUrl + "'>" + "View" + "</a>" + '</td>';
tableContent += '</tr>';
}
$('#TDGrid').append(tableContent);
}
});
});
</script>
<div id="div">
<input class="form-control mb-2" id="TDSearch" type="text" placeholder=" Search">
<table id='Table' class="table table-striped table-sm small">
<tr>
<td>
<div id="TDGrid" style="width: 100%"></div>
</td>
</tr>
</table>
</div>
Current search function
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
You can convert string to array and then make a function, which will check match for strings of that array.
Something like
$(document).ready(function() {
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
var valueArr = value.split(' ');
$("#TDGrid tr").filter(function() {
$(this).toggle(checkIfValuePresent($(this).text().toLowerCase(), valueArr));
});
});
});
function checkIfValuePresent(currRowText, valuesarr) {
let isfound = false;
for (let i = 0; i < valuesarr.length; i++) {
if (currRowText.indexOf(valuesArr[i] > -1)) {
isfound = true;
break;
}
}
return isfound;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='TDSearch'>
split on space, join all strings with | between them for a combined regex string search, case insensitive.
$(document).ready(function(){
$("#TDSearch").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#TDGrid tr").filter(function() {
$(this).toggle(new RegExp(value.replace(/\./g,'[.]').split(' ').join('|'),'gi').test($(this).text()))
});
});
});

Pass JSON result from AJAX to HTML

I am querying a fuseki server using AJAX and the result that I am getting is a JSON object.
I would like to use pagination to go through the result with a limit of records per page. I have tried to send the JSON object to a div in the html file but it is not working. Is there a workaround this? Here is my code:
function myCallBack2(data) {
var all_results = '';
for (var i = 0; i < data.results.bindings.length; i++) {
var bc = '';
if (i % 2 == 0) {
bc = '#b8cddb';
} else {
bc = '#f2f5f7';
}
all_results += '<div class="all_results" style="background-color:' + bc + '">';
for (var j = 0; j < data.head.vars.length; j++) {
var text = data.results.bindings[i][data.head.vars[j]].value;
var type = data.results.bindings[i][data.head.vars[j]].type;
all_results += '<div class="result_row">';
if (type == ('literal')) {
all_results += '<p> ' + data.head.vars[j] + ": " + text + '</p>';
} else {
all_results += '<a href=' + text + " title=" + data.head.vars[j] + '>' + text + '</a>';
}
all_results += '</div>';
}
all_results += '</div>';
}
$('#result').html(all_results);
}
function doSparql() {
var myEndPoint = "http://localhost:3030/Test/query";
name = document.getElementById("search").value;
var requiredName = "?Author foaf:firstName \"" + name + "\".}";
myQuery = ["PREFIX dcterms: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX locah: <http://data.archiveshub.ac.uk/def/>",
"SELECT ?Register ?Id ?Date ?Type",
"WHERE{",
"?Register dcterms:creator ?Author.",
"?Register dcterms:identifier ?Id.",
"?Register dcterms:type ?Type.",
"?Register locah:dateCreatedAccumulatedString ?Date.",
requiredName
].join(" ");
console.log('myQuery: ' + myQuery);
window.alert(myQuery);
$.ajax({
dataType: "jsonp",
url: myEndPoint,
data: {
"query": myQuery,
"output": "json"
},
success: myCallBack2,
error: myError
});
console.log('After .ajax');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//raw.github.com/botmonster/jquery-bootpag/master/lib/jquery.bootpag.min.js"></script>
<div id="page-selection1" "></div>
<div id="result " class="result "></div>
<div id="page-selection2 "></div>
<script>
$('#page-selection1,#page-selection2').bootpag({
total: 50,
page: 1,
maxVisible: 5,
leaps: true,
firstLastUse: true,
first: 'First',
last: 'Last',
wrapClass: 'pagination',
activeClass: 'active',
disabledClass: 'disabled',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first'
}).on("page ", function(event, num) {
$("#result ").html("Page " + num);
});
</script>
I am expecting to show part of the results instead Page 1, Page 2... in #result according to a limit per page.

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Little javascript / ajax / mysql chat

For my site I want to have a little chat / support field. At the moment I can write and also save it right to the database.
But I want to have it, that if I open the site again the old text come from the database. But how is the best way to do that? I also think my Array is false, because I only get one and not all data back from the database.
My javascript testcode:
initChat: function () {
var cont = $('#chats');
var list = $('.chats', cont);
var form = $('.chat-form', cont);
var input = $('input', form);
var btn = $('.btn', form);
var handleClick = function (e) {
e.preventDefault();
var text = input.val();
if (text.length == 0) {
return;
}
var time = new Date();
var time_str = time.toString('dd.MM.yyyy - H:mm')+ " Uhr";
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + time_str + '</span>';
tpl += '<span class="body">';
tpl += text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
var time_str_new = time.toString('yyyy-MM-dd H:mm:ss');
$.ajax({
type: "POST",
url: '../support.php',
data: {datum: time_str_new, text: text},
dataType: 'json',
success: function(data)
{
input.val("");
}
});
$('.scroller', cont).slimScroll({
scrollTo: list.height()
});
}
My php testscript:
$kundenid = KUNDENID;
$query = "INSERT INTO support set datum = '$datum', kunde = '$kundenid', text = '$text', typ = 'kunde'";
$result = mysql_query($query,$db);
$querysup = "SELECT id, datum, kunde, text, typ FROM support WHERE kunde = '$kundenid'";
$resultsup = mysql_query($querysup,$db);
while($rowsup = mysql_fetch_array($resultsup)) {
$datum = $rowsup['datum'];
$text = $rowsup['text'];
$typ = $rowsup['typ'];
$data = array("datum"=>$rowsup['datum'], "text"=>$rowsup['text'], "typ"=>$rowsup['typ']);
}
echo json_encode($data);
Ok now I have this code. If I post a new text it show me all posts from database. But I need it that the data from mysql still there before my first post.
initChat: function () {
var cont = $('#chats');
var list = $('.chats', cont);
var form = $('.chat-form', cont);
var input = $('input', form);
var btn = $('.btn', form);
var handleClick = function (e) {
e.preventDefault();
var text = input.val();
if (text.length == 0) {
return;
}
var time = new Date();
var time_str = time.toString('dd.MM.yyyy - H:mm')+ " Uhr";
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + time_str + '</span>';
tpl += '<span class="body">';
tpl += text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
var time_str_new = time.toString('yyyy-MM-dd H:mm:ss');
$.ajax({
type: "POST",
url: 'support.php',
data: {datum: time_str_new, text: text},
dataType: 'json',
success: function(data)
{
var myArray = data;
for (var i = 0; i < myArray.length; i++) {
var datum = new Date(myArray[i].datum);
var tpl = '';
tpl += '<li class="out">';
tpl += '<img class="avatar" alt="" src="assets/img/avatar.png"/>';
tpl += '<div class="message">';
tpl += '<span class="arrow"></span>';
tpl += 'Meine Frage ';
tpl += '<span class="datetime">vom ' + datum.toString('dd.MM.yyyy - H:mm:ss')+ ' Uhr' + '</span>';
tpl += '<span class="body">';
tpl += myArray[i].text;
tpl += '</span>';
tpl += '</div>';
tpl += '</li>';
var msg = list.append(tpl);
}
}
});
But how to load it from the array to my javascript... so if I refresh the page the values from array are in my "Chatbox"
The missing part could be a simple "assign" operation like
var chatArr=<?PHP echo json_encode($data) ?>;
in a <script type="language/JavaScript"> section, which you can insert after you have dealt with all the PHP stuff in the document. You should make sure of course that nothing "unwanted" gets into $data. After that you can do whatever you want to do with the JavaScript Array/Object in a $(function(){...}) section anywhere else in the document.
There are of course also dedicated JSON parsers which will also take care of Date objects. The simple assign will only generate Stings or numeric contents in the JavaScript object, see here.

Categories

Resources