How to get the property of a model in Javascript? - 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.

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.

Making a counter for #StopTheFire

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

How do I get the specific part of a URL using jQuery and JavaScript?

I am checking out an order in WordPress via jQuery AJAX. Upon successfully posting, WordPress returns a response to me with a result success value and url value.
I want to get the particular part of this url so I can use the id as an object for my purpose.
This is the structure of the url: http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459
This is my current code:
j('.my-checkout').on('submit', function(evt) {
evt.preventDefault();
var billing_customer_type = j("#billing_customer_type").val();
// and so on...
j.ajax({
type: 'POST',
url: 'http://localhost/mywebsite/ajax=checkout',
cache: false,
data: {
'billing_customer_type': billing_customer_type,
// and so on..
},
success: function(result) {
var orderResponseUrl = result.redirect;
j('.order-response-url').html(orderResponseUrl);
// http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459
orderResponseUrl.split("/");
console.log(orderResponseUrl[3]);
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function() {}
});
});
The result of my code above is just the the letter "p". I think because it started of the first letter of http and I used the index [3].
Do you know how can I get the specific part of the url that is 28564?
If the URL that you need to interact with is always the same, you can split the returned url at the 'order-received/' portion (which gives an array of everything before that, and everything after it).
Then rather than splitting again on the '?" which is another way of doing it - you can use parseFloat() to get the order number. This works since parseFloat returns all numerical values up to but not including the first non-numerical character ("?").
var urlStr = 'http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459';
var orderNumber = parseFloat(urlStr.split('order-received/')[1]);
console.log(orderNumber); //gives 28564
Because when you do orderResponseUrl.split("/"); it does NOT change orderResponseUrl, it creates a new array.
var parts = orderResponseUrl.split("/");
console.log(parts);
if the length is always same then you can use substring function.
var str = "Hello world!";
var res = str.substring(1, 4);
now res contain
console.log(res); // ell
if you do not know the index, you can find like this.
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
now n look like
console.log(n); // 13

How to extract a single value from an array

I am very new to JavaScript so forgive me if this is a dumb question:
I have this Ajax call:
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
console.log('success', data)
}
});
The value "data" produces an array:
success [{"price":"120.00"}]
What I need, is to extract the value of price (the 120) and use it later in an addition.
How do I get this value out?
You can do:
var price = data[0]['price'];
or:
var price = data[0].price;
Either of these work like this: you are accessing the first value in your array named data, and then the field in that value named "price". Assigning it to a variable isn't necessary.
However, you would probably want to do this inside a loop, iterating over all values of data so that, in the case the first element of data isn't what you want, you can still catch it. For example:
data.forEach(function(i) {
console.log(data[i].price);
//do stuff with the value here
});
data has an array of objects with a price property. Access the first object in the array and parse it's price as a number:
parseFloat(data[0].price);
Test it,
You must parse JSON string before using it!
var data = JSON.parse('[{"price":"120.00"}]');
var Price = data[0].price; // 120.00
//OR IF it's Single And not Array
var Price = data.price; // 120.00
Since your response is an array, access the first position, and then access the object property:
data[0].price; //"120.00"
var result = {},
sum = 0;
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
result = data[0];
}
});
sum = parseFloat(result.price) + 2.25;

More user friendly search box in MVC

I have implemented searchbox using jQuery. Here is the code which sends search term and
after that I receive Json which I use to make list of matched searched items.
The problem is that on each keyup I delete all matched items :
$("#realPlaceForSearchItems").html("");
because if I don't that I get duplications when searching for product if I enter "pro" and then type "d". (I am appending list items to the list) Is it possible to achieve that I somehow just delete elements that do not match "prod" (which previously matched "pro" ofcourse) and that elements that match prod stay untouched after typing "d".
$("#searchInput").keyup(function () {
$this = $(this);
$('#realPlaceForSearchItems').show();
$("#realPlaceForSearchItems").html("");
var seachedTerm=$this.val();
if ($this.val().length> 2)
{
$("#realPlaceForSearchItems").html("");
$('#realPlaceForSearchItems').show();
$.ajax({
type: "POST",
url: ROOT + "Filter/Search/",
data: {term: $this.val()},
success: function (data)
{
var Link = $("#searchTemplate>li>a");
var placeForProductId=$("#searchTemplate>li>a>input");
var placeForPicture = $("#searchTemplate>li>a>div>img");
var placeForProductName = $("#searchTemplate>li>a>div>div");
var placeForPrice= $("#searchTemplate>li>a>div>span");
$.each(data.productsWereSeached, function () {
console.log("sddsd", data.totalrows);
var imagesFolder="/Content/images/";
var pathToProduct="/ProductDetails/Index/"
var slash = "/";
Link.attr("href", pathToProduct + this.Id);
placeForProductId.val(this.Id);
if (this && this.Picture) //for the case there is no any picture there would be error cant read propery or undefined
placeForPicture.attr("src", imagesFolder + this.Id + slash + this.Picture.FileName);
else
placeForPicture.attr("src", "");
placeForProductName.html(this.Name);
placeForPrice.html((parseFloat(this.Price) / 100.0).toString() + " kn");
$listItem = $("#searchTemplate").html();
$("#realPlaceForSearchItems").append($listItem);
});
$("#nOfMatchedProducts").val(data.totalrows);
if (data.totalrows > 2)
{
var searchurl="/Search/ShowMoreSearched?term="
$showMoreItem = $("#showMoreItem").html();
$("#showMoreItem>li>a").attr("href",searchurl+seachedTerm);
$("#realPlaceForSearchItems").append($showMoreItem);
}
},
failure: function ()
{
}
});
}
});
$.each(data.productsWereSeached, function () {
if($('a[href="'+pathToProduct + this.Id+'"]').length == 0) {
console.log("sddsd", data.totalrows);
var imagesFolder="/Content/images/";
var pathToProduct="/ProductDetails/Index/"
var slash = "/";
Link.attr("href", pathToProduct + this.Id);
placeForProductId.val(this.Id);
if (this && this.Picture) //for the case there is no any picture there would be error cant read propery or undefined
placeForPicture.attr("src", imagesFolder + this.Id + slash + this.Picture.FileName);
else
placeForPicture.attr("src", "");
placeForProductName.html(this.Name);
placeForPrice.html((parseFloat(this.Price) / 100.0).toString() + " kn");
$listItem = $("#searchTemplate").html();
$("#realPlaceForSearchItems").append($listItem);
}
});
Psst... I'm assuming you also want to limit calls to the server and that your search result list is not wildly huge!
So! Benefit to your current approach is you don't have to manage/compare any existing data set. This makes things easier when a search for "pro" changes to a search for "cro" or any other change that makes the previous AJAX call irrelevant. But, like you said, it leaves you with this clear then re-add items inefficiency when you search for "prod" after "pro".
Idea:
Store the most recent AJAX call criteria in a global.
If new search value includes the latest AJAX search value, filter/hide items in the existing data set which do not match the new criteria. Do not perform a new search.
If new value does not include the latest AJAX search value: clear current data set, update AJAX search value, execute new AJAX call
Pass the index from $.each (http://api.jquery.com/jQuery.each/) into your function, then use it to select the search result you will replaceWith (http://api.jquery.com/replaceWith/) the element you just built. In using this method, your four LI elements within the search results UL must exist before a search.keyup is executed.
Do this by changing two lines...
$.each(data.productsWereSeached, function (index) {
... all of the existing code in the loop stays the same except ...
$("#realPlaceForSearchItems LI:eq(" + index + ")").replaceWith($listItem);
});

Categories

Resources