replace words with images chatroom - javascript

Okay, below I have attached my chatroom script, What I'm trying to implement is a script which replaces specific words like :wow with an image <img src="wow.gif"></img> I previously used the following to achieve this;
var newdata = data.replace(/:wow/g,"<img src=\"wow.gif\"></img>");
however where I've recently redone my chatroom javascript I don't know where to place this or if this would even work with my updated script. Below is the JavaScript that loads my chatroom. Thankyou for any help.
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}

It appears your update is referencing the chat content within an array of string data, in which case you'll reference data.text[i] within the for loop. Try this:
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/_account/_pages/chat_room_scripts/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
// UPDATE HERE
$('#chat-area').append($("<p>"+ data.text[i].replace(/:(wow|hi)/g,"<img src=\"$1.gif\"></img>")+"</p>"));
// UPDATE HERE
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
General Purpose Replacement
You can customize your emoticons by just adding them to the capture group separated by pipes:
replace(/:(wow|hi|fish|tiger|dog|elephant|bird)/g,"<img src=\"$1.gif\"></img>")

option 1:
if you want the code in the javascript, then in updateChat() where you are appending the html to #chat-area you could apply the same code. eg:
var newdata = data.replace(/:wow/g,"<img src=\"wow.gif\"></img>");
$('#chat-area').append($("<p>"+ newdata +"</p>"));
option 2:
do the replacement in the server side AJAX code. This way you don't have to keep updating javascript to add new image translations.
And don't hardcode them, store the translations in a db table or file so you can easily add new ones.

Related

Sending strings to MVC Controller via AJAX

I am trying to send data via AJAX to MVC Controller method. I am trying to make booking system app. I want to check that user input exists in Entity Model. Ajax is pushing parameters to method controller but i don't get response.
Here is my AJAX call in View:
var check = document.getElementById('check');
//starttime.onchange = checkvalidate(startdate, starttime);
$(check).click(function (datevalue, timevalue) {
var startdate = document.getElementById('startdate');
var starttime = document.getElementById('starttime');
var log = document.getElementById('log');
var datevalue = startdate.value;
var timevalue = starttime.value;
$.ajax({
type: "POST",
url: "/Home/CheckValidate",
data: { 'start': datevalue, 'time': timevalue },
dataType: "Boolean",
success: function (response) {
console.log = response;
if (response == true) {
log.value = "YES";
} else
{
log.value = "NO";
}
}
})
})
And method in controller:
public bool CheckValidate(string start, string time)
{
string datastart = start + " " + time;
DateTime startDate = Convert.ToDateTime(datastart);
EventsEntities dc = new EventsEntities();
var MatchedElements = dc.Events.Where(x => x.start <= startDate && startDate < x.end).FirstOrDefault();
if (MatchedElements == null)
{
return true;
} else
{
return false;
}
}
I want to send string inputs and get back data to show message that is possible to book that room.
Where did I mistake?
You can do like this.
var obj = {};
obj.startdate = document.getElementById('startdate');
obj.starttime = document.getElementById('starttime');
$.ajax({
type: "POST",
url: "/Home/CheckValidate",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
//failure message
}
});
function OnSuccess(response) {
//do your stuff after success response
}
There are a few things missing from your ajax call. You need to specify data you're sending in such way so that it is sent as JSON and properly. To do that you need to stringify your javascript json object and declare that you're sending a JSON data type. Here is your click event handler code with changes:
$(check).click(function () {
var data = {
start: datevalue,
time: timevalue
};
$.ajax({
type: "POST",
url: "/Home/CheckValidate",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "boolean",
success: function (response) {
if (response) {
log.val = "YES";
} else {
log.val = "NO";
}
}
})
});
You can read more about it here: jquery ajax documentation
There are also other existing question here that already answer your question such as this one.

how to append serialize with formdata in ajax

I am tring to append serilize with formdata.It is not working.My controller as two viewmodel with httppostfilesbase as a parameter.i want to append both serilize collection with formdata and i went to send all data including file to controller.it is not working for me.can any one help on this please`
var fileData = new FormData();
if (window.FormData !== undefined) {
var fileUpload = $("#myFile").get(0);
var files = fileUpload.files;
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
}
}
var other_data = $('form').serializeArray();
fileData.append('file',other_data );
debugger
$.ajax({
type: "POST",
url: '#Url.Action("Save", "Settlement")',
data: fileData[0],
contentType: false,
processData: false,
success: function (result) {
if (result.redirectTo) {
} else {
$("#childcontent").html(result);
}
}
})
}
}
There is no need of fileData[0]. Change url to url: '/Settlement/Save',
Also check the console for any errors and revert if you need more information
Can you try with this?
$.ajax({
type: "POST",
url: '/Settlement/Save',
contentType: false,
processData: false,
data: fileData,
success: function(result) {
if (result.redirectTo) {
} else {
$("#childcontent").html(result);
}
},
});

jQuery Mobile pageload code with params not firing

$("#home").on("pageload", function() {
console.log("test2");
var url = window.location.search;
var split = url.split('=');
var vendorID = split[1];
$.ajax({
type: "POST",
url: "vendorpull.php",
data: 'id=' + vendorID,
cache: false,
success: function(data)
{
document.getElementById('vendor-data').innerHTML = data;
}
});
});
This code does not seem to be firing unless the page is physically refreshed. I've tried pageshow, pagebeforeshow and others and it doesn't change. The test console.log does not even fire. This event should be trigged as soon as vendor.html?id=1 is loaded, that is the page that is navigated to containing the above AJAX code. Any suggestions?
$("#home").ready(function() { //You can also use $(document).ready(function() {
console.log("test2");
var url = window.location.search;
var split = url.split('=');
var vendorID = split[1];
$.ajax({
type: "POST",
url: "vendorpull.php",
data: 'id=' + vendorID,
cache: false,
success: function(data)
{
document.getElementById('vendor-data').innerHTML = data;
}
});
});
This code for jQuery Mobile 1.4.5 will reload data for every page visit:
$(document).on("pagecontainerbeforeshow", function(e, ui) {
var pageId = $(":mobile-pagecontainer").pagecontainer("getActivePage").prop("id");
/* JQM NAVIGATE #2 */
if (typeof ui.toPage == "object") {
/* manipulate page navigating to */
switch (pageId) {
case "home":
var url = window.location.search;
var split = url.split('=');
var vendorID = split[1];
$.ajax({
type: "POST",
url: "vendorpull.php",
data: 'id=' + vendorID,
beforeSend: function() {
$.mobile.loading("show");
},
cache: false,
success: function(data) {
$("#vendor-data").html(data);
$("#home .ui-content").trigger("updatelayout");
},
complete: function() {
$.mobile.loading("hide");
},
error: function() {
$.mobile.loading("hide");
}
});
break;
default:;
}
}
});

Clearing uikit html editor

i am trying to clear the content of my uikit html editor after saving data of when closing/cancelling my modal.
i tried clearing it with these codes:
$("#description").val('');
$('#description').attr('data-uk-htmleditor');
$.UIkit.htmleditor('#description', { /* options */ });
but it's still not working. does anyone here can help me?
EDIT:
here's my other codes for pulling the data from the database:
function editTask(id){
key = id;
s_type = 'u';
console.log(s_type);
enableForm('#task');
$('#btn-save-task').hide();
$('#btn-save-edited-task,#btn-cancel-task').show();
$.ajax({
type: "GET",
url: baseUrl+"/opportunities/getInfo/task/"+id,
async : true,
data : {
getType : "getTask"
},
dataType: 'json',
error : function(req,error){
notify(req.statusText,'warning');
},
success: function(data){
$("#taskDescription").val(data.description);
$('#taskDescription').attr('data-uk-htmleditor');
$.UIkit.htmleditor('#taskDescription', { /* options */ });
}
});
}
Try this:
var task = '';
function editTask(id) {
key = id;
s_type = 'u';
console.log(s_type);
enableForm('#task');
$('#btn-save-task').hide();
$('#btn-save-edited-task,#btn-cancel-task').show();
$.ajax({
type: "GET",
url: baseUrl + "/opportunities/getInfo/task/" + id,
async: true,
data: {
getType: "getTask"
},
dataType: 'json',
error: function(req, error) {
notify(req.statusText, 'warning');
},
success: function(data) {
task = data.description;
}
});
}
$.UIkit.htmleditor('#taskDescription', { /* options */ });
//Get a reference to the CodeMirror editor
var editor = $('.CodeMirror')[0].CodeMirror;
//You can then use it as you wish
editor.setValue(task);

How to access success data out of success block in jquery

jQuery.validator.addMethod("uniquerheading", function(value, element) {
var data = false;
$action_name = 'checkunquieannoucementheading';
var url = '<?php echo "$module_name/$controller_name/checkunquieannoucementheading"; ?>';
$.ajax({
url: url,
type: 'get',
data: {
"txt_heading":value
},
success: function(data) {
// Display list on the page by replacing the content on existing, get from the controller-action
return data;
}
});
}, "Annoucement heading already used");
Working Code...Just use async: false
jQuery.validator.addMethod("uniquerheading", function(value, element) {
$action_name = 'checkunquieannoucementheading';
var response = false;
var url = '<?php echo "$module_name/$controller_name/checkunquieannoucementheading"; ?>';
$.ajax({
url: url,
type: 'get',
data: {
"txt_heading":value
},
success: function(data) {
// Display list on the page by replacing the content on existing, get from the controller-action
response = data;
},
async: false
})
return response;
}, "Annoucement heading already used");

Categories

Resources