I have a similar to SO clone i am working on for practice. I am in the middle of coding the vote system. I would like that when the upvote/downvote button is clicked, an Ajax call gets sent with the parameters for the processing page holding the post id and the value.
The post is needed to be able to know which post to record on the processing page that the javascript calls
I have a table of posts each with a post id and a votes table with votes with a vote id, so in my votes mapping table I record the topic id along side the post id.
However I cannot work out how to dynamically give a different post id for the Ajax call to each different post? Should I create perhaps a hidden field?
How is this generally done? Thanks a lot!
Actually, you don't need to use hidden fields either. ) It may be more simple just to use the post's ID itself - or the rel attribute of upvote/downvote buttons. Like that:
HTML
<div id='post-XXX'>
<a href='#' class='upvote_post' rel='XXX'></a>
{ ... some immensely great post content goes here ... }
</div>
JS
$('.upvote_post').click(function() {
var post_id = this.getAttribute('rel');
// or var post_id = $(this).parents('div').getAttr('id').match(/\d+$/);
$.post(some_url, /* data including post_id */)
}
On Stack Overflow, every post contains <input type="hidden" value="POSTID">. When a vote button is clicked, the code seeks for this input element, and sends an AJAX request, together with this post ID.
You can have a look at the relevant code, here: http://userscripts.org/scripts/review/125051
This user script allows all (including non-registered) users to view vote counts on posts. To do so, the post ID and vote buttons have to be located.
Stripped down to the bare bones (excluding CSS), the code looks like:
<input type="hidden" value="--post id--">
<div class="vote upvote"></div>
<div class="vote downvote"></div>
// Example using jQuery:
$('.upvote').click(function() {
var $this = $(this);
$.get('/vote', {
postId: $this.siblings('input[type="hidden"]').val(),
type: $this.hasClass('upvote') ? '+1' : '-1'
}, function(data) {
// do something with server's response.
});
});
You can iterate over all buttons and raise the id of each post or they already have ids server side but then you have to tell your script these upon creation.
Related
Simply, I have an <a> tag having values(ID) which will be posted to the same page in clicking,
I wanted to load data into the table based on the ID provided by the post method. On the other hand I am having a clock which is rested again and again when fired a post method.
I simply wanted to do the same via jQuery.
In short I wanted to Implement ajax using jQuery
Also I am using database MySQL, with PHP scripting
Any sort help will be appreciated.
<a class="D" href="?ID=<?php echo $rows[0]; ?>" onclick="">Question<?php echo $QNo; ?></a>
I wanted the same above and get ID for searching relevant data against the ID.
I might be wrong here, but you basically want to query a PHP page based on an ID and display relevant content in a div?
To make an AJAX call, setup a PHP page that will query your database and in turn return HTML data which you can then display in a DOM element.
A very simple example of this would be:
HTML
Load table 1
Load table 2
<div id="contentToPopulate"></div>
jQuery:
$('a.linkToLoadTable').click(function(){
var pageId = $(this).data('tableId')
$.ajax({
url: 'loadTable.php?id='+pageId
}).done(function(data) {
$('#contentToPopulate').html(data)
});
})
I have a row of links like this:
Delete | Votes (2) | Comments (1)
They are each associated with user posts.
My question is on Delete:
All I want user to do is click it and then this needs to happen on php side:
<?php
$reviewId = $database -> escape_value(trim($_POST['reviewId']));
$user_id = $database -> escape_value(trim($_POST['user_id']));
// Delete Review Method
$result = Data::deleteMyReview($reviewId);
?>
My questions, what is the most efficient way of writing the code for Delete?
I don't really want an entire form for that one word. But then it also seems like a security issue to continue with the Delete approach. Then anyone can delete user comment by altering the url.
So should I use Post vs Get and Form vs <a>?
Using a form with the post method seems more appropriate for a delete action. I would have a separate form for each row, containing a hidden input with the ID and a submit button. A single form would work but you would have to have some Javascript to set the ID when each button is clicked.
A form is no more secure than a link. To make either way secure, you need to verify that the current user is authorized to delete the target review. For example, check that he owns the review. This should be done right before the delete code is executed.
It's fine to hide the delete button for reviews that don't belong to the user, but you should not rely on that for security because anyone can post a form and set the review ID to delete, regardless of what you were hiding and showing on the page.
You can use an <a> element and still POST the data. For example, using jQuery to perform an AJAX post:
HTML:
Delete
jQuery:
$(document).ready(function(){
$('.delete-review').click(function(){
$.ajax({
type: "POST",
url: "thispage.php",
data: { reviewId: $(this).data('review-id'), userId: $(this).data('user-id') },
success: function(data) {
//Do whatever you want to do when the delete succeeds such as redirect to another page
},
error: function(jqXHR,textStatus,errorThrown) {
//Handle your error here
}
});
return false;
});
});
As stated in my comments, for security concerns, you definitely need to validate the data before performing the delete. Don't trust it just because the delete option should only been seen by a valid user and you're using POST. Always validate.
Apologies for the ambiguous title, it just goes to show how confused I am with this one.
<a href"page.php?article_id=123&&img_id=img1">change image</a>
The link above is inside a form and is supposed to allow a user to change the image on an article. The functional php side of things is sorted - uploading the image, changing the image etc, but this will require the main form being submitted which is fine for the initial upload - not so much for the edit.
When the user clicks the "change image" link, I would ideally like to process that particular request alone in a different form, then update the parent page. I thought of doing it with a javascript new window popup which would have been ideal, except that I can't figure out how to pass the article_id as well as the img_id to the new popup page but above all... is this the most efficient way of doing this nowadays?
If not, How do I carry out this task? I have thought of ajax, jquery... but the same issue of passing the article_id and img_id still limits me.
I hope all of this makes sense and thanks in advance
ps: An article can have multiple images and article id is dynamic.
ajax sounds good to me.
may be you try something like this (jquery)?!
$.ajax({
type: "POST",
url: "page.php",
data: { article_id: 123, images: { i1: "img1", i2: "img2" } }
}).done(function( msg ) {
alert( "done: " + msg );
});
for further information and examples: http://api.jquery.com/jQuery.ajax/
why cant u receive article_id and img_id?
if you use:
<a href"#" onclick="window.open('page.php?article_id=123&&img_id=img1', 'window1');">edit</a>
u can get article_id and img_id in $_GET
however, this is a oldfashioned way getting this done.
Check this up: http://www.malsup.com/jquery/form/ - jQuery is a prerequisite but plugin allows you to send form elements via ajax, including file fields using simple API and does all heavy lifting for you.
Hey, I'm trying to make an Address book for my site and I was thinking of having two panes. The one on the left to have Contact names, and the one on the right to have the contact details.
I can get the Contact pane loaded up using a while loop to cycle through my query, but then I was thinking that I really had no Idea how to load the details of that contact when the user clicks on a specific contact name.
How would I be able to approach this problem?
If you have something like:
<div id="contactNamesPane">
<ul>
<li>Doe, John</li>
</ul>
</div>
<div id="contactDetailsPane">
</div>
$('contactNamesPane a.names').click(
var thisContactId = $(this).attr('id');
$('contactDetailsPane')
.load('http://path/to/script.php?contactId=' + thisContactId + ' #' + thisContactId);
);
This has the assumptions that you have a php script to generate the contact details (located at http://path/to/script.php and this script can take a GET variable in order to show the particular individual.
It also assumes that this data will be placed inside an element of an id equal to the contact's name.
A vaguely coherent demo's posted on my server at: http://davidrhysthomas.co.uk/so/loadDemo.html
When you create the list on the left add the id of the contact to the rel
<ul id="contacts">
<li>Name Here</li>
...
</ul>
Then with jquery you can use the rel attribute and peform a ajax request to a php page that returns the info of the contact with that id
$("#contact a").click(function() {
var id = $(this).attr("rel");
$.get("url_of_php_page", { id: id },
function(data){
// do something with the data
}
);
});
use jquery.data instead
i have a list of names with "delete" button, every row is a form and clicking on delete the list should be updated in real time but don't works because in this plugin i can set only one id (infact it runs when in the list there's only one name)
this is the javascript function:
$(document).ready(function() {
var options = {
target: '#risposta',
resetForm: true,
success: function(showResponse) {
$("#lista_categorie").load("categorie.php").show('fast');
$('#risposta').fadeIn(2000),setTimeout(function({$('#risposta').fadeOut(1000);},5000);}};
$('#elimina_categoria').ajaxForm(options);
});
the html form is build with php:
<form action="categorie_elimina.php?id=$row['id']" method="post" id="elimina_categoria">
<p>$row['nome']
<input type="submit" id="submit_pro" value="elimina" class="elimina"></p>
</form>
i should create a different id for every form (using the id of the row for example) but i should tell to js function that every form must follow that function in this line:
$('#elimina_categoria').ajaxForm(options);
i also used this code:
$('[id|=elimina_categoria]').ajaxForm(options);
but this only works at first click, clicking the second time it opens the php script..
hope you can help me, sorry for bad english
First of all:
Instead of creating several forms with the same id, you should create several forms with the same class. The same value for the ID-attribute should only be used once. Example
<form id="elimina_categoria_1" class="elimina_categoria"> ... </form>
<form id="elimina_categoria_2" class="elimina_categoria"> ... </form>
Please use a more descriptive naming than _1, _2 ... though, if possible.
When each form has the same class, you can call ajaxForm(options) using
$('form.elimina_categoria').ajaxForm(options)
Second:
The script you're probably looking for is something like this
function eliminaCategoria() {
var eliminaForm = $(this).parent().parent(); // Select the form of the button
$.post(eliminaForm.val('action')); // Call the action defined by the form
eliminaForm.remove(); // Remove the form-element from the page.
return false; // don't let the submit-button submit the form.
}
$(document).ready( function() {
$('.elimina').bind('click', eliminaCategoria);
});
The script might not work as-is in your current situation, but I hope this helps you forward. You probably want add the fadeIn, fadeOut effects you used and you might want to check the results of the HTTP POST request before deleting the form from the page.