Making a counter for #StopTheFire - javascript

So, I just wanted to make a counter for #StopTheFire Which how can I extract the number from <span>? I also saw some post on twitter asking about this. With JavaScript. Can I use WrapAPI for this? Thanks.
Part of the code from StopTheFire.gg:
<span>$25,692</span>

Get the html of the site
Use jQuery:
$.ajax({ url: 'your-url', success: function(data) { alert(data); } });
This data is your HTML.
.getElementsByTagName("span") will return you a collection of elements. Here you might have to parse first and select by id or class because there will be wrong spans...
Then, you might want to use .innerHTML:
For your case you would just loop through
var spans = document.getElementsByTagName("span");
and for each of those
var array_values = []
var value;
for(key in spans) {
value = spans[key].innerHTML;
array_values.push(value)
}

Related

Ajax call to get list of objects clicked on

I am trying to use an AJAX call to send data to my django view, which I then hope to use in another view. When a user clicks on a particular word, known_words must go up by one (this part works). But I also want to know which word the user clicked on (I have access to this in the template: {{item.0}}. And this is the part that I cannot get to work.
The relevant part of my html (this is the last column of my table, the first column contains {{item.0}}):
Yes
My js:
$(document).ready(function() {
var known_words = 0;
var clicked_words = [];
$(".word_known").click(function() {
known_words++;
var reference = this;
var songpk = $(this).data('songpk');
var userpk = $(this).data('userpk');
var clicked_words = $(this).data('clicked_words'); //I know this part is wrong, how can I append the word to the list?
$.ajax({
url: "/videos/songs/vocab/known/"+songpk+"/"+userpk+"/",
data: {known_words: known_words, clicked_words: clicked_words},
success: function(result) {
$(reference).removeClass("btn-warning");
$(reference).addClass("btn-success");
$(reference).text("Known");
},
failure: function(data) {
alert("There is an error!")
}
})
});
})
Views:
def word_known(request, pk_song, pk_user):
if request.method =='POST':
pass
elif request.method == 'GET':
known_words = request.GET.get('known_words', '')
clicked_words = request.GET.get('clicked_words', '')
request.session['known_words'] = known_words
clicked_words = []
clicked_words.append(request.session['clicked_words'])
print('The number of known words is {} and clicked words are {}'.format(known_words, clicked_words))
return HttpResponse(json.dumps(known_words))
In the console, when I click on a word (not 'hello'), I get the following in the console:
The number of known words is 1 and clicked words are ['hello']
And if I click a second time on a different word:
The number of known words is 2 and clicked words are ['hello']
So the counter is working, but not the word list. How can I fix that?
I haven’t tested this, but I think you are overwriting the Array instead of adding to it.
This line
var clicked_words = $(this).data('clicked_words');
Should be
clicked_words.push($(this).data('clicked_words'));
This is a link to the documentation on MDN
In addition to #Daniel Butler's answer, I had to change my view as follows:
clicked_words = request.GET.getlist('clicked_words[]')
Because apparrently when you send a list through jQuery it changes the keyword as well.

How to retrieve a specific object from a JSON value stored in sessionStorage?

I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}

How to get the property of a model in Javascript?

I want to get the property of a model in javascript. So my ajax call is receiving a list of models from the controller. In javascript, after success, I want to obtain a particular property of the model. Below is my script:
$("#filter").keyup(function () {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Search',
success:
function (result) {
console.log(result.Books);
var filter = $("#filter").val();
console.log(filter);
// Loop through each row of the table
result.Books.forEach(
(function (book, index) {
console.log(index);
var i = index;
var title = book[index];
// If the list item does not contain the text phrase fade it out
if ($(title).text().search(new RegExp(filter, "i")) < 0) {
$(book).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(book).show();
}
})
)
}
});
});
As you can see, I have tried var title=book[index]. I want something like this:
var title = book[index].Title;
where Title is one property of the model(here book). Any idea how to do this?
Just use book.Title.
book is an element of the result.Books collection, so you don't need to use index.
When looping through an array of objects, as you're doing, each time you loop, you get the next instance of your object.
So, in your example, book is a simple object, within your forEach loop. So the statement book[index] is wrong.
The way to access your title property would be:
book.Title
Continuing with your code, replace $(title).text().search(new RegExp(filter, "i")) with the following line:
book.Title.search(new RegExp(filter, "i))
book.Title is a string and you can apply the javascript search method to a string. When you write $(title), jQuery is trying to find an element in the DOM based on the book's title. I don't think that is what you're trying to do.

Parse 2-dimensional array retrieved as string from database

I am building an array of data that is being retrieved from the cells of a table. The resulting array looks something like this:
[["","","",""],["","9/2/14","","9/17/14"],["","","89ol",""],["","687k","","9-0["p/"],["","245g","245g","356h"],["","","",""],["","","4j6","467j"],["","","9/9/14",""]]
I'm saving the data to a MySQL database as a string in one field. I now need to retrieve that data and iterate through it to repopulate the table.
I'm getting the data to an $.ajax function as a string in the above format.
How can I get the individual cell data to populate the cells properly?
UPDATE:
Here's the php code I'm using to retrieve the data:
$queryGetUserTaskNotes = "SELECT userProgressNotes FROM userProgress WHERE userProgressUserID = $userID AND userProgressSiteID = $siteID and userProgressNotesTable = '" . $taskTableID . "'";
$resultGetUserTaskNotes = #mysqli_query($dbc,$queryGetUserTaskNotes);
if ($resultGetUserTaskNotes) {
$taskNotes = mysqli_fetch_assoc($resultGetUserTaskNotes);
echo $taskNotes['userProgressNotes'];
}
Here's how I'm getting the data from the php script
function GetTaskNotes(siteID,tableID) {
$.ajax({
url: 'script.php',
data: {getTaskNotes:'true', userID:userID, siteID:siteID, tableID:tableID},
success: function(data) {
console.log('GetTaskNotes data: ' + data);
}
});
}
As for what I've tried so far, I've been working with how to parse the string on the js side in the success function. JSON.parse(data) didn't work and frankly, I'm not sure what else to try.
Thanks!
Unless you have very special needs in terms of performance/logic, I would say it would be better to use a hash of name/value pairs (a.k.a an object) where the names in the hash correspond to actual fields in the database. That being said, lets say for the sake of argument that the arrays are populated by .push() calls, in which case a simple nested for loop should work:
'use strict';
var array = JSON.parse(string);
var cell, row, i, j;
var table = document.createElement('table');
for (i=0; i < array.length; ++i) {
row = document.createElement('tr');
for (j=0; j < array[i].length; ++j) {
cell = document.createElement('td');
cell.innerHTML = array[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.appendChild(table);
Where string is the string you get back from the DB when its time to repopulate.
I think the steps here for you are going to be:
In PHP, provide a URL that JS can do a GET against that will return the data. The way that is structured and looks will depend somewhat on what framework (if any) that you're using. Be sure to return that data as JSON using a built in PHP JSON encode method.
In JS, do a GET like so:
$.ajax({
url: 'your url here',
type: 'GET',
success: function(data) { console.log(data); }
});
In your success function, I assume you'll handle iterating over your object and inserting it into the DOM. I would look at jQuery's $.each() method for that. When it comes to "populating the cells properly", it'd be helpful to see your HTML and JS in a jsFiddle or something.
Good luck!
References:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jquery.each/

How can I "Parse" array returned by ajax?

I have 3 spans on my page that contain numbers. On click of a button I would like to retrieve an ajax response, and if the response is valid (it should be an array of 3 elements) I would like to update the numbers in these spans. Could you please recommend a solution via jQuery?
Thank You.
$.getJSON(url, function(resp)
{
var list = resp.list;
if(!list)
{
throw new Exception("list is not set");
}
for(var i = 0; i < list.length; i++)
{
$('#span' + (i + 1)).text(list[i]);
}
});
if the spans have ids span1, span2, and span3. See $.getJSON for more information. Note that you can add error handling by using $.ajax instead.
You can just implement this by usig jQuery.getJson(url,callback(data,textStatus)) .
for example :
$.getJSON(url, function(data,textStatus){
var spanValues = data.list;
$('#span_Id').text(spanValues [i]);
...
});

Categories

Resources