Little javascript / ajax / mysql chat - javascript

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.

Related

Backbone.js - Solving method

BACKBONE and Jquery
I have a piece of code:
var ChatMessage = Backbone.View.extend({
el : '#friend-list',
events : {},
initialize : function() {},
loadMessage : function(parent_id) {
//ukrycie komunikatów etc.
$("#chat_body").html('');
$("#end-record-info").hide();
$("#end-record-load").hide();
page = 1;
this.ajax(parent_id,page); //initial data load
},
ajax : function(parent_id,page) {
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
$("#end-record-load").hide();
this.build(json.message, page);
page ++; //page increment
loading = false; //set loading flag off
end_record = false;
if(json.max < page){ //no more records
end_record = true; //set end record flag on
return; //exit
}
});
},
build : function(arr, page) {
alert('dgd');
html = '';
var height = 0;
arr.reverse();
$.each(arr, function(i, data){
html += '<div class="answer '+data.side+'">';
html += '<div class="avatar">';
html += '<a href="**" target="_blank">';
html += ''+data.id+'';
html += '</a>';
html += '<div class="status offline"></div>';
html += '</div>';
html += '<div class="name">';
html += '<a href="**" target="_blank">';
html += data.username;
html += '</a>';
html += '</div>';
html += '<div class="text">';
html += data.content;
html += '</div>';
html += '<div class="time">';
if (data.side != 'left') {
html += data.dateSendMessage
}
else {
if (data.read == 0) {
html += 'xxx';
}
else {
html += 'xxx';
}
}
html += '</div>';
html += '</div>';
});
var nh = $('#chat_body').html();
$('#chat_body').html(html+nh);
if (page == 1) {
$('#chat_body .answer').each(function(i, value){
height += parseInt($(this).height());
});
height += '';
$('.chat2').scrollTop(height);
}
}
});
In AJAX method I want to build method
this.build(json.message, page);
But something does not work and I get an error.
pm2.js:67TypeError: this.build is not a function. (In 'this.build(json.message, page)', 'this.build' is undefined)
Can anyone help? What changes in this piece of code can be by the way?
Piotr
You should probably save current context before calling getJSON:
ajax : function(parent_id,page) {
var self = this;
$.getJSON( "/**/**/"+parent_id+"/"+page, function( json ) {
...
self.build(json.message, 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);

XML or text declaration not at start of entity error - PHP and Javascript

Hi I'm trying to get the xml data from php to javascript using DOM document and it keeps giving me : XML or text declaration not at start of entity error.(on firebug)
I tried saving it to a real xml file and it outputs a well formatted xml.
I guess the reason for this is white space on top of the xml file. I tried using ob_start(); and ob_end_flush(); but couldn't get that working
BTW I'm new to Ajax!
JS script
var xh = createRequest();
var xhrObject = false;
if (window.XMLHttpRequest)
{
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData()
{
if ((xh.readyState == 4) &&(xh.status == 200))
{
alert("hi");
var serverResponse = xh.responseXML;
var header = serverResponse.getElementsByTagName("good");
var spantag = document.getElementById("sp");
var x;
spantag.innerHTML = "";
x = "<table cellpadding='1' cellspacing='6' border='0'>";
x += "<tr><td>ID</td><td>price</td><td>quantity</td><td>Total</td><td>Remove</td></tr>";
for (i=0; i<header.length; i++)
{
var id = header[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
var price = header[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
var qty = header[i].getElementsByTagName("quantity")[0].childNodes[0].nodeValue;
var total = header[i].getElementsByTagName("total")[0].childNodes[0].nodeValue;
if(qty=="0")
{
continue;
}
x += "<tr>"
+ "<td>" + id + "</td>"
+ "<td>" + price + "</td>"
+ "<td>" + qty + "</td>"
+ "<td>" + total + "</td>"
+ "<td>" + "<a href='#' onclick='AddRemoveItem(\"Remove\","+id+");'>Remove Item</a>" + "</td>"
+ "</tr>";
}
x += "</table>";
if (header.length != 0)
spantag.innerHTML = x;
}
}
PHP code
function toXml($shop_goods)
{
$doc = new DomDocument();
$goods = $doc->createElement('goods');
$goods = $doc->appendChild($goods);
foreach ($shop_goods as $Item => $ItemName)
{
$good = $doc->createElement('good');
$good = $goods->appendChild($good);
$title = $doc->createElement('ID');
$title = $good->appendChild($title);
$value = $doc->createTextNode($Item);
$value = $title->appendChild($value);
$price = $doc->createElement('price');
$price = $good->appendChild($price);
$value3 = $doc->createTextNode($ItemName["price"]);
$value3 = $price->appendChild($value3);
$quantity = $doc->createElement('quantity');
$quantity = $good->appendChild($quantity);
$value2 = $doc->createTextNode($ItemName["qty"]);
$value2 = $quantity->appendChild($value2);
$total = $doc->createElement('total');
$total = $good->appendChild($total);
$value3 = $doc->createTextNode($ItemName["total"]);
$value3 = $total->appendChild($value3);
}
$strXml = $doc->saveXML();
//echo("<br>----- DATA RECOREDED!!! ----");
return $strXml;
}
As others have noted, this could be an encoding issue.
Check your code for the Xml byte order mark.
Check the document is returning the correct mime type.
Not sure of your constraints but have you considered serializing your data to Json format. It's much easier to work with in the browser.
Finally consider using a library like JQuery to handle your ajax requests, much easier for cross browser compatibility.

Assigning user input to object with variable in its index

I am trying to using the JS to take user input and modify certain object attributes based on the user's input. I am storing the object's index in the select's alt attribute in order to use that to update the correct object. I'm getting an error: element[Payment_Format_name] is undefined
The WF.php file takes data from a CSV and formats it into a mulch-dimensional object.
$(document).ready(function() {
$.getJSON('WF.php', function(data) {
var newDiv, NewDiv2, NewDiv3,InvoiceInfo, count, DeliveryMethod, PaymentFormat, Payment_Format_id, Payment_Format_name;
count = 0;
$.each(data, function(index, element) {
count = count + 1;
//document.write (count);
newDiv = $('<div/>').addClass('row').appendTo('#showdata');
newDiv3 = $('<div/>').addClass('hd').appendTo(newDiv);
$('<div class="hd_field">' + element['PmtRec']['RcvrParty']['Name']['Name1'] + '</div>').appendTo(newDiv3);
if (element['PmtRec']['PmtMethod'] === 'CHK'){
$('<div class="hd_field">Delivery Method: <select alt="Delivery_Method" " id="Delivery' + count +'" class="Delivery_Method"><option value="100" selected="selected">US Mail</option><option value="300">Foreign Mail</option><option value="J00">Certified Mail with Return Receipt</option></select><div id="Selected_Method' + count +'"></div></div>').appendTo(newDiv3);
}
else if (element['PmtRec']['PmtMethod'] === 'DAC') {
$('<div class="hd_field">Payment Format: <select alt="'+index +'" id="Payment_' + count +'" class="Payment_Format"><option value="CTX" selected="selected">Company to Company</option><option value="PPD">Company to Person</option></select><div id="Selected_Format'+count+'"></div></div>').appendTo(newDiv3);
}
$('<div class="hd_field">' + 'Total: ' + element['PmtRec']['CurAmt'] + '</div>').appendTo(newDiv3);
InvoiceInfo = element['PmtRec']['PmtDetail']['InvoiceInfo'];
$.each(InvoiceInfo, function(index, element) {
newDiv2 = $('<div/>').addClass('sub_row').appendTo(newDiv);
$('<div class="field">' + element['InvoiceNum'] + '</div>').appendTo(newDiv2);
$('<div class="field">' + element['NetCurAmt'] + '</div>').appendTo(newDiv2);
});
$('select.Payment_Format').change(function(){
Payment_Format_id = ($(this).attr('id').match(/[\d]+$/));
Payment_Format_name = ($(this).attr('alt'));
//alert(Payment_Format_name);
PaymentFormat = ($(this).val());
element[Payment_Format_name] = Payment_Format_name;
element[Payment_Format_name]['PmtRec']['PmtFormat'] = PaymentFormat;
$('#Selected_Format' + Payment_Format_id).text('Selected Format: ' + element[Payment_Format] );
});
});
console.log(data);
});
});
PHP (this is a snippet, I'm actually creating a lot more elements here)
if (($handle = fopen('upload/BEN-new.csv', "r")) === FALSE) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$cardCodes = array();
$payments = array();
$details = array ();
while ($row = fgetcsv($handle, 1024, ",")) {
$cardCodes[] = array_combine($headers, $row);
}
$prevCode = '';
foreach ($cardCodes as $key => $value) {
$payments[$value['CardCode']]['PmtRec']['PmtCrDr'] = 'C';
$payments[$value['CardCode']]['PmtRec']['PmtFormat'] = 'CTX';
fclose($handle);
echo json_encode($payments)
Ok, so for starters,
$('select.Payment_Format').change(function(){
Payment_Format_id = ($(this).attr('id').match(/[\d]+$/));
Payment_Format_name = ($(this).attr('alt'));
PaymentFormat = ($(this).val());
element[Payment_Format_name] = Payment_Format_name;
element[Payment_Format_name]['PmtRec']['PmtFormat'] = PaymentFormat;
$('#Selected_Format' + Payment_Format_id).text('Selected Format: ' + element[Payment_Format] );
});
});
is not what you want - this function is reassigned to the change event of the 'select.Payment_Fomat' element for each iteration of $.each(data, function(index, element). The event listener should be added outside the $.each function, inside the $.getJson call and it needs to loop over the elements object, and try to find the correct data to update.
Apologies for the uselessness earlier, it was 5am and apparently I was slightly delusional.

Splitting an array

I have two javascript functions, the first one is working, teh second is working but not echoing the correct value in the hidden inputs.
Ive manage to get the last hidden input value correct but I'm not sure how
var customTicketsArr = Array();
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var storeString = "TicketName" + TicketName + "TicketPrice" + TicketPrice + "Quantity" + ticketquantity + '';
customTicketsArr.push(storeString);
EditEventUpdateTickets(true);
}
function EditEventUpdateTickets(fade){
jQuery("#custom_tickets_string").val(customTicketsArr);
var output = "";
var style = "";
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].split("TicketName");
ticketprice = customTicketsArr[i].split("TicketPrice");
ticketquantity = customTicketsArr[i].split("Quantity");
if(fade){
if (customTicketsArr.length - 1 == i){
style = "display: none; ";
var fadeInDiv = i;
} else {
style = "";
}
}
if (i % 2 == 1) { style += "background-color: #660000; "}
html = "<div id='customticket" + i + "' class='customeventbase' style='" + style + "'>";
html += '<input type="hidden" name="customTicketid[' + i + '][Name]" id="customticketName' + i + '" value="'+ ticketname + '" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Price]" id="customticketPrice' + i + '" value="' +ticketprice[1] +'" />';
html += '<input type="hidden" name="customTicketid[' + i + '][Quantity]" id="customticketQuantity' + i + '" value="'+ ticketquantity[1] +'" />';
html += '<button class="customeventdel" type="button" onClick="EditEventRemoveDate(' + i + ')"></button>';
html += '<div class="clear"></div>';
html += '</div>\n';
output += html;
}
output += "<input type='hidden' id='custom_ticket_info' name='custom_ticket_info' value='" + customTicketsArr + "' />";
jQuery("#custom_ticket_container").html(output);
if(fade){
setTimeout("EditEventfadeInDiv(" + fadeInDiv +")", 10);
}
}
this outputs:
<div style="background-color: #660000; " class="customeventbase" id="customticket1">
<input type="hidden" value=",testTicketPrice50Quantity44" id="customticketName1" name="customTicketid[1][Name]">
<input type="hidden" value="undefined" id="customticketPrice1" name="customTicketid[1][Price]">
<input type="hidden" value="44" id="customticketQuantity1" name="customTicketid[1][Quantity]">
<button onclick="EditEventRemoveDate(1)" type="button" class="customeventdel"></button>
<div class="clear"></div></div>
the values for the first two hidden fields are incorrect
They're not incorrect values - split() is doing exactly what it is supposed to - returning an array of substrings after removing the separator.
With your string structure, splitting on TicketName will give you two strings - the substring before the separator and the substring after - TicketName itself is not included.
Thus, for the string "TicketNametestTicketPrice50Quantity44", you will get "" and "testTicketPrice50Quantity44" when you split on "TicketName" . Splitting the same string on TicketPrice will give you "TicketNametest" and "50Quantity44".
I'd suggest putting objects into your array instead -
var storeObject = {
"TicketName" : TicketName,
"TicketPrice" : TicketPrice,
"Quantity" : ticketquantity
};
customTicketsArr.push(storeObject);
You can then get back the data as:
for (i = customTicketsArr.length-1; i >= 0; i--){
var currentObject = customTicketsArr[i];
var ticketname = currentObject.TicketName;
var ticketprice = currentObject.TicketPrice;
var ticketquantity = currentObject.Quantity;
//do other stuff here
}
why do you save it as a string? I would recommend storing it in an object:
function EditEventAddTicket(){
alertWrongTime = false;
var TicketName = jQuery("#ticketname").val();
var TicketPrice = jQuery("#ticketprice").val();
var ticketquantity = jQuery("#ticketquantity").val();
var ticket = {"TicketName": TicketName, "TicketPrice": TicketPrice, "Quantity": ticketquantity};
customTicketsArr.push(ticket);
EditEventUpdateTickets(true);
}
and then you can simply load the data:
for (i = customTicketsArr.length-1; i >= 0; i--){
ticketname = customTicketsArr[i].TicketName;
ticketprice = customTicketsArr[i].TicketPrice;
ticketquantity = customTicketsArr[i].Quantity;
// ...
}
Why not just make a two dimensional array?
var customTicketsArr = Array();
function EditEventAddTicket() {
customTicketsArr.push({
'name' : jQuery("#ticketname").val(),
'price' : jQuery("#ticketprice").val(),
'qty' : jQuery("#ticketquantity").val()
});
}

Categories

Resources