jQuery Raty set score inside click event - javascript

I'm trying to use this rating plugin but I was unable to set the new score on click.
I'm making an ajax request on click event and get new calculated score. I wanted to set the new score inside the click event. What is the right way to do it?
<div class="rating" data-id="some-int" data-score="0.5"></div>
Javascript:
$(".rating").raty({
score: function () { return $(this).attr("data-score"); },
click: function (score, evt) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "./ajax.asmx/RateImage",
data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
dataType: "json",
async: false,
success: function (result) { actionResult = result.d; }
});
if (actionResult.Success) {
console.log("Score: " + actionResult.Message);
score = actionResult.Message;
} else { // cancel rating
alert(actionResult.Message);
return false;
}
}
});

There is a built in method to set new score, so just use:
$('.rating').each(function(i) {
var thisRating = $(this);
thisRating.raty({
score: function () {
return $(this).data('score');
},
click: function (score, evt) {
$.ajax({
type: 'post',
contentType: 'application/json; charset=utf-8',
url: './ajax.asmx/RateImage',
data: {
ImgId: thisRating.data('id'),
Score: score
},
dataType: "json",
success: function (result) {
thisRating.raty('score', result.d.Message);
}
});
return false;
}
});
});
Under docs - Functions you will find:
$('#star').raty('score');
Get the current score. If there is no score then undefined will be
returned.
$('#star').raty('score', number);
Set a score.

You can do
$(".rating").raty('setScore', score);
See it working
http://codepen.io/anon/pen/qdVQyO

According to the documentation, you can simply do $('#selector').raty({score: 3}) to set the score. So in the callback, you can call $(".rating").raty({score: actionResult.Message}) like so:
$(".rating").raty({
score: function () { return $(this).attr("data-score"); },
click: function (score, evt) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "./ajax.asmx/RateImage",
data: "{ ImgId: " + $(this).attr("data-id") + ", Score: " + score + "}",
dataType: "json",
async: false,
success: function (result) { actionResult = result.d; }
});
if (actionResult.Success) {
console.log("Score: " + actionResult.Message);
$(".rating").raty({score: actionResult.Message});
} else { // cancel rating
alert(actionResult.Message);
return false;
}
}
});

Related

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

Loading finishing before everything has loaded from multiple functions

I'm sure this is going to be something really simple, but I am having a problem when calling a function which needs to do various different function calls via ajax to a .net code behind and I want to show a loader over the page until everything has finished, but its not happening.
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
checkSession();
expand2(ID, user);
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
Which calls
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
});
}
and
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
});
}
But the loading overlays are disappearing before it is finishing doing what its doing? I've seen something about using $.when for my calls but I'm not sure how to get this working properly?
Any advice would be great. Thanks
Try to hide loading in expand2 or checkSession function on finish request. Like this
... .done(function () {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
});
So loader will be hidden after everything will have finished.
To be sure that everything is over, you can set "flag". For example check = 2. And do
check--; check||$('.loadingBlackSml, .loadingSml').fadeOut(1000);
edited 10.04.17
Example with flag (check) for requests
var check = 0; // count pending requests
function expand(ID, user) {
$('.loadingBlackSml, .loadingSml').fadeIn(1000);
count = 2;
checkSession();
expand2(ID, user);
}
function checkSession() {
return $.ajax({
type: "POST",
url: "/Test.aspx/checkForSession",
//data: "{}",
data: "{'idleTime':'" + clickedDT + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (sessionCheck) {
sessionActive = JSON.stringify(sessionCheck.d);
}
}).done(function () {
//if session comes back as dead, redirect to restart session
if (sessionActive == "\"false\"") {
var url = "/Error.aspx?RefreshNeeded=true&page=" + window.location.pathname;
$(location).attr('href', url);
}
//if page has gone past timeout length, try and reload it
else if (sessionActive == "\"timeout\"") {
var urlTO = window.location.pathname;
$(location).attr('href', urlTO);
}
count--;
if (count === 0) { // check. are all requests finished
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
function expand2(ID, user) {
return $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '/Test.aspx/markExpanded',
data: "{'ID':'" + ID + "', 'user':'" + user + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
}).done(function () {
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
});
}
Of course, you can move
count--;
if (count === 0) {
$('.loadingBlackSml, .loadingSml').fadeOut(1000);
}
to separate function

Looping through two JSON arrays Ajax

I'm trying to get data from a Json file using the id from a previous previous ajax call looping through the the second array based on the id gotten from the first
I have tried
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
$('.blog').empty();
for (var i=0; i<n; i++) {
var storytitle = output.data[i].story_view;
var id = output.data[i].titleID;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var n2 = output2.data[0].episode_count;
for (var i=0; i<n2; i++) {
var titles = output2.data[i].title;
console.log(storytitle + " " + titles);
}
}
else {
console.log('faileds');
}
});
}
} else {
console.log('failed');
}
});
});
The storyTitle has a single value and loops through all the titles when i check my console.
I tried debugging and found out the second for-loop was only executed once, after executing request2.done, it goes back to the first for-loop after the first has finish all its loop, it executes the second for-loop.
I don't know where am missing it.I need help with this.
Finally solved the problem...Changed my code to...
$(document).on('click', '.stories', function(e) {
e.preventDefault();
var request = $.ajax({
url: 'includes/functions.php?job=front_title',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function (output) {
if (output.result === 'success') {
var n = output.data[0].title_count;
var jsonArray = $(jQuery.parseJSON(JSON.stringify(output.data))).each(function() {
var id = this.titleID;
var CLASS = this.story_view;
var request2 = $.ajax({
url: 'includes/functions.php?job=story_episodes',
cache: false,
data: 'id=' + id,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request2.done(function (output2) {
if (output2.result === 'success') {
var jsonArray2 = $(jQuery.parseJSON(JSON.stringify(output2.data))).each(function() {
var id2 = this.id;
console.log(id + " " + id2);
})
}
})
})
} else {
console.log('failed');
}
});
})
And it worked fine....thanks to Swapnil Godambe

Can I use jquery's .done() more than once?

I have 2 JS literals:
var obj1 = {
Add: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/add",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
var obj2 = {
List: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/list",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
And this is my document.ready:
$(document).ready(function () {
obj1.Add(1).done(function (data) {
alert('you added ' + data);
});
obj2.List().done(function (data) {
$.each(jQuery.parseJSON(data), function (i, item) {
// fill a combo box
});
});
});
jQuery just executes the first call and obj2.List() ain't called at all.
How to properly use the deffered objects in this case?
Change your Add and List function to RETURN the ajax object.
Add: function (id) {
return $.ajax({..
and
List: function (id) {
return $.ajax({...
This way - it will return the jqXHR obj which will return the deferred object.
This implement the Promise interface which has : the callbacks you are looking for.
edit :
look at this simple example which does work :
var obj1 = {
Add: function (id) {
return $.ajax({
type: "get",
data: JSON.stringify({
"id": 1
}),
url: "http://jsbin.com/AxisAmi/1/quiet",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("at success --"+data.data)
}
});
}
};
obj1.Add(2).done(function (a){alert("at done --"+a.data);});

Ajax doesn't execute success function

My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});

Categories