Looking for syntax guidance on implementing AJAX project - php

I am taking on my first AJAX project and conceptually have everything mapped out for the most part but am being held back due to my lack of knowledge syntactically. I think I also might be off the mark slightly with my structure/function logic.
I am looking for some guidance, albeit reference to tutorials or any corrections of what I am missing or overlooking.
profile.php: this is the page that has the actual thumb icon to click and the $.post function:
Here is the thumb structure.
When thumb is clicked, I need to send the id of the comment? I know I need to calculate the fact that it was clicked somehow and send it to the $. Post area at the bottom of this page, I also need to put some sort of php variable in thumb counter div to increment numbers when the $. Post confirms it was clicked.
<div id="thumb_holder">
<div id="thumb_report">
<a href="mailto:info#cysticlife.org">
report
</a>
</div>
<div id="thumb_counter">
+1
</div>
<div id="thumb_thumb">
<?php $comment_id = $result['id'];?>
<a class="myButtonLink" href="<?php echo $comment_id; ?>"></a>
</div>
</div>
Here is the $.post function
This should be sent the id of the comment? But most certainly should be sent a record of the thumb link being clicked and somehow send it to my php page that talks to the db.
<script>
$.ajax({
type: 'POST',
url:" http://www.cysticlife.org/thumbs.php,"
data: <?php echo $comment_id; ?>,
success: success
dataType: dataType
});
</script>
thumbs.php: is the page that the request to increment is sent when the thumb is clicked and then in turn tells the db to store a clikc, I don't really have anything on this page yet. But I assume that its going to be passed a record of the click from via $.post function from the other page which syntactically I have no clue on how that would work and then via insert query will shoot that record to the db.
Here is what the table in the db has
I have three rows: a id that auto incrments. a comment_id so it knows which comment is being "liked" and finally a likes to keep track on the number of thumbs up.

At least you've made a good start, there are still some mistakes. First of all there are some basic principles you might want to get used to:
1) How to create a click event
First of all the button, I inserted '2' as the href.
<a class="myButtonLink" href="2">Vote Up!</a>
EDIT: Just in case JS in disabled, this would be a better option:
<a class="myButtonLink" href="voteup.php?id=2" id="2">Vote Up!</a>
Then the JS:
$('.myButtonLink').click(function(e) {
e.preventDefault();
alert('the button has been clicked!');
});
The e represents the event, so the first thing we do after the submit is to cancel the default action (redirecting to '2'). Then we're alerting that the button was clicked. If this works, we can go to the next step.
2) Getting the ID value from the clicked link.
Inside the click function, we can use $(this), it's a representation of the element clicked. jQuery provides us with a set of functions to get attributes from a given element, this is exactly what we need.
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
alert('We are upvoting comment with ID ' + comment_id);
});
When everything goes well, this should alert 'We are upvoting comment with ID 2'. So, on to the next step!
3) Sending the Request
This might be the harders step if you're just getting started with ajax/jquery. What you must know is that the data you send along can be a url string (param=foo&bar=test) or a javascript array. In most cases you'll be working with an url string because you are requesting a file. Also be sure that you use relative links ('ajax/upVote.php' and not 'http://www.mysite.com/ajax/upVote.php'). So here's a little test code:
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'thumbs.php',
data: 'comment_id=' + comment_id,
success: function(msg) { alert(msg); }
});
the dataType is detected automatically, you can for instance choose between a JSON response (which can be an array with a status and message response) or just plain text. Let's keep it simple and take plain text to start of with.
What this script does is calling thumbs.php and sending a $_POST value ($_POST['comment_id'] = 2) along with this request. On thumbs.php you can now do the PHP part which is:
1) checking if the comment_id is valid
2) upvoting the comment
3) print the current amount of votes back to the screen (in thumbs.php)
If you print the number of votes back to the screen, the last script I gave you will alert a messagebox containing the number of votes.
4) Returning an array of data with JSON
In order to get a proper response on your screen you might consider sending back an array like:
$arr = array(
'result' => 'success', // or 'error'
'msg' => 'Error messag' // or: the amount of votes
)
Then you can encode this using the php function json_encode($arr). Then you would be able to get a more decent response with your script by using this:
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'thumbs.php',
data: 'comment_id=' + comment_id,
success: function(data) {
if(data.result == "error") {
alert(data.msg);
} else {
alert('Your vote has been counted');
$('#numvotes').html(data.msg);
}
}
});
As you can see we're using (data) instead of (msg) since we're sending back a dataset. The array in PHP ($arr['result']) can be read as data.result. At first we're checking to see what the result is (error or success), if it's an error we alert the message sent along (wrong DB connection, wrong comment ID, unable to count vote, etc. etc.) of the result is success we alert that the vote has been counted and put the (updated) number of votes inside a div/span/other element with the ID 'numvotes'.
Hopefully this was helpfull ;-)
//edit: I noticed some mistakes with the code tags. Fixed the first part of the 'manual'.

Related

Cross checking with database before rendering page

I am trying to cross check some values with what I have in the database before letting those data go any further.
I have a form and in this form I am post
pid, Name, size, category and qty.
I have a validation already for the qty.
In those data I am posting I am using those to find the price in the database. I AM NOT POSTING THE PRICE.
Because I am using those post data to find the price someone might want to mess about with them for an example change the category or size value to whatever. If they do this, it will still get posted and the page will render and it will look like
Name: qty: unit price: total item price:
size:
Although those table name shows NOTHING is getting shown which means the page is just rendering for nothing.
I know some of you might think "if the person whats to mess about with the values, that is their fault" and I totally agree but I still want to stop the page from rendering
if everything posted doesn't relate to any of the item with that product ID (Pid).
How can I use ajax to validate them before rendering it in the other page?
I already Have an ajax which looks like
$(document).ready(function(){
$('#selected').hide();
$('#button').click(function(){
var pid = $('#pid').val();
var size = $('#size').val();
var qty = $('#Qty').val();
var price = '\u00A3' + parseInt($('#pricetag').text().replace(/^\D/, ''), 10) * qty;
if (!/^[1-9]\d?$/.test(Qty)){
alert('Quantity should not be below 1 or null');
return false; // don't continue
}
else {
$('#sprice').text(price);
$('#ssize').text(size);
$('#selected').slideDown();
}
$.ajax({
url: 'cart.php',
type: 'POST',
data: { pid:pid,
size:size,
Qty:Qty,
Category:Category },
success: function(data)
{
}
});
});
});
in cart.php
is where I am posting those values to.
How can I do this please?
You want to ask the server to see if the data is valid. Aside from the form data, I would also post a flag telling PHP that this is the AJAX validation so it can tell the AJAX post from normal form submission.
In PHP, after the data validity is determined, it can just return true or false. Then your Javascript can determine what to do from that point on.
However, I think there are other ways to go about this. Maybe you shouldn't let the user modify these fields, or maybe you can post the form, and render the form again if the user has submitted invalid data. Another alternative is to limit the choices that the user can do, so their input is always valid.

How do I post to a new php page with jquery

I am trying to post the element information that jQuery pulls, when a user clicks on table cell, to a new page that will use that information (an id in this case) in a sql query. i.e., the user clicks a cell and the job he/she clicks has an id of 25, that is to be passed to my php page that queries the database for the job with that id and then populates the page with said information. The user can then alter the information from the query and submit it to update the database table. I have the id from the click function and a success alert tells me that the info was posted. The problem is that when the page is opened it states that the posted name index is undefined.
Here is my script to get the information:
<script>
$(document).ready(function()
{
$("table.jobs tbody td#job").click(function()
{
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
if (col == '')
alert("Please pick another column");
else
$.ajax(
{
type:"POST",
url:"../php/jobUpdate.php",
data:"name=" + LeftCellText,
success: function()
{
window.location = "../php/jobUpdate.php";
}
});
});
});
</script>
and here is the simple php page it is sending to:
$name = $_POST['name'];
echo $name;
I am new to jQuery, and I cannot figure out why this is not working?
When you use ajax, the second page ../php/jobUpdate.php processes the data sent by the first page, and returns a value (or even a huge string of html, if you want).
The first page receives the new data in the ajax routine's success function and can then update the current page. The updating part happens in the success: function, so you're on the right track.
But in your success function, you are redirecting the user to the 2nd page -- after already being there and processing the data. Redirecting them is probably not what you want to do.
Try replacing this:
success: function()
{
window.location = "../php/jobUpdate.php";
}
with this:
success: function(data)
{
alert(data);
}
If you want to see how to update the first page with the data received via ajax, try adding an empty DIV to your html, like this:
<div id="somestuff"></div>
Then, in the success: function of the ajax routine, do this:
$('#somestuff').html(data);
(Note that the term "data" can be any name at all, it only needs to match the name used in the function param. For example:
success: function(whatzup) {
alert(whatzup);
}
From your comment to my previous post, it seems that you don't need ajax at all. You just need a form in your HTML:
<form id="MyForm" action="../php/jobUpdate.php" method="POST">
<input type="hidden" id="jobID" name="yourJobID">
</form>
Note that forms are invisible until you put something visible inside them.
You can have select controls (dropdowns) in there, or all form elements can be invisible by using hidden input fields (like the HTML just above), which you can populate using jQuery. Code to do that would look something like this:
<script>
$(document).ready(function() {
$("table.jobs tbody td#job").click(function() {
var $this = $(this);
var col = $this.text();
var LeftCellText = $this.prev().text();
//Set value of hidden field in form. This is how
//data will be passed to jobUpdate.php, via its `name` param
$('#jobID').val(LeftCellText);
if (col == '')
alert("Please pick another column");
else
$('#myForm').submit();
});
});
</script>
If you add more values to your form to send over to jobUpdate.php, just ensure that each element has a name, such as <input type="text" name="selectedJobType"> (this element, type="text", would be visible on screen).
In the jobUpdate.php file, you would get these values thus:
$SJT = $_POST['selectedJobType'];
$id = $_POST["yourJobID"];
//Use these vars in MySQL search, then display some HTML based on results
Note that the key referenced in the $_POST[] array (selectedJobType / yourJobID) is always identical to the name specified in the HTML tag. These names are case sensitive (and spelling counts, too).
Hope this isn't TMI, just wish to cover all the bases.
On your success function causing the window to reload will delete any of the variables passed in via .ajax.
What you can try is returning the data and use it in the existing page.
success: function(msg) {
$('#someDiv').append(msg);
}
The reason the index is not defined is because you are using a string in the data-argument, however, that is actually an array-like object. :)
data: { name: col }
that should be the line you need to change. Otherwise I have not seen any problems. Also if I can give you a little idea, I wouldn't use POST actually. In fact, I'd use GET. I can not confirm if that is saver or not, but using $_SERVER["HTTP_REFFERER"] you can check from where that request is coming to determine if you want to let it pass or not.
The way I would suggest is, that you sent the ID in a GET-request and have the PHP code return the data using json_decode(). Now in jQuery, you can use $.getJSON(url, function(data){}) - which is, for one, shorter and a bit faster.
Since you probably will crop the URL yourself here, make sure that you use a function like intVal() in JS to make sure you are sending an intenger instead of a malicious string :)

Can't send array to php via ajax and back

i am trying to get a button on my page which will eventually be a delete button to work. However because it is a <li> element and not your average submit button with a form etc... i have to use ajax to send all the variables to be processed, at the moment i just want them to be in a state where they can be processed, but at the moment my script doesn't seem to return any value like i want it to and output them.
Hopefully from the code below you will see what i mean, all i need it to do at the moment is just select all the values from the checkboxes which are cehcked and send it to the mail_trash.php, and then just send it back and output the array, just so i can see it is selecting the proper values etc... The actual delete php code is already written and working, this is just to check the Ajax.
Here is the javascript and ajax
<script>
$("document").ready(function (){
$("li.trash").click(function(e){
var db = $(':checkbox:checked').map(function(i,n) {
return $(n).val();
}).get(); //get converts it to an array
if(db.length == 0) {
db = "none";
}
$.ajax({
type: "GET",
url: "mail_trash.php",
data: {'db[]':db },
dataType: "json",
statusCode: {
200: function (response) {
$("#mail_header_name").html(response.mess_id);
}
}
});
});
});
</script>
And here is the script for the mail_trash.php
<?php
include 'connect_to_mysql.php';
$mess_id = $_GET["db"];
echo json_encode($mess_id);
?>
And just to check things the button
<li><a class="trash" href=""> </a></li>
Thank you so much for your help, this has been bugging me for the last couple of hours.
It's not li.trash. It's a.trash because trash is a class of the a element. As such the first three lines of the js should be:
<script>
$("document").ready(function (){
$("a.trash").click(function(e){
and then so on with the rest of you code. I haven't checked the rest of your code necessarily, although I am pretty iffy about $(':checkbox:checked') as I don't think that's correct jquery.... To start off, I'd suggest fixing the first selector I mentioned, checking the second with jquery docs and then jshinting/jslinting your code. (Javascript only)
I don't know if its a typo in the question itself or the issue with your script but name of th e parameter while passing is "db" but on the server side you are expecting "mess_id"

Can a variable go to a hidden PHP page using jQuery?

My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>​
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});​
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>​
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,

Return results from a MySQL database using jQuery/AJAX and insert into a DIV

I am working on a project for reserving classrooms. One way of reserving a room is to select a room, see if the things it has (# of seats, # of computers, etc.) is ample for whatever the person needs it for, and then make a reservation.
I have a page that displays all of the available rooms as links in an HTML table, created dynamically in PHP/MySQL. My goal is when a user clicks on a room name, the AJAX request executes a query and returns the necessary data, and then displays it in a DIV on that same page.
Right now, I'm calling an external PHP file that gets the ID of the room that's clicked and executes the query. I'm still very much a novice at jQuery, and I'm pretty sure the problem is in my jQuery script:
<script type="text/javascript">
$(document).ready(function()
{
$('table.roomNums td a.rm-details').click(function()
{
var id = $(this).attr('id');
$.ajax(
{
type: 'POST',
url: 'roomInfo.php',
data: {
roomID: id
},
dataType: 'json',
cache: false,
success: function(result)
{
$('#room-details').empty();
$('#room-details').append("<ul>\n\t<li>Seats: " + result.numOfSeats + "</li>\n</ul>");
}
});
});
});
</script>
As of now, when I click on one of the room number links, nothing happens. I'm assuming that my problem resides in this script, but I'm not sure where or what. I've been reading into the ajax function in jQuery and I'm pretty sure I understand what's going on, but I'm having no luck at the moment.
You want to troubleshoot the following four things:
The HTTP Request Does the browser even issue an ajax request? If so, does it contain the form parameter you are trying to make it contain?
The HTTP Response Does your php script return the data you are expecting in JSON format so JQuery can automatically parse it for you? Copy and paste the response from the server into a test javascript file and see if it compiles as a valid JSON object in a javascript debugger.
AJAX success function Does your javascript error out? Can you step through each line of execution in a javascript debugger like firebug?
Click Event Handler Does your click handler properly return false so the page does not reload? Does your click event handler function fire at all upon click?
Somewhere in the above four things lies your issue. It looks to me like you just need to return false in your click handler so the page does not reload.

Categories