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)
{
$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
jQueryand jQuery’s$.ajax()method.See Live example: http://jsfiddle.net/rtE9J/11/
HTML
CSS
JS
I even threw in a nice loading icon for you.