Jquery/Php post without redirect - php

I am making a website that displays a list of hotels. I want to add a "favorite" button so that it stores that hotel with the user. From my understanding I need to use php/jquery based on some answers I saw on stackoverflow.
I have no experience with php/jquery. Absolutely none writing it or even adding some to my web page (this is the first website/web application I am trying to build.
After looking at a couple of stackoverflow answers on this topic I have checked out this website: http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
and attempted to click on the recommended link for newbies: 15 Resources to get you Started with jQuery From Scratch.
but to no avail as the page is not found.
This is the html where I want to add the favorite button stored in "Bookmark for later". However, I know hypothetically even if my click worked I am not capturing the data of the specific hotel for which they clicked bookmark for later.
{% for hotel in close_hotels %}
<div id = "display_hotel">
<p><font color="blue" size="2"><b> {{ hotel.name }} </font></b></p>
<div id = "hotel_format">
<div id = "favorite_form">
<input id="bookmark" type="button" value="Bookmark for later!"
onclick= "function()"/>
</div>
This is my .js file. I tried following http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59 as best as I could, but recognized some differences. For example I am trying to capture information from a button(should I change this) instead of a form.
I didn't bother with the form validation since it is just a button.
$(function() }
//using a button to add hotel to favorites
$(".button").click(function() {
var hotel = $("input#bookmark").val();
//skipping form validation since no need -- using a button
});
});
//next part of the tutorial
$.ajax({
type: "POST",
url: "bin/process.php",
data: hotel,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Hotel Favorited!</h2>")
.hide()
});
}
});
return false;
Ultimately there are two things I am wondering. Is a button most appropriate for what I am seeking? If not, what else should I use, but if so how can I capture the hotel information with the PHP. Second of all as I am not familiar with php/jquery will the code work?
From my understanding this line should be able to capture the hotel name I want, but again I don't even think my button would even send the information.
var hotel = $("input#bookmark").val();
Thanks for the help!

There are two main ways to submit information to the server (your PHP code):
Using an HTML <form>
AJAX
I'm guessing you want to do it via AJAX since you're not sending typical form data. For that you would do something like this in jQuery:
var req = $.ajax({
type: "POST",
url: "http://whatever.com/stuff",
data: { "some_key": "some_value" }
});
req.done(function (response) {
// code to run after the server handles your data and responds
});
req.fail(function(jq_xhr, text_status, error_thrown) {
// if you want to handle errors ...
});

Related

Second AJAX call returning whole page instead of intended target

So I have a simple web-app interface that is relying on AJAX to build and control which settings a user can see at any one point in time. Think of them as acting like sub-menus.
<script type="text/javascript">
$(document).ready(function(e) {
$(".option").click(function() {
var method = $(this).attr("id");
var target = "";
switch(method){
case "optManPpl":
target = "/controls/location/manage_people.php";
break;
case "optManLoc":
target = "/controls/location/manage_locations.php"
break;
}
$.ajax({
type: "POST",
data: "user=0",
url: target,
success: function(msg){
$("#controls").html(msg);
}
});
});
});
</script>
<div id="options">
<div id="optManPpl" class="option"> Manage People </div>
<div id="optManLoc" class="option"> Manage Locations </div>
</div>
<div id="controls">
</div>
This page is obviously called and displayed from another ajax call and loaded to the screen. When I click on "optManPpl" or "optManLoc" for the first time, the call goes through great and returns the expected result. However, the second time I click on either of them (2 calls in any combination), the entire page is returned instead of the [target] url.
EDIT: I am "chaining" AJAX calls throughout the application. I am relatively new to working with AJAX in a web-app situation, so I'm not sure if this is the best way, but it is the way I came up with for getting user input from the forms into PHP without having to resubmit the page.
EDIT: the attached image is what the page looks like after the second call. After the FIRST call, the "controls" div tag is instead populated with 4 other div tags.
please put exit after last line in manage_locations.php file.
also you can check out put by following.
$.ajax({
type: "POST",
data: "user=0",
url: target,
success: function(msg){
alert(msg); return false;
$("#controls").html(msg);
}
});
Here you ll see the particular output only. so that you can find the results in an alert.

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"

how to deal with delete buttons in php?

I want to know what is the best way to handle delete or edit buttons?
So let's say from a comment box, should I use post or get method for this and then make some validations in the page that is suppose to delete the comment?
As a specific example, I'm gonna point out facebook's comment box, it has a little button for deleting comments, but it doesn't display the url in the bottom of the browser, so I guess this uses post method with some jQuery in it. I'm I right? if not what should I use for this type of buttons?
I don't know what Facebook uses, but yes, you should use POST. You might want to use something like this:
<div class="comment">
<p><code>POST</code> should be used for actions which change data.</p>
<form action="comments/1/delete" method="post" class="delete-form">
<input type="submit" value="Delete" />
</form>
</div>
$(".delete-form").submit(function() {
var me=$(this);
$.ajax({
type: 'POST',
url: me.attr('action'),
success: function() {
me.parent().remove();
},
error: function() {
alert("Oops! An error occurred while deleting your comment.");
}
});
return false;
});
If you don't like that the delete button is on a separate line, just style it a bit with CSS:
.comment > p,
.comment > .delete-form {
display: inline;
}
You are right.
To solve that kind of issues you can either do a classical form which will reload a page after the click or rely on AJAX.
AJAX is an asynchronous way to communicate with a server. In your case, when someone clicks on the button you want it to transmit a request to the server to perform the deletion or edition without reloading the page.
Check out the JQuery get and post functions for a quick start on the topic:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
In the very case of a delete button, you will do a post since it is going to change something on the server side.

Looking for syntax guidance on implementing AJAX project

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'.

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