set value of rating from database using rateyo plugin - php

I am using this rateyo plugin in my application. There is a page where user can give rating to an entity. But before giving rating I am making a check, if that user already assigned a rating to that particular entity and if the user does, then I fetch rating value from database and set it as the plugin says. But if it is a new user, he can submit his new rating.
here is the code what I am implementing:
$(document).ready(function(){
$("#rateYo").rateYo().on('rateyo.set',function(e, data){
$.ajax({
type : "post",
url : "PostRatingValue.php",
data : {
"rating" : data.rating,
"peopleid" : celeb_id,
"userid" : user_id
},
dataType : "json",
success : function(response){
if(response.toString() == "true"){
$.growl.notice({ title: "Growl", message: "Rating<b> "+ data.rating +" </b>assigned successfully" });
}
else{
$.growl.error({ message: "<b>Unable to assign rating.</b>" });
}
},
error : function(response){
$.growl.error({ message: "<b>Something went terribly wrong! :'(.</b>" });
}
});
});
below is the code to set the rating value if it exist.
<?php
if(isset($fetchRatingIdAndValue['ratingpoints'])){
?>
$("#rateYo").rateYo("option", "rating", <?php echo $fetchRatingIdAndValue['ratingpoints'];?>);
<?php
}
?>
});
Problem is that, when old rating is set, an ajax call is made which inserts same data again in table. I want my ajax call to work only when I need to set new rating or edit previous rating. I am not able to find the way out for this. Please help.

When you set the rating after Initialization of rateyo, rateyo.set event will be fired on the element.
Please do not do that, instead If already old rating exists, pass it during initialization itself like
$(document).ready(function(){
$("#rateYo").rateYo({
rating: <?php echo $fetchRatingIdAndValue['ratingpoints'];?>
}).on('rateyo.set',function(e, data){
$.ajax({
type : "post",
url : "PostRatingValue.php",
data : {
"rating" : data.rating,
"peopleid" : celeb_id,
"userid" : user_id
},
dataType : "json",
success : function(response){
if(response.toString() == "true"){
$.growl.notice({ title: "Growl", message: "Rating<b> "+ data.rating +" </b>assigned successfully" });
}
else{
$.growl.error({ message: "<b>Unable to assign rating.</b>" });
}
},
error : function(response){
$.growl.error({ message: "<b>Something went terribly wrong! :'(.</b>" });
}
});
});
});
$fetchRatingIdAndValue['ratingpoints'] should contain 0 if user has not given any rating previously.

Related

if else condition in jquery ajax response

I have one Ajax function which is running properly.but i want when my Ajax response is
<h3>No Couriers found near by you.please select another location</h3>
i want to display some error message else i want to display another map div in else condition.
but every time when i hit Ajax only else condition is working..but when i alert response and see the output it shows this message when
<h3>No Couriers found near by you.please select another location</h3>
but still it not comes in if condition..can anyone help me to do this....
<script>
$('#weight0,#weight1,#weight2,#weight3').click(function() {
var checked = $(this).is(':checked');
if($(this).is(":checked")) {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Orders","action" => "searchCourier")); ?>',
data: {
frmlat: $("#PoolLatitude").val(),
frmlong: $("#PoolLongitude").val(),
mylocation: $("#PoolLocation").val()
},
dataType: "html",
success: function(response) {
alert(response);
if(response =="<h3>No Couriers found near by you.please select another location</h3>"){
alert(thanks);
} else {
$('#map_canvas').css('display', 'none');//used to hide map after ajax success response.
$("#load_map").html(response);
}
},
complete: function() {
$('.spinicon').hide();
}
});
} else {
$("#secretcode").val("");
}
});
</script>
In your php script, return a boolean flag instead of a string :
<?php
if (some_condition) {
$return = true;
} else {
$return = false;
}
die(json_encode(array('return' => $return)));
And in the ajax success :
...
dataType: 'json',
success: function(data) {
if (data.return) {
alert("return is true");
} else {
alert("return is false");
}
},
...
Hope it helps.
PS : use Json Encode to parse the response and access values easily.
First of all, i suggest you to use status for ajax response something like:
1 for success
0 for failure
Than, as per your statement, your are getting the correct response in:
alert(response);
Than, you must need to check either response having <h3></h3> tags or not.
In your code, the main issue is that, you are using string without quotes in alert alert(thanks); this will return undefined thanks in console and treated as a variable.
This should be alert("thanks");
One more suggestion, it's always better to check browser console when you are not getting success in Ajax or any other script, this will help you to find the errors.

Two forms on the same page - errors messages visibles just in first one

I have two steps forms on different modal each.
Three steps on first one (#form1) and the same on second one (#form2).
All inputs and elements with different names and ID.
Links with validation pages (one by step)are working. My problem is just errors messages don't appear on second form. I made the verification with error containers id (one id by form too).
An idea why ?
I try to resolve by coding a array2 of errors for form2 but no error messages visible.
$(".step1").click(function() {
var data = {
'data1' : jQuery("input[name=data1]:checked", "#forml").val(),
'data2' : jQuery('#data2').val(),
'data3' : jQuery('#data3').val(),
};
jQuery.ajax({
url : '/mySite/parsers/check.php',
method : 'POST',
type : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#list_errors').html(data);
}
if (data.result == 'passed') {
$(".frm").hide("fast");
$("#step2").show("slow");
$(".open1").css("display","none");
$(".open2").css("display","inline-block");
}
},
error : function(){
alert('no working.'); }
});
});
That's because you're outputting errors on a div using ID. ID of DIVs should be unique on a single page.
What jQuery does is, it updates the first DIV with list_errors ID and leaves the second one which is in second modal as it is.
Solution:
Use different IDs for each or use class of the DIV and access it with parent() or child() jQuery function.
You have to mention about in which form you need to display error. Also change id='list_errors' to class='list_errors' because its not good to use same id in one page.
$(".step1").click(function() {
var data = {
'data1' : jQuery("input[name=data1]:checked", "#forml").val(),
'data2' : jQuery('#data2').val(),
'data3' : jQuery('#data3').val(),
};
jQuery.ajax({
url : '/mySite/parsers/check.php',
method : 'POST',
type : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
$(this).find('.list_errors').html(data);
}
if (data.result == 'passed') {
$(".frm").hide("fast");
$("#step2").show("slow");
$(".open1").css("display","none");
$(".open2").css("display","inline-block");
}
},
error : function(){
alert('no working.'); }
});
});

PHP Laravel : TokenMismatchException in VerifyCsrfToken.php line 67

Here the scenario is, I want to fetch some data from database and show it to user. While someone give some input and save it to database and I put a status with that which is always "0" until someone see it. So whenever a input has submitted user will see a pop up screen with that new data has inserted in another page. Here the problem is when ajax got some value with status "0" it shown it to screen but when it couldn't fetch any value ( when all the status value is 1)it shows error in console :
TokenMismatchException in VerifyCsrfToken.php line 67
.
How do I solve the issue , any possible suggestion please ?
Here is the route:
Route::post('/unread',[
'uses'=>'ItemController#getUnread',
'as'=>'unread'
]);
Route::post('/s_update',[
'uses'=>'ItemController#status_update',
'as'=>'s_update'
]);
Here is the controller :
public function getUnread()
{
$items=DB::select(DB::raw("SELECT count(*) as total from items where status =0"));
// $data=mysql_fetch_assoc($items);
return Response::json($items);
}
public function status_update()
{
$items=DB::select(DB::raw("UPDATE items SET status=1 WHERE status=0"));
return Response::json($items);
}
and here is the ajax call :
<script type="text/javascript">
setInterval(function(){
$(".container").load("list", function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type : "POST",
url : "{{url('unread')}}",
dataType : 'json',
success : function(data) {
$.each(data,function(index,subcatObj){
if(subcatObj.total != '0')
{
var yes = confirm('You have '+subcatObj.total+' new messages');
if(yes){
status_update();
}
}
});
},
});
});
}, 3000);
function status_update(){
$.ajax({
url:"{{url('s_update')}}",
method:"POST",
});
}
</script>
Change this route
Route::post('/unread',[
'uses'=>'ItemController#getUnread',
'as'=>'unread'
]);
to
Route::get('/unread',[
'uses'=>'ItemController#getUnread',
'as'=>'unread'
]);
I think this is because you are not sending the laravel csrf token in the post.
You need to send a field called "_token" in the json which is the csrf_token provided.
See here : https://laravel.com/docs/5.3/csrf
{{ csrf_field() }}
use this to generae csrf token in your form

Form submission using ajax and page view moderation after the submission

At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.

jQuery: setup multiple periodicalUpdater

I have a problem on jQuery periodicalUpdater
I set up 2 periodicalUpdater
$.PeriodicalUpdater({
url : '../../includes/ajax/admin/countorder.ajax.php',
type: 'text'
},
function(data){
if(data!=0){
$("#counto").load("../../includes/ajax/admin/countorder.ajax.php");
}else{
$("#counto").empty();
}
});
$.PeriodicalUpdater({
url : '../../includes/ajax/admin/countuser.ajax.php',
type: 'text'
},
function(d){
if(d!=0){
$("#countu").load("../../includes/ajax/admin/countuser.ajax.php");
}else{
$("#countu").empty();
}
});
but variable d is getting value of the variable data
How can I set up multiple periodicalUpdater?
thanks
Appears to be an issue with PeriodicalUpdater -> https://github.com/RobertFischer/JQuery-PeriodicalUpdater/issues/20

Categories