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.
Related
This might look as the dumb question, but I hope it's not.
I have a PHP file delete.php that will delete selected users (it is not ready yet, but I will write it after I finish my HTML model).
So, on my HTML model I have the following:
<li><button class="sexybutton">
<span><span><span class="add">Add</span></span></span>
</button></li>
This sexybutton is the button styling I've downloaded. So, how to make it post the selected user list to a PHP file without putting a <form> tag inside (it will brake all the structure otherwise and will not be valid)?
I could use jQuery (or JS), but I still do not know how to do this. If PHP would have something like "onclick" function :)
Thank you in advance.
You can send an ajax request without a form, like this :
$('.sexybutton').on('click', function() {
var users = $.map( $('li.users'), function(el) {
return $(el).text();
});
$.ajax({
url : 'delete.php',
data: users
});
});
just create the data you need, and send it ?
<form id="your_form">
<ul>
<li><button class="sexybutton" onclick="$('#your_form').submit();">
<span><span><span class="add">Add</span></span></span>
</button></li>
</ul>
</form>
explanation:
wrap your existing code with form element, give some unique id to your form (e.g. your_form) and then add attribute onclick to your button and fill it with some jquery syntax (or pure javascript if you wish):
$('#your_form').submit();
this will do the submit job.
I have a webpage that generates a table from mysql. I have a button at the beginning of each row. I would like it so if the user decides to press on the button, the contents of that individual row are written to a new table in MySQL.
Currently I am thinking of just having the button be an href to another php script that connects to mysql and inserts the row into a table; however, I think that will redirect my current page.
I would like the button to run the script, without redirecting my current page. That way, the user can continue analyzing the table without having the page have to reload every time.
This is what my current table looks like. This is just a snippet, and the table can be very large (hundreds of rows)
In order to do this client side, there are a couple of ways I can think of off hand to do this:
Javascript
You can include a Javascript library (like the ever popular JQuery library), or code it yourself, but you could implement this as an XMLHTTPRequest, issued from a click handler on the button. Using a library is going to be the easiest way.
An iframe
Create a hidden iframe:
<iframe style="display:none;" name="target"></iframe>
Then just set the target of your tag to be the iframe:
...
Whenever someone clicks on the link, the page will be loaded in the hidden iframe. The user won't see a thing change, but your PHP script will be processed.
Of the two options, I'd recommend the Javascript library unless you can't do that for some reason.
You need to insert a record into mysql table upon click of button without reloading the page.
For accomplishing the above task you need to use AJAX which will send http request to server in background using xmlhttprequest object and thereby updating web page without reloading the web page.
So you will have to create a function in javascript which will send http request to server using xmlhttprequest object and also you need to define server side handler for processing http request sent using ajax.
For implementation details of ajax with php ,please refer the example mentioned in below link
http://www.w3schools.com/php/php_ajax_php.asp
It's easy to do using jQuery:
<script>
$(function(){
$('#your_button_dom_id').click(function(){
$.ajax({
url: 'your_php_script_url',
type: 'POST', // GET or POST
data: 'param1=value1¶m2=value2', // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is: " + data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!");
}
});
});
});
</script>
You can read more about AJAX in jQuery here: http://api.jquery.com/jQuery.ajax/
You can use another input tag after your submit button with hidden type.
<input class="ButtonSubmit" type="Submit" name="Submit" id="Submit" value="Submit"/>
</p>
<input type="hidden" name="submitted" id="submitted" value="true" />
after that use in top of your code this
if (isset($_POST['submitted'])) {
// your code is here
}
it's work for me. you can use it in wordpress template as well
I am trying to run this tutorial
i did not implement the validation part yet, but my problem shouldn't be based on this. Here is my code:
<script type="text/javascript">
$("#submitbutton").click(function () {
var content = $.("#contentarea").val();
$.ajax({
type: "POST",
url: "addArticle.php",
data: content,
success: $.("#addArticle").append("<p>ok</p>")
});
return false;
})
</script>
As seen in the demo, it should not refresh the page because of the return false statement and also should do a post instead of get. But neither it does. It will continue to reload the page and also append the given content to the url as an argument. How do i prevent this / where is my failure?
Here is the whole thing
The tutorial you have followed is incorrect. There are more ways to submit a form than just clicking on its submit button (for example, you can press return while in a text field). You need to bind your code to the form's submit() event instead of the button's click() event.
Once you have done this, use your in-browser debugger to check whether the code is actually being run when you submit the form.
Also, the success parameter needs to be a function:
submit: function() { $("#addArticle").append("<p>ok</p>") }
EDIT : also, you have written $.( instead of $( several times. This will cause a runtime error, which may cause the code that blocks the submission to fail.
Well well well...
A few less nerves later, it works.
I decided to use the jquery form plugin
But, and i bet you'll love that, i have no idea why it is working:
<script>
$(document).ready(function() {
$('#addForm').ajaxForm(function() {
alert("ok");
});
});
</script>
<div id="addArticle">
<form id="addForm" method="post" action="addArticle.php">
<textarea id="contentarea" required="required" name="content"> </textarea>
<br />
<input type="submit" id="submitbutton">
</form>
</div>
I guess the author has done pretty good work, just wanted to tell my solution to that future guy who is searching on google for that problem.
I'm making a blog type webpage, with a div that has a 'like' and 'dislike' button, and a rating above which is a mysql query of likes/(likes+dislikes). When a user clicks like or dislike, I want to add their vote to the db, and dynamically change the rating value without reloading the page. Here's a little snippet of the html, I have barely worked with javascript, so any help would be great.
<div class="narrow_right_container">
<?php
$popularity = get_popularity($row);
?>
<div class="yellow_bg">Rating: <?php echo $popularity . "%"; ?></div>
<div style="margin-left:2px;">
<div class="dislike">
<img src="ui_images/dislike.png"/>
<span>Dislike</span>
</div>
<div class="like">
<img src="ui_images/like.png" />
<span>Like</span>
</div>
</div>
</div>
You would not actually be changing a PHP value--once the page is output to the browser, consider PHP gone--you can't interact with it because it's on the server. Instead, think of interacting with the document that's in the browser.
The best way to do this is to make an ajax call to a server-side script. That server-side script can commit the like or dislike to the database, and then return the new rating, which you can insert in place of the old one using javascript.
You'll probably want to check out some tutorials on javascript and ajax, as it seems you have a more general need for a tutorial than for a specific problem. In other words, if you fill in your knowledge gaps on the general subject, you'll be able to solve your specific problem quite easily.
You will want to create some PHP code for handling the saving to the database on the Server side. You will POST the like / dislike value information to this server side script. If possible, I would use jQuery's AJAX helper to post data to the PHP page you just created.
Something like this:
$.ajax({
url: "whatever.php",
type: "POST",
data: {Like: true},
success: function(data){ /* update view */}
});
You will have to use ajax to accomplish this. Its not possible to alter PHP variables VIA javascript.
You will have to call an Ajax function that will handel the database work and after its done that, you will have to update the count using javascript. This will give the allusion that the count was updated while the count will also be updated in the database (from the Ajax)
Here is a great example of how you could accomplish this:
Example Code
Live Demo
$('.like').click(function(){
rate(1);
})
$('.dislike').click(function(){
rate(-1);
})
function rate(_val){
$.ajax({
url: 'ajax/rate.php?val='+_val,
success: function(data) {
alert('Rate was performed.');
$(".narrow_right_container").find(".yellow_bg").append("Rating: "+data+"%");
}
});
}
in rate.php:
if(isset($_GET['val'])){
$sql = "UPDATE.........."; //do an update to your rate table
echo get_popularity($row); //return rating to ajax
}
I have a big problem with my website.
I have made it in a way that seems to stop be from doing anything.
I have a number of containers, the main part of the page has three small containers all on top of each other and then a bigger container next to them that has the main content. The content that is shown in this main container is pulled from other pages so I don't have to refresh the whole page ever time a link is pressed. So I have one main page (the index) and a bunch of other content filled pages.
Now, if a page were to need to post data to the server to process it and then confirm with the user, this can't be done with normal PHP like I'm used to because the whole page is refreshed and it goes back to the default.
So I thought, I know Ajax can do this. I can post data to the server, process it and then change something on that page without loading anything.....
But I was wrong, it seems that it still wants to refresh the whole page meaning I lose my data. Also with the Ajax I am using "post" not "get" but for some reason it's putting the data into the address bar.
Is there a way I can keep my current structure and be able to do this, or am I doomed?
Any help, tips, code or advice would be MORE than welcome and thank you for the time and help.
Oh yeah, if I view the content outside of the index page the script runs just fine, it's only when the index pulls it from another page.
Ajax:
unction pass()
{
// Real Browsers (chrome)
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var oldPass = document.getElementById('oldPass').value;
var newPass = document.getElementById('newPass').value;
var newPassCheck = document.getElementById('newPassCheck').value;
xhr.open("POST","changeSettings.php");
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
var obj = {oldPass: oldPass, newPass: newPass, newPassCheck: newPassCheck};
xhr.send("data=" + JSON.stringify(obj));
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
//grade = xhr.responseText;
document.getElementById("myDiv").innerHTML = xhr.responseText;
//document.write.grade;
//alert ("Nice essay. Your grade is " + grade);
}
}
return false;
}
Here is the original page:
<div id="content">
<form>
<h1>This page is still under construction please do not attempt to use it!</h1>
<p>
Old Password: <input type="password" name="oldPass" id="oldPass"><br />
new Password: <input type="password" name="newPass" id="newPass"><br />
Retype Password: <input type="password" name="newPassCheck" id="newPassCheck"><br />
<input type="submit" name="submit" value="Submit" onClick="return pass();">
</p>
</form>
<div id="myDiv" name="myDiv"> </div>
</div>
Just because you're supplying "POST not GET" in the form doesn't mean ajax will handle it this way.
What needs to be actually done is attach to the submit event of the form, then let AJAX handle it the rest of the way. On a confirmed submission (or even a failure) you can update content (or show errors).
To keep it simple with jQuery...
<div id="content-container">
<form method="post" action="/some/submission/page.php">
<!-- flag to let the landing page know it's an ajax request
this is optional, but IMHO it makes for a more seamless
experience -->
<input type="hidden" name="ajax" value="true" />
<!-- controls go here -->
</form>
</div>
So there's your form. Now, you need to attach to the submit event. Again, I use jQuery for simplicity, but feel free to use any method. I also am creating a very generic controller here so you could presumably use it for every form found on the page, but that's up to you. (And, because we still decorate the <form> an absence of javascript will still proceed, but when it IS there, it will use the nice ajax look and feel)
// use .live to catch current and future <form>s
$('form').live('submit',function(){
var target = $(this).prop('action'),
method = $(this).prop('method'),
data = $(this).serialize();
// send the ajax request
$.ajax({
url: target,
type: method,
data: data,
success: function(data){
//proceed with how you want to handle the returned data
}
});
});
The above will take a normal form found on the page and make it submit via AJAX. You may also want to bind to $.ajaxError so you can handle any failures.
Also, depending on the content you return from the AJAX call, you can either pass the entire response back to the container ($('#content-container').html(data); in the success call), or if it's JSON or plain text, display other data.
Oh, and using my example, you may want to have something like the following in your posted page:
<?php
$ajax_call = isset($_POST['ajax']);
if (!$ajax_call){
// not an ajax call, go ahead with your theme and display headers
}
// output content as usual
if (!$ajax_call){
// again, not ajax, so dump footers too
}
(That way when it's AJAX, only the info in your container is returned, otherwise display the page as usual because they probably don't support AJAX/JavaScript).
You need to put up the page or post a code example in order to get answers to this question.
If I were to take a guess, it would be that you are not preventing submission of the form, so it's firing off the ajax request like you asked, but also submitting the form. In order to prevent it, you need to select the submit button and have it return false. Here's a quick example with jquery of how you would do this
$('input[type=submit]').click(function(){
$.ajax({ ... request here ... });
return false
});
or you can also catch the click event and prevent default, as such
$('input[type=submit]').click(function(event){
event.preventDefault();
});
Since I can't see any of your code, this is not guaranteed to be right. If you post the code, I can revise this. In the meantime, hopefully I guessed it!