Switching around buttons with jQuery and Ajax
I have two buttons, Save and Unsave. Typically, I had each go to a PHP post page and that refreshed the page. If you clicked Save, the page would be refreshed and only Unsave would show - and vice versa.
I'm trying to do this with Ajax and jQuery. Basically, I have these:
<span style="display: <?php echo $youveSaved; ?>"><input type="button" value="Unsave" onClick="$.post('php/removeSave.php', $('#removeSave').serialize());$('#jqs').attr('value', 'Save');" id="jqs"/></span>
<span style="display: <?php echo $hasSaved; ?>"><input type="button" value="Save" onClick="$.post('php/saveCoup.php', $('#saveCoup').serialize());$('#jqs').attr('value', 'Unsave');" id="jqs"/></span>
Here's the PHP that would normally switch them:
//$thisIsSaved would return 1 if the coupon has been saved and 0 if not
$hasSaved = "inline";
$youveSaved = "none";
if($thisIsSaved > 0 && $_SESSION["loggedIn"] == 1)
{
$hasSaved = "none";
$youveSaved = "";
}
elseif($thisIsSaved == 0 && $_SESSION["loggedIn"] == 1)
{
开发者_StackOverflow中文版 $hasSaved = "";
$youveSaved = "none";
}
else
{
$hasSaved = "none";
$youveSaved = "none";
}
How could I do that without a page refresh, with pure Ajax + jQuery?
You can easily do that with jQuery
and jQuery's $.ajax()
method.
See Live example: http://jsfiddle.net/rtE9J/11/
HTML
<button id="save">Save</button>
<button id="unsave">Unsave</button>
<div id="result"></div>
CSS
#unsave{display:none}
JS
$('#save, #unsave').click(function(){
//maintain reference to clicked button throughout
var that = $(this);
//disable clicked button
$(that).attr('disabled', 'disabled');
//display loading Image
$('#result').html('<img src="http://blog-well.com/wp-content/uploads/2007/06/indicator-big-2.gif" />');
//Make your AJAX call
$.ajax({
url: 'changeSave.php',
data: {action: $(this).attr('id')},
success: function(d){
//re-enable the button for next time
$(that).attr('disabled', '');
//Update your page content accordingly.
$('#result').html(d);
//Toggle the buttons' visibilty
$('#save').toggle();
//Toggle the buttons' visibilty
$('#unsave').toggle();
},
type: 'POST'
});
});
I even threw in a nice loading icon for you.
精彩评论