Im using Ajax to send values to a PHP script which writes some value to a database:
$.ajax({
type: "POST",
data: "action=vote_down&id="+$(this).attr("id"),
url: "vote.php",
success: function(msg) {
$("span#votes_count"+the_id).fadeOut();
$("span#votes_count"+the_id).html(msg);
$("span#votes_count"+the_id).fadeIn();
}
});
As you can probably tell from the action=vote_down the script is for a voting script.
Im already preventing the user from voting more than once by logging there vote against there username and ID in vote.php and if there username and ID is already in the DB against the same post then I dont add the vote to the DB.
I personally think that querying the database on each page load to check if the user has already voted could be quite intensive, there are many places to vote on a single page.
So instead i'll show the user the voting option, but when they vote I want to some how return a value from vote.php to say they have already voted.
Any ideas for the best approach to this?
Use JSON
If this is your file to show the voting form:
<div id='voteform-div'>
<form id='voteform'>
Your form elements and a submit button here.
</form>
</div>
Your JS code look like this:
jQuery('#voteform').live('submit',function(event) {
$.ajax({
url: 'vote.php',
type: 'POST',
data: "action=vote_down&id="+$(this).attr("id"),
dataType: 'json',
success: function( messages) {
for(var id in messages) {
jQuery('#' + id).html(messages[id]);
}
}
});
return false;
});
your vote.php should be something like this:
// Get data from $_POST array.
if( Already voted ) {
// It will replace the id='voteform-div' DIV with error message
$arr = array ( "voteform-div" => "you have already voted." );
} else {
// Store vote in database
// It will replace the id='voteform-div' DIV with confirmation message
$arr = array ( "voteform-div" => "Yor vote is submitted. Thanks" );
}
echo json_encode( $arr ); // encode array to json format
For more detail on this look at this question.
This should put you in the right direction...
http://forum.jquery.com/topic/jquery-ajax-and-php-variables
I would parse back a boolean false if they have posted already, or the id of the vote if they were successful (for styling / adding the html message).
Related
I'm sure there is a simple answer to this stupid problem but I have searched high and low and can not figure out why this wont work.
$tutorid = $_GET['userid'];
var_dump($tutorid);
//populate user tutoring subjects
if( isset($_POST['a'])) {
$currentsubjects = get_current_user_subjects( $tutorid );
unset($_POST['a']);
echo json_encode($currentsubjects); return;
}
I have a simple AJAX function that sets $_POST['a'] equal to something. The var_dump($tutorid) properly displays the id from the url. However the $tutorid in the get_current_user_subjects is sending NULL.
If I try a var_dump like this to check $tutorid
$tutorid = $_GET['userid'];
//populate user tutoring subjects
if( isset($_POST['a'])) {
echo json_encode($tutorid); return;
// $currentsubjects = get_current_user_subjects( $tutorid );
// unset($_POST['a']);
// echo json_encode($currentsubjects); return;
}
Then I get NULL. If I hard code in a tutorid in the get_current_user_subjects( $tutorid ) (like add in 15 or something) the function returns data to console.log like expected but using the variable $tutorid stops it completely. I can't figure out why this is happening! Someone please enlighten me.
Here is the AJAX just incase. It works find on other pages so I am assuming the issue is with $_GET
$.ajax({
url: 'profile.php',
method: 'post',
data: "a=true",
dataType: 'json',
success: function (x) {
console.log(x);
},
error: function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
Maybe you can use this method. So you can POST the userid
$.ajax({
url: 'profile.php',
method: 'post',
data: {a: a, userid:userid},
dataType: 'json',
success: function (x) {
console.log(x);
},
error: function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
So in your form before the action. you can set userid in hidden form
<input type="hidden" name="userid" value="<?php echo $userid;?>" />
Save the userId to the session and take it from there. Or pass the userId with the ajax request. I dont think the logic is right in your code, as bsed on the info you have provided. Trying to take the id from $_GET in the requested page while your ajax method is post and no userId is passed with the request, is not right. From my knowledge, you wont have data in the $_GET array if the request to that page is not 'get'. Session provides InterPageCommunication. use session.
So I got this form which lets the user enter up to 10 item IDs and then check for the status or apply changes right away. If the user clicks check status the item IDs will be sent to another PHP.
What is the easiest way to send the result back to the form and display it in the red area?
if ($_POST['action'] == 'Check Status/Shelf') {
$itemids = "$itemID1, $itemID2, $itemID3, $itemID4, $itemID5, $itemID6, $itemID7, $itemID8, $itemID9, $itemID10";
while ($row = mysql_fetch_array($all)) {
$hyllplacering = $row['Hyllplacering'] . "";
$all = mysql_query("SELECT Hyllplacering, itemID FROM booking WHERE itemID IN ('$itemids')");
}
}
If you don't want to use Ajax, then save the details into a $_SESSION[] and upon submission the form is posted and then the details can be populated into SESSION and displayed back out to the form upon reloading, but it's a bit of a fiddle for not much return.
And use MySqli or PDO.
For that you have to use ajax
Give id to Apply Changes & Check Status/Self button
<script type="text/javascript">
$(document).ready(function(){
$('#apply').click(function() {
var id1 = $('#id1').val();
var id2 = $('#id2').val();
//same for all your 10 field
var cstring = "id1="+id1+"&id2="+id2 // etc;
$.ajax({
type: "POST",
url: "your file url to do database opration & fetch detail back to here",
data: cstring,
cache: false,
success: function(result) {
$('.resultdata').html(result)
}
});
});
});
</script>
<div class="resultdata"></div>
Basically what I'm trying to do is post comments to a page without having to refresh the entire page. Just the Comments DIV so it looks like it posted and refreshed smoothly.
The form submits to the same page it's on. Everything I've found shows me how to refresh content constantly using intervals. I just want the comments DIV to refresh when someone posts a comment.
I can't find the correct ajax code to do this the way I want.
Here is my code:
var submit_button = $('#submit_button');
submit_button.click(function() {
var commentSubmitted= $('commentSubmitted').val();
var update_div = $('#update_div');
$.ajax({
type: 'POST',
url: '/blog/',
data: data,
success:function(html){
update_div.html(html);
}
});
});
in the same PHP file, I have the post to DB:
if($_POST[commentSubmitted])
{
$query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
mysql_query($query);
}
The HTML is for the form:
<form id="flow" method='post' action='/blog/'>
<textarea name='commentSubmitted' ></textarea>
<input type='submit' value='Post'/>
The DIV containing all comments looks like so:
<DIV id='AllComments'>
// comments displayed here
</DIV>
So after submitting the form, I would like the 'AllComments' DIV to reload.
The best would be to use jQuery to make the ajax call to the server and retrieve the data you want.
You have two ways of retrieving the data. Either retrieve the additional comments to show in a json array and handle it with javascript, or create the html on the server side and append/replace the html in the comments section.
Using Json
$.ajax({
url: "the_ajax_url_here",
type: "post",
data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
dataType: "json"
success: function(response) {
// handle the response
}
});
Retrieving Html
$.ajax({
url: "the_ajax_url_here",
type: "post",
data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
dataType: "html"
success: function(response) {
// set the html of comments section to the newly retrieved html
$("comments_section_selector").html(response);
}
});
What I would do is retrieve the newly added comment in a json array and then using javascript append it to the comments section.
edit:
After seeing your code I have some comments that might help you.
I would personally prefer the code that handles the ajax request in a separate file.
In that file you can store the new comment and create the html to display that comment.
Then in the success function just append the new html to the comment section like so:
success: function(response) {
$('#AllComments').append(response);
}
You can also make new comment appear on top using prepend
$('#AllComments').prepend(response);
Simple as that hope you are upto it
submit_button.click(function() {
var commentSubmitted= $('commentSubmitted').val();
var update_div = $('#update_div');
$.ajax({
type: 'POST',
url: '/blog/',
data: data,
success:function(html){
update_div.html(html);
}
});
});
Then you go to insert data
if($_POST[commentSubmitted])
{
$query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
mysql_query($query);
//After Inserting data retrieve back all the comments from db
$sql = "select * from comments";//any query and execute it
$query = mysql_query($sql);
while($data = mysql_fetch_array($query)){
echo $data["comments"];//Echo your commenets here
}
exit;
}
Thats it
So I am submitting data to the database. Each data sent contains an id that is auto incremented. With ajax or PHP (I am very much new to this, and trying to learn I'm sure it's ajax along with some php) I need to fetch the id of the data that was submitted.
The idea is, after the form is submitted, the user gets the link back to the submitted page. Example:
Quote was submitted! [link] Click to go to the link or go back.
The link will look like this: http://example.com/quote-192
I pretty much have everything else set, I just don't know how I'll get the id and add it to the link.
Here is the PHP that processes the form:
require('inc/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
//echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Oh, and the data is being sent with ajax:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
var like = $('.quote-wrap span iframe');
$('.inner').prepend('<div class="quote-wrap group">' + like + '<div class="quote"><p>' + quoteVal+ '</p></div></div>');
// console.log("success");
});
return false;
});
So how would I get the id for each quote and add it to the page after the form has been submitted?
In you php:
echo mysql_insert_id($result)
Then in your jquery ajax:
$.ajax({
type:'post',
url:'url.php',
data:querystring,
success:function(data){
var id = parseInt(data);
}
]);
this will return the inserted ID as an integer value that you can work with in javascript
Have the PHP print the ID as a response to the request:
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
// Print the id of last insert as a response
echo mysql_insert_id();
jQuery, test code to alert what was echoed by the PHP as a test
// add data as a param to the function to have access to the PHP response
$.post("add.php", $(this).serialize(), function(data) {
alert(data);
});
With this php-function. You can call after inserting.
int mysql_insert_id ([ resource $Verbindungs-Kennung ] )
mysql_insert_id
I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.