Is my JavaScript code correct? - javascript

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>

Related

calling the ajax call from another file

I want to put the ajax call in outside jsp and call it in the JS file .. here is my code
deleteRow : function() {
$("input:checkbox:checked").each(bindContext(function(index, item) {
var str = $(item).attr("id");
str = str.substring(str.indexOf("_") + 1);
var id = this.data[str][this.columns[1]];
$.ajax({
url : '/Spring3HibernateApp1/deleteDep',
type : 'GET',
data : {
"id" : id,
},
dataType : "json"
});
So what if I want to just put the ajax call in function in another jsp ??

Make a textbox visible and other css changes on ajax success

function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = document.getElementById('searchClientCellPhoneNo').value;
$.ajax({
type:"POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function(result){
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
window.location.reload(true);
}
});
}
The textboxes do not become visible in the ajax success, though I have verified control goes to the success block.
I think this is because of window.location.reload(true), why do you think to reload the page again!!
As per my understand, when the page is reloaded for a second time, the search input parameter becomes null/empty, so in this snippet var cellValue = parseInt(thisCell.text()); cellValue is null/undefined.
Because of this, the following two lines do not function as expected
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
If you want to keep your status like :
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
you should store a boolean in the user localstore or a cookie (on ajax success). Then on the page just have a document ready:
$(document).ready({
if(localstorage/cookie) { / check the status of your cookie or localstorage
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// clear the cookie or the localstorage
}
});
I hope this gives you an idea man...
There were a few things wrong. Primarily you were reloading the page, which is probably the main issue.
Also you had a few small issues with your number parsing and validating. I have fixed it below.
function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = $('#searchClientCellPhoneNo').val();
$.ajax({
type: "POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function (results) {
$("#progressbar").hide();
$("#example td").each(function () {
var thisCell = $(this);
var cellText = thisCell.text();
// This will update your textbox...
$("#selectedClientName").val(result.clientName);
// And this is an example of updating based on an array of data.
result.transactions.forEach(function(result){
// Create a list item and append it to the list.
$('<li></li>').text(result).appendTo('#resultList');
});
// If the cell text is a number...
if (!isNaN(cellText)) {
// Parse the text to a base 10 integer...
var cellValue = parseInt(thisCell.text(), 10);
if (cellValue >= $("#selectedClientRewardPoints").val()) {
thisCell.css("background-color", "#FF0000");
}
}
});
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// Do not reload the page.
}
});
}
Thanks #JimmyBoh for the pointers, this is how I fixed the issue :
1) Used struts2-json library. In struts.xml, added below:
<package name="json" extends="json-default">
<action name="searchClientCellPhoneNo" class="com.intracircle.action.RedeemAction" method="searchClientCellPhoneNo">
<result type="json">
<param name="root">jsonData</param>
</result>
</action>
</package>
2) In the action class, added a jsonData Map as follows :
private Map<String,Object> jsonData = new HashMap<String,Object>();
Added getters and setters for jsonData
public Map<String,Object> getJsonData() {
return jsonData;
}
public void setJsonData(Map<String,Object> jsonData) {
this.jsonData = jsonData;
}
In the action method, added data to be returned to jsp to the jsonData Map as follows :
public String searchClientCellPhoneNo() {
clientList = userdao.getClientsList(searchClientPhone);
if(clientList != null && clientList.size() > 0) {
selectedClientName = clientList.get(0).getProfileName();
jsonData.put("selectedClientName",selectedClientName);
int storeId = ((Stores)SecurityUtils.getSubject().getSession().getAttribute(SESSION_CONSTANTS.SESSION_STORE)).getStoreId();
selectedClientRewardPoints = redeemDao.getCountRewardPointsForClientForStore(storeId, clientList.get(0).getId());
jsonData.put("selectedClientRewardPoints", selectedClientRewardPoints);
}
viewRedeemScheme();
return SUCCESS;
}
3) In the jsp ajax method, did the following changes : Make sure, you add dataType:'json' and if you want to print the ajax result using alter, stringify it.
$.ajax({
type:"GET",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
dataType: 'json',
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
success: function(result){
alert("result: " + JSON.stringify(result));
console.log("Result " + result);
$("#selectedClientName").val(result.selectedClientName);
$("#selectedClientRewardPoints").val(result.selectedClientRewardPoints);
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientNameLabel").show();
$("#selectedClientRewardPointsLabel").show();
$("#selectedClientRewardPoints").show();
}
});
Thanks everyone for the help, especially #JimmyBoh.

How to bind button function to a corresponding item in an array - AJAX, Firebase

I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}

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"

Adding username without hardcoding, chatbuilder application

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 ;)

Categories