Adding username without hardcoding, chatbuilder application - javascript

First off I am openly a newbie (to this site and coding) so I apologize in advance if the answer to this question is overly easy, however I am desperately in need of some help.
I have developed "chatbuilder" as a part of my interview process to a development bootcamp. Unfortunately I hardcoded my username within the chatSend function which includes an ajax call. I want to use the prompt input for the username due to the fact that hypothetically this chat should have the ability to have many users, not just me and the robotchatters. I have spent far too much time trying to figure out the right way to do this, hours worth of trial and error while I realize the fix probably will take about 45 seconds. I am posting my full code, if someone could show me how implement this properly it would be greatly appreciated. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://chatbuilder.hackreactor.com/ChatBuilder.js"> </script>
</head>
<body>
<script>
Chat.guide.start();
delete Chat.display;
delete Chat.fetch;
delete Chat.send;
function chatDisplay(str){
$(".messages").append( "<li>" + str + "</li>");
};
function chatFetch(fun){
var obj = {};
var result = [];
$.ajax({
type : "GET",
url : "https://api.parse.com/1/classes/chats?order=-createdAt",
dataType: "json",
contentType : "application/json; charset=utf-8",
async : false,
complete : function(data)
{
obj = JSON.parse(data.responseText);
}
});
for (var i = 0; i < obj.results.length; i++) {
result.push(obj.results[i]);
};
result.sort(function(a,b){
a = new Date(a.createdAt);
b = new Date(b.createdAt);
return a<b ? -1 : a>b ? 1 : 0;
});
for (var i = 0; i < result.length; i++){
result[i] = result[i].text;
}
fun(result);
};
function chatSend(str){
var user = document.URL.slice(document.URL.lastIndexOf('=') + 1);
var userpost = $.ajax({
type : "POST",
url : "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: 'Daniel: ' + str,}),
dataType: "json",
contentType : "application/json; charset=utf-8",
async : false,
});
return userpost;
};
function chatRefresh(){
$(".messages").empty();
function chatTether(arr){
for(var i = 0; i < arr.length; i++){
chatDisplay(arr[i]);
}
};
chatFetch(chatTether);
};
setInterval(chatRefresh,3000);
$(document).ready(function(){
$(".send").on("click", function(){
chatSend($(".draft").val())
$(".draft").val('');
});
});
</script>
<div class="container">
<h2>Fixed Chat</h2>
<input class="draft" type="text"/> <button class="send">send</button>
<ul class="messages">
</ul>
</div>
</body>
</html>

So, if I did get you in the right way:
first you make smth like this
var promptName = prompt('Enter your name', 'Some name just in case))');
and then you just add this to your ajax func:
function chatSend(str){
var user = document.URL.slice(document.URL.lastIndexOf('=') + 1);
var str = promptName + someElseStringYouWant;
var userpost = $.ajax({
type : "POST",
url : "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: str,}),
dataType: "json",
contentType : "application/json; charset=utf-8",
async : false,
});
return userpost;
};
BTW: Declare the promptName variable in global scope, so your send message function can see it.
UPD: ok, forget 'bout the prompt stuff, I said before, cause it's built in to your lib, and I've found just minified version of it, so i can't find a variable, where it's stored, so you should try your previous method with url
function chatSend(str){
var url = $(location).attr('href');
var user = url.substr(url.lastIndexOf('=')+1);
var fullString = user + ': ' + str;
var userpost = $.ajax({
type : "POST",
url : "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: fullString,}),
dataType: "json",
contentType : "application/json; charset=utf-8",
async : false,
});
return userpost;
};
So, you get substring from your url and it's done.
P.S. you can accept the answer even if you can not upvote ;)

Related

How to make an AJAX request to get a word and store the variable globally

I need to make an AJAX request to API to get the word for a hangman game. Also struggling, on reading the word length and displaying it with placeholders. I referenced this link enter link description here , but am still stuck.
//function to get the word from the API using AJAX
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
//accessing global variable (word)
var results = $.getValues("https://hangman-api.lively.software");
for (var i < 0; i < word.length; i++) {
results[i] = "_";
}
Hopefully my snippet can help you in some ways. have a nice day!
$(function(){
$.ajax({
url: "https://hangman-api.lively.software/",
type: 'get',
success: function(data) {
//how to access word
console.log(data.word)
//how to create placeholders
placeHolder = " _ ";
placeHolders = placeHolder.repeat(data.word.length)
//how to print place holder
$(".placeHolder").text(placeHolders)
}
});
})
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Placeholders : <span class="placeHolder"></span>
</body>
</html>

Is my JavaScript code correct?

I am trying to get JSON out of my Rest API and want to use this JSON information to show them on my application.
Is the function renderUserState ever called? Because the rest of my Code should work fine.
function testSubmit() {
var card = getQueryVariable("select_card");
var action = getQueryVariable("select_action");
var urlGet = "/test/api/getting-ready?cardId=" + card + "&action=" + action;
$.ajax({
type : 'GET',
url : urlGet,
dataType : 'json',
encode : true
}).done(renderUserState);
}
function renderUserState(userState){
$("#gold").text(userState.goldAmount);
}
Thanks for your help!
Yup, your code is correct you just need to call a function in the done since the done will receive the data returned by your endpoint.
Hope this will help you click on the button and see the log.
function testSubmit() {
// var card = getQueryVariable("select_card");
// var action = getQueryVariable("select_action");
// var urlGet = "/test/api/getting-ready?cardId=" + card + "&action=" + action;
var urlGetTest = "https://jsonplaceholder.typicode.com/posts";
$.ajax({
type : 'GET',
url : urlGetTest,
dataType : 'json',
encode : true
}).done((userState) => {
renderUserState(userState);
});
}
function renderUserState(userState){
console.log(userState);
// $("#gold").text(userState.goldAmount);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="testSubmit();">Click Here</button>

Unable to display results using jquery ajax

I am trying to implement a comment feature on my page. I have an itemID 123. on that page, I would like to display the comments that people have posted about itemID 123. However as of now, I am unable to display these comments on my page. There are no errors in the console.
Javascript:
function mywall() {
var url = serverURL() + "/viewwall.php"; //execute viewwall.php in the server
itemID = decodeURIComponent(getUrlVars()["itemID"]);
var JSONObject = {
"itemID": decodeURIComponent(getUrlVars()["itemID"])
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_mywallresult(arr); //success. execute _mywallresult()
},
error: function () {
validationMsg();
}
});
}
function _mywallresult(arr) {
var i;
//for all the shouts returned by the server
for (i = 0; i < arr.length; i++) {
//append the following:
//<b>
//time of posting </b>
//<br/>
//the message
//<br>
//userid
$("#wallcontentset").append("<b>" + arr[i].timeofposting + "</b><br/>" + arr[i].message + "<hr>" + arr[i].userid);
}
}
HTML:
<div data-role="content" class="ui-content" id="wallcontentset"></div>
Try the following :
success: function (response) {
_mywallresult(response.arr);
},

AJAX post - {"readyState":0,"responseText":"","status":0,"statusText":"error"}

I have this javascript but it is not working : I receive the following error : {"readyState":0,"responseText":"","status":0,"statusText":"error"}
This script is included in a webpage of my site which is in a subdirectory of the site.
From my debugging, I do not understand where the error can come from... (since I do quite exactly the same for the index webpage of my site with another javascript which looks almost the same)
$(document).ready(function() {
//if submit button is clicked
$('#filterbtn').click(function () {
//Get the data from all the fields
var a = JSON.stringify( $("#multiselect").val() );
var b;
if ($('#b').prop('checked')) {
b = 0;
} else {
b = 1;
}
var c = JSON.stringify($("#Sliderstart").slider("value"));
var d = JSON.stringify($("#Sliderend").slider("value"));
//organize the data properly
var data = 'b=' + b + '&c=' + c + '&d=' + d + '&a=' + a;
//start the ajax
$.ajax({
url: "./filter.php",
type: "POST",
data: data,
crossDomain: true,
cache: false,
success: function (html) {
document.getElementById("message").innerHTML=html;
},
error: function (e) {
alert(JSON.stringify(e));
}
});
return false;
});
});
Thank you guys !
Cheers
This is the kind of error you get when you request an url that doesn't exist.
Try changing this:
url: "./filter.php"
to an aboslute path like this:
url: "/PATH_TO_FILTER/filter.php"

If new data else stop insert over and over

To keep it simple, I'm just wanting to know how I'd go about and if else statement against my ajax to print new data out once if it finds it and not the same data over and over again. Amd how can I possibly store the last id as a variable to reuse it when searching for more new records?
Someone mentioned to me also I could save the new notification idea as a return so when the ajax restarts it uses this to find the next new set of results.
Has anybody got any ideas how to achieve these?
<script type="text/javascript">
setInterval(function(){
var time = new Date().getTime();
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
}
});
},20000);
</script>
Regarding to store the last id, you could use:
window.localStorage.setItem('key', 'value');
Then when you want to get it again you'll should use:
var lastId = window.localStorage.getItem ('key');
And regarding the duplicates issue, well, you should have a internal storage in order to handle the recieved data. May be an array can help as storage, also you can also store this array in local storage.
Once you handle this data storage, you could apply something like this to verify that your data has no duplicates:
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
UPDATE
var notification_id = window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler(response);
if(response.num){
window.localStorage.setItem('lastId', response.num);
}
});
},20000);

Categories