I have a jQuery up vote plugin. Everything is working fine except the error handling. My up vote plugin is in a foreach loop. like this below
if($RES['counter'] === '1'){
echo '
<td>
<div data-id='.$id.' class="upvote upvote-serverfault">
<a style="cursor:pointer;" class="upvote upvote-on" title="This idea is helpful"></a>
<span class="count">'.$counter.'</span>
<a class="downvote"></a>
<span id='.$index.'><span class="votingFeedback"></span>
</div>
</td>';
}
else
if($RES['counter'] === '-1'){
echo '
<td>
<div data-id='.$id.' class="upvote upvote-serverfault">
<a style="cursor:pointer;" class="upvote upvote-down" title="This idea is helpful"></a>
<span class="count">'.$counter.'</span>
<a class="downvote downvote-on"></a>
<span id='.$index.'><span class="votingFeedback"></span>
</div>
</td>';
}
The problem is when the user tries to span my voting system it will throw an error.The error checking is done in my PHP file and It's working but when I tries to dispaly the error on screen instead of showing the message on that particular topic is it shows on all the topic id
I was trying to make something like stack overflow. If you try to span the up or down vote it will throw and error but it's seems harder then I thought
My ajax call to my php file
<script>
var callback = function(data) {
$.ajax({
url: 'voting.php',
type: 'post',
data: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred },
success: function(data) {
$(".votingFeedback").html(data);
}
});
};
$('.upvote').upvote({callback: callback});
</script>
When you get a response back from your ajax request you are selecting all voting feedback elements on the page because you are using a class selector. This is updating all the span with the class votingFeedback
You need to use a selector that is unique to the element you want to update. You already have a container div with the id. Use that as part of the selector.
$("[data-id='" + data.id + "'] .votingFeedback").html(data);
But you will also want to rename the parameter of the success function because you are defining data twice. This will mean that data.id doesn't exist anymore. Rename it to something like response or rename the parameter of the outer function.
You are getting unrecognized expression because you are replacing your original data variable with the new results from the ajax. from #allcutt answer try changing it to this.
var callback = function(data) {
$.ajax({
url: 'voting.php',
type: 'post',
data: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred },
success: function(result) {
$("[data-id='" + data.id + "'] .votingFeedback").html(result);
}
});
};
$('.upvote').upvote({callback: callback});
Related
How do you reload a page without re-fresh after sending a javascript variable to PHP via Ajax.
Below is an image of a webpage I'm creating which analyses asset performance.
What I'm trying to do is the following.
When a user selects a test block with in the graph, the selcection box is updated with all subtests within that specific test block. However, I do not want to refresh the page. I have managed to send the the selected tested block to the PHP code via ajax, but can not get ajax to reload the page without a refresh.
Currently, when a test block is selected, the label is return to PHP and is stored in the $_SESSION['label'] variable. This is then used in the panel header #subtest-chart-select. However the label will not update without a page refresh which is what I want to avoid.
Ajax:
$("#test_block_chart").click(
function(evt){
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
//alert(label);
$.ajax(
{
url:'test_performance.php',
type: 'POST',
datatype: 'json',
data: {'label':label}, // post to location.php
success: function(label) {
// success
},
error: function(label) {
alert("There may an error on uploading. Try again later");
}
});
}
});
});`
PHP:
session_start();
if(isset($_POST['label']))
{
$_SESSION['label'] = $_POST['label'];
}
PHP echo HTML
<?php
echo '<div class="row">
<div class="col-lg-12 subtest-select">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i>' . $_SESSION['label'] . ' Subtest Select </h3>
</div>
<select class="form-control">
<option>1</option>
</select>
</div>
</div>
</div>'
?>
I'm still to write the PHP code to update the options of subtests within the selected test block.
Any help will be greatly appreciated as I've been trying to get this working for what seems like forever.
In $.ajax() set
dataType: 'text',
In your $.ajax() success function say:
success: function(data) {
$('.inside_whereever_you_want_to_show_this').html(data);
}
Edit:
To update only one value on page you can:
a) in PHP print out only this value (so that whole page would be only this value).
<?php echo $_SESSION['label']
and in HTML put a span around the bit you want to update (avoid constructing longer strings in javascript, all constant parts should be in HTML)
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i><span class="subtest-updateable">' . $_SESSION['label'] . '</span> Subtest Select </h3>
then you can update only your needed bit with whole response
success: function(data) {
$('.subtest-updateable').html(data);
}
b) better (in systematic approach means) would be use json response, where you can return more isolated variables as well:
Set dataType to json.
Success function would use $('.subtest-updateable').html(data.label)
In PHP print json_encode(array('label' => $_SESSION['label'], 'someelse' => $someother_variable ))
You still should put span (or some other html element) around updateable bits of your page (to avoid writing constants into your javascript)
In your success function you need to update the part of the DOM that you want to change. On the PHP side just return your blade partial or whatever HTML you want to display.
$(document).on('submit', 'form#form-grad', function (e) {
e.preventDefault();
var context = $(this);
var thisForm = context.closest('form');
$.ajax({
url: thisForm.attr('action'),
method: 'PUT',
data: thisForm.serialize(),
success: function (response) {
$('#updatearea').html(response.pt_html);
// Close grading form
}
});
return false;
});
I have a button and user's name on the template and if a user clicks on button, Ajax should replace user's name and button with some messages using new CSS styling.
This is my Ajax :
$('#fulfillButton').bind('click',function() {
$.ajax({
type : "GET",
contentType : "application/json; charset=utf-8",
url : "order/${orderID}",
dateType : "json",
cache: false,
success: function (data) {
if(data.statusCode=="OK")
{
$('#replace').replaceWith("<div class ="error_message">"+ data.body +"</div>");
}
},
error: function (data) {
alert("Something went wrong, please retry again");
},
});
});
This is my html:
<div id="replace">
<div class="full_name">
${name}
</div>
<button id="fulfillButton" type="button" class="action-button shadow animate green">
FulFill
</button>
</div>
<button id="goBackButton" type="button" class="go_back_button">
Go Back
</button>
However, when I clicked on the button, nothing happened. I am missing something here? I am using Jquery 1.6.
You code is fine in general, and working. The only thing went wrong, is the html escaping of the replace element:
// before
$('#replace').replaceWith("<div class ="error_message">"+ data.body +"</div>");
// after
$('#replace').replaceWith('<div class="error_message">' + data.body + '</div>');
And you should really update your jQuery version. 1.6 is a hundred years old! :)
Working example.
Yesterday I coded a Commentbox in PHP, HTML and ajax. The ajax part gives me the opportunity to delete a comment without refreshing the page. The way I do this, is that I give each and every comment (div) a unique id via the database. So let us for example say that in my mysql database this is how a comment looks like:
Username: blabla<br>
Comment: haha this is so funny<br>
id: 52
This will be printed out in the html page likes this for example:
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment">Delete the comment here!</div>
</div>
AND THEN!
Comes the ajax part which is coded something like this:
$(document).ready(function(){
$(".deleteComment").click(function(){
//Getting the id of comment
id = $(".deleteComment").attr("id");
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
});
This works fine when deleting the first comment. But it WONT LET ME DELETE OTHER COMMENTS UNLESS I REFRESH THE PAGE >.<. The first comment can be perfectly deleted without refreshing the page, but when I want to delete other comments I have to refresh the page multiple times.
How do I solve this?
The code in your document ready event would work properly only for the first click. In order to get this work, you must have an on click event registered within the tag.
Example :
<div class="deleteComment" onclick="DeleteMe(id)">Delete the comment here!</div>
</div>
function DeleteMe(id)
{
$.ajax{
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
$("#" + id).hide();
}
}
});
}
If the on click on a div does not work, you can use an anchor tag (Delete here) instead.
.deleteComment is child of <div class="commentStyle".., so you can select it with parent() selector:
var id = $(this).parent().attr("id");
Or more specifically:
var id = $(this).parent('.commentStyle').attr("id");
Looks like you need to get the id from the parent element first and then target the child, the element you clicked, to hide the comment from it after the ajax request returns success:
$(".deleteComment").click(function(){
var id = $(this).parent().attr("id");
var child = $(this);
$.ajax({
type: 'GET',
url: 'deletecomment.php',
data: "id=" + id,
success: function(){
child.hide();
// or if you want to delete the entire element with the id of X
// child.parent().hide();
}
});
});
There are few changes which need to be done in your code.
First of all add ID tag to the inner div.
<div class="commentStyle" id="<?php echo $commentid; ?>">
This comment will now have the id of 52
<div class="deleteComment" id="<?php echo $commentid; ?>">Delete the comment here! </div>
</div>
Secondly use this
id = $(this).attr("id");
instead of...
id = $(".deleteComment").attr("id");
Thirdly change the ajax call like this:
$.ajax({
Type: 'GET',
url: 'deletecomment.php',
data: "id=" + id
}).done(function(){
$("#" + id).hide();
});
Hope this works for you, if not just reply me.
I've read through a number of similar questions and tried my hand at putting it to work on my website, but it is not working (when you click the link there is no response on the console and the database is not updated).
Here's what I want to do: I want users to rate a comment +1 by clicking an icon next to the comment. I want that to update my mysql comment_table column called rating with rating+1. When I do it without AJAX (ie, just set the form action to a php page?id=10) it works fine. I can't get the AJAX to update the database though.
My main page with the comment:
<span class="glyphicon glyphicon-chevron-up"></span>
The javascript below that link:
<script type="text/javascript">
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
rating: rating,
id: <?php echo $thisperspective_row['id']; ?>,
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
</script>
and my rating.php file is
<?php
require_once('connectiontodatabase.php');
/* simple comment up and down voting script */
$mode = $_GET['mode'];
$rating = $_GET['rating'];
$id = $_GET['id'];
if ($mode=="vote")
{
// The name of the
$cookie = "nameofmycookie".$id;
if(isset($_COOKIE[$cookie]))
{
echo '<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Sorry You have already rated this comment within the last 14 days.</div>';
}
else
{
$expiry = 1209600 + time(); // 14 day expiry
setcookie ($cookie, "voted", $expiry);
mysql_query ("UPDATE comment_table SET rating = rating+$rating WHERE id=$id", $connection);
}
}
?>
The php runs fine and all the variables are listed properly when I view the source. However, when I click the link, there is no response at all and the console does not output the response. What am I doing wrong? Thanks in advance!
Firstly you should change the way you are detecting the click event. Check out this fiddle. Then secondly you need to pass all the variables through in one JSON string using the data option. Your code should look something like this:
<span class="glyphicon glyphicon-chevron-up clickable"
data-rating="1"
data-id="<?php echo $thisperspective_row['id']; ?>"></span>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "vote",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'rating.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
First off all, check that you are loading jQuery, then use this code
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
data: { rating: rating, id: id },
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
is working for me.
note that I removed ` inside Ajax, since you are already sending the params in the function, also to send params you have to use data:, you can see more examples here Ajax jQuery
I'm a bit lost and getting real short in time.
I need to create something like this script
$(function () {
var i = 0;
$('#addButton').click(function () {
$('#form1').append
('<div class="clearfix">Ingredient Item <div id="editor2"><input style="float:left;" type="text" name="Ingredient[' + i + '].IngredientItem"/></div><div id="editor3"> Item Amount<input style="float:left;" type="text" name="Ingredient[' + i + '].ItemAmount"/></div>');
//Dif table..
('<div class="clearfix1">Instructions <div id="editor3"><input style="float:left;" type="text" name="Instructions[' + i + '].IntrusionStep"/></div><div id="editor4"> Cooking Time<input style="float:left;" type="text" name="Instructions[' + i + '].CookingTime"/></div>');
//& one more diff table here
i++;
});
});
I know this is not a good approach and far from best practice I didn’t find any example of using any better way to do it ( I'm complete novice as far as JavaScript or any scripting for this matter).
What i have understood is that you need to post your form from java-script code. You can make use of a jQuery post or an ajax post method here.
$.ajax({
url: '<%=Url.Action("Create","YourController") %>',
type: 'post',
data: $(form).serialize(),
datatype: 'json',
success: function (result) {
// Handle code for success post
},
error : function (result) {
// Error condition
}
});
Now make your controller action accordingly to return json value back to your java-script code in the view