I am building a chat application with JQuery and PHP. The PHP writes the chat input to the data.txt file and the JQuery is used to append the div where I want the chat to be printed. My output prints the username of the person who sent the chat, however the message is never added to the div. Please help!
JQuery Code:
function updateChat() {
if(!instanse){
instanse = true;
/* define AJAX function */
$.ajax({
type: "POST",
url: "ajax.php",
data: {'function': 'update','state': state,'file': file},
dataType: "json",
success: function(data) {
if(data.text){
/* manage data */
for (var i = 0; i < data.text.length; i++) {
alert(data.text[i]);
$('#chat-row').append($(""+ data.text[i] +""));
}
}
/* manage position of current chat */
document.getElementById('chat-row').scrollTop = document.getElementById('chat-row').scrollHeight;
instanse = false;
state = data.state;
}
});
}
else {
setTimeout(updateChat, 1000);
}
}
.append( content [, content ] ), where content is DOM element, text node, array of elements and text nodes, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
I think $(""+ data.text[i] +"") == [Object, oblect]
function updateChat() {
if(!instanse){
instanse = true;
/* define AJAX function */
$.ajax({
type: "POST",
url: "ajax.php",
data: {'function': 'update','state': state,'file': file},
dataType: "json",
success: function(data) {
if(data.text){
/* manage data */
for (var i = 0; i < data.text.length; i++) {
alert(data.text[i]);
$('#chat-row').append($(data.text[i]));
}
}
/* manage position of current chat */
document.getElementById('chat-row').scrollTop = document.getElementById('chat-row').scrollHeight;
instanse = false;
state = data.state;
}
});
} else {
setTimeout(updateChat, 1000);
}
}
I managed to solve this problem by replacing this:
success: function(data) {
if(data.text){
/* manage data */
for (var i = 0; i < data.text.length; i++) {
alert(data.text[i]);
$('#chat-row').append($(data.text[i]));
}
}
with this:
success: $('#chat-row').load('data.txt')
Related
I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/
I have written a script which retrieves data from SharePoint lists. and populates the data onto a page.
$(document).ready(function(){
init();
});
function init(){
func();
}
function func(){
if(GetQueryStringParams("papcat") != undefined){
//store category in variable
var PAPCat = GetQueryStringParams("papcat");
//query for data that has the catagory associated
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists(guid'9BBF789F-E5BA-449D-A595-BAA326E2C8FF')/Items?$filter=Category eq '"+PAPCat+"'&$orderby=Reference desc",
type: "get",
async: false,
headers: { "accept": "application/json;odata=verbose" },
success: function(dataObj){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Policies and Procedures Categories')/Items?$select=Title,Id",
type: "get",
headers: { "accept": "application/json;odata=verbose" },
async: false,
success: function(dataObj){
//checking if the category exists
if(PAPCat > dataObj.d.results.length){
$("#output").html("Sorry, that category doesn't exist.");
}
//outputting the category
$("#output").append("<h1>"+dataObj.d.results[PAPCat - 1].Title+"</h1>")
},
error: function(dataObj){
$("#output").after("Sorry, an error occured retrieving the records for this category.");
console.log(dataObj);
}
});
//checking to see if any records
//exist against the selected category
if(dataObj.d.results.length == "0"){
$("#output").after("Sorry, no records found for this category.");
return;
}
$("#output").after("<table id='policy_and_responsibility' class='output_table'>"+"<tbody>"+"<tr>"+"<td>"+"<h3>Policy and Responsibility</h3>"+"</td>"+"</tr>"+"<tr id='polandresp_col_titles'>"+"<td><b>Ref</b></td>"+"<td><b>Title</b></td>"+"</tr>"+"</tbody>"+"</table>");
$("#policy_and_responsibility").after("<table id='working_practise' class='output_table'>"+"<tbody>"+"<tr>"+"<td>"+"<h3>Working Practices</h3>"+"</td>"+"</tr>"+"<tr id='workingpractise_col_titles'>"+"<td><b>Ref</b></td>"+"<td><b>Title</b></td>"+"</tr>"+"</tbody>"+"</table>");
for(var i = 0; i < dataObj.d.results.length; i++){
switch(dataObj.d.results[i].Policy_x0020_Type){
case "Policy and Responsibility":
$("#polandresp_col_titles").after("<tr>"+<td>"+"<a href='/hr/Lists/Policies%20%20Procedures%20Catalogue/DispForm.aspx?ID="+ dataObj.d.results[i].Id +"'>"+ dataObj.d.results[i].Reference.toUpperCase() +"</a>" +"</td>"+"<td class='title'>"+dataObj.d.results[i].Title+"</td>"+"</tr>");
break;
case "Working Practices":
$("#workingpractise_col_titles").after("<tr>"+"<td>"+"<a href='/hr/Lists/Policies%20%20Procedures%20Catalogue/DispForm.aspx?ID="+ dataObj.d.results[i].Id +"'>"+dataObj.d.results[i].Reference.toUpperCase() +"</a>"+"</td>"+"<td class='title'>"+dataObj.d.results[i].Title +"</td>"+"</tr>");
break;
}
}
},
error: function(dataObj){
$("#output").after("Sorry, an error occured retrieving the records for this category.");
}
});
}
else{
//retrieving all categories
//from categories list
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('Policies and Procedures Categories')/Items?$select=Title,Id",
type: "get",
headers: {"accept":"application/json;odata=verbose" },
success: function(dataObj){
console.log(dataObj);
for(var i = 0; i < dataObj.d.results.length; i++){
$("#output").append("<a href='"+_spPageContextInfo.webAbsoluteUrl + "/SitePages/DVCTest.aspx?papcat="+dataObj.d.results[i].Id+"'>"+ dataObj.d.results[i].Title + "</a><br/>");
}
},
error: function(dataObj){
$("#output").after("Sorry, an error occured retrieving the categories.");
}
});
}
}
function GetQueryStringParams(param)
{
var pageUrl = window.location.search.substring(1);
var urlVariables = pageUrl.split('&');
for (var i = 0; i < urlVariables.length; i++)
{
var parameterName = urlVariables[i].split('=');
if (parameterName[0] == param)
{
return parameterName[1];
}
}
}
It works fine in Chrome, it outputs all the data without a problem. However, in Internet Explorer 11 it doesn't render anything. I believe that it is because Internet Explorer is forcing it's Document Mode to be IE=9. So, outside of any functions, I wrote this little bit of script...
if($("meta[http-equiv=X-UA-Compatible]").attr("content") != "IE=Edge")
{
$("meta[http-equiv=X-UA-Compatible]").attr("content","IE=Edge");
console.log($("meta[http-equiv=X-UA-Compatible]").attr("content"));
}
But it still insists on being set to IE=9.
Any help on this is greatly appreciated.
Check the masterpage maybe you have the following tag:
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
?
I've got a javascript document where I'm getting a json object and I want to create div's because I can have more than an instance on the json array. I'm creating an article , changing his innerHTML and adding it to the body but it doesn't get added.
$.ajax({
url: 'myURL',
type: "GET",
data: query,
dataType: 'json',
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++)
{
var _body = document.getElementsByTagName('body') [0];
alert(_body.innerHTML);
var article = document.createElement('article');
article.id = 'invoiceno'+i;
article.innerHTML = '<div id="client"></div><table class="cabecalho"><tr><th><span>Invoice #</span></th><td id="invoiceno"><span>invoiceno</span></td></tr><tr><th><span>Date</span></th><td id="invoicedate"><span>invoicedate</span></td></tr></table><table class="total"><tr><th><span >Total</span></th><td><span data-prefix>€</span><span id="tots">(TotalAPagar)</span></td></tr></table>';
alert(article.innerHTML);
_body.appendChild(article);
$("#invoiceno"+i).html(data[i].InvoiceNo);
$("#invoicedate"+i).html(data[i].InvoiceDate);
$("#client"+i).html(data[i].CompanyName);
$("#tots"+i).html(data[i].GrossTotal);
}
}
});
I am trying to populate a dropdownbox with data from a JSON page.
Here is the code I am using:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data
});
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
});
</script>
And here is what the json data returns:
{"d":"{\"16\":\"hello\",\"17\":\"world\"}"}
I am getting an error that "data is undefined." Do I have to somehow tell JQ how to read the json data?
Firstly, the data variable you are passing to the ajax call is not defined (well, not in the code sample you provided), and secondly the ajax call is happening asynchornously, so you need to do something with the returned data, i.e. via a success callback. Example:
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
also you shouldn't need to parse the data returned from the ajax call, as jQuery will automatically parse the JSON for you, ( should need the $.parseJSON(data.msg))
EDIT
Based on the interesting format of the JSON, and assuming that it cannot be changed, this should work (ugly though)
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
data = data.d.replace(/{/g, '').replace(/}/g, '').split(',');
var obj = [];
for (var i = 0; i < data.length; i++) {
obj[i] = {
value: data[i].split(':')[0].replace(/"/g, '').replace('\\', ''),
label: data[i].split(':')[1].replace(/"/g, '')
};
}
var htmlToAppend = "";
for (var j = 0; j < obj.length; j++) {
htmlToAppend += '<option value="' +
obj[j].value +
'">' + obj[j].label +
'</option>';
}
$('#taxList').append(htmlToAppend);
}
});
});
You need to use the success option to return the data.
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
success: function(data){
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
</script>
I have an ajax for retrieving names from the database, when the names are more than one, i split them then clone the first class so that i can have the other name(second) in the cloned class. It seems not to work, What am i missing?
$.ajax({
type: "POST",
url: base_url + "c_transfer/viewTransfer/" + transfer_id,
dataType: "json",
success: function (data) {
var all_transferors = data[0]['Transferor_Name'];
var sole_transferors = all_transferors.split(',');
for (transferor_counter = 0; transferor_counter < sole_transferors.length; transferor_counter++) {
if (transferor_counter > 0) {
$('.clone').relCopy({});
$("#transferor_name").val(sole_transferors[transferor_counter]);
} else {
$("#transferor_name").val(sole_transferors[transferor_counter]);
console.log(sole_transferors[transferor_counter]);
}
// console.log(sole_transferors[transferor_counter]);
}
Are you trying to do this?
$("#transferor_name").val(sole_transferors[transferor_counter].val());
You need to use .val() at the end?