I have a list of items on a page using PHP. I want to add a simple AJAX toggle to allow users to bookmark an item in the list while they are browsing.
So if the item->bookmark field = 1, then the item is bookmarked and it should show a simple image. When they click it again, it make it ="0" in mysql and the bookmark image changes back to something else.
What is the best way to do this without reloading the page?
I feel like you could have googled "jquery ajax example" but here you go...
HTML:
<div class="container">
<div class="item" id="<?php echo $whateverYourIdIs; ?>">Bookmark me!</div>
</div>
jQuery:
$(document).ready(function(){
$('.item', $('.container')).click(function(){
var id = $(this).attr('id');
$.ajax({
type: "POST",
url: "some.php",
data: { id: id }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
AJAX is the way to go to save data on the server. But if you want to add / remove bookmark on the fly while on the page, you can use a function that toggle bookmark on and off, using data-* attributes
$(".bookmarkButton").click(function(){
if(! $(this).parent().data('bookmark')){
alert('bookmarked');
$(this).parent().data('bookmark', 1);
// Add image + AJAX call
}
else {
alert('not bookmarked');
$(this).parent().data('bookmark', null);
// Remove image + AJAX call
}
});
Here's a simple JSFiddle : http://jsfiddle.net/YwTuB/
Related
I have a four menu tabs. in One tab is a submit form (default), the second tab contain list of entries, each entry has a button called change status. When i click "change status" I called windows.reload using ajax to update the page with out refresh but the tab will go back to the default one which is the first one. Now my problem is how can i update the menutab class to the current selected menu to become an active one. below is my ajax codes:
<input type="button" value="change status"> // a button to click to change status
<a class="active">tab1</a> // need to change classname when the button clicked
<a class="nonactive">tab2</a> // need to change classname when the button clicked
<script>
$(document).ready(function() {
$(".closeBTN").click(function() {
var data = $(this).attr('id');
//alert (data);
$.ajax( {
type: "POST",
url: "../deals_status_update.php",
data: { 'id': data }
}).done(function(msg) {
$("#notification").html(msg);
window.setTimeout(function(){
location.reload()
$('#itrade .active').removeClass().addClass('nonactive');
$('#iopendeals .nonactive').removeClass().addClass('active');
},100)
});
});
});
</script>
location.reload() reloads the website, so you cant use jQuery methods after that.
maybe window.location.hash can help you.
Add a hash and parse this hash after the website reload to trigger your classes?
try using location.hash, cuz as explained location.reload() will actually refresh the page, and i still don't get why you need to refresh the page to update data !
<input type="button" value="change status"> // a button to click to change status
<a class="active">tab1</a> // need to change classname when the button clicked
<a class="nonactive">tab2</a> // need to change classname when the button clicked
<script>
$(document).ready(function() {
$(".closeBTN").click(function() {
var data = $(this).attr('id');
$.ajax( {
type: "POST",
url: "../deals_status_update.php",
data: { 'id': data }
}).done(function(msg) {
$("#notification").html(msg);
window.setTimeout(function(){
location.hash = 'iopendeals';
location.reload();
},100)
});
});
if(location.hash != '') {
$('.active').removeClass().addClass('nonactive');
$(location.hash + ' .nonactive').removeClass().addClass('active');
}
});
</script>
You're reloading the page, so any JavaScript that happened later will lose its state. DOM modifications are only good for the current page session. Once it is navigated away or reloaded, they lose progress.
Have you considered not reloading? Why are you reloading for anyway?
or,
Can you maybe do those changes client-side, and instead of reload, redirect to the same page with different GET parameters?
<li class="menuitem<?=$_GET['page'] == 'homepage' ? ' active' : ''?>">
Homepage
</li>
I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.
I'm using the jEditable plugin and the following code to toggle between On and Off for a series of settings on a page.
$(document).ready(function() {
$('.editable_select').editable(''http://someexamplepage.com/save.php', {
indicator: '<img src="/images/spinner.gif">',
data : " {'✓':'✓','✗':'✗'} ",
tooltip : 'Click to Edit',
type : 'select',
onblur : 'submit',
style : 'inherit'
});
});
And then this in the html:
<b class="editable_select" id="setting1" style="display:inline">✓</b>
When the checkmark indicating On is clicked, it produces a dropdown menu with checkmark for On and the X for Off in it, which the user can then select. What I would prefer is that clicking the check/X not open a dropdown, but instead send the current On or Off setting to the save.php file. I could then just write the save.php file to return the opposite value, so that clicking just toggles between the two without opening any kind of edit window. I tried the following code:
$(document).ready(function() {
$('.editable_select').editable('http://someexamplepage.com/save.php', {
indicator: '<img src="/images/spinner.gif">',
tooltip : 'Click to Edit',
onclick : 'submit',
style : 'inherit'
});
});
But clicking the text still opens a little editing window, which I don't want. I'm still new to JavaScript and jQuery, so any help is greatly appreciated!
I wouldn't use a plugin for this, but rather a very simple bit of jQuery to run on the ready event.
I would include the current state as a data attribute on the DOM, so change your tags to:
<b class="editable_select" id="[ID FOR ITEM]" data-state="checked">ઙ</b>
Then do something like:
$(function(){
var update_dom = function(data){
var item_id = data.id;
var state;
data.state === 'checked' ? state = '✓' : state = '✗';
$('#'+item_id).data('state', data.state).html(state);
};
var selected = function(evt){
var item_id = $(this).attr('id');
var state = $(this).data('state');
$.ajax({
url: PATH_TO_SCRIPT,
data: {id: item_id, state: state},
type: "POST",
success: update_dom
});
}
$('.editable_select').click(selected);
});
This binds the click event to everything that has a class of editable_select. When you click on it, it'll call the selected function, which wil get the data from the DOM, and call your script. When your script is complete, it should send back a response (JSON would be good here), and, the success handler will update the DOM and display the state back to the user.
Hello I am having trouble regarding div reloading when a new record has been added. What I wanted to do is to show first a loading image then after a record has been inserted it will reload the div.
$("a.follow").click(function(event) {
event.preventDefault();
$("#flash").show();
$("#flash").fadeIn(300).html('<img src="ajax-loader-transp.gif" />Loading Result.');
$.ajax({
//url: $(this).attr("href"),
success: function(msg) {
$("#results_div").load('http://localhost/<app_name>/index.php/<contoller>/index');
}
});
return false;
});
That's what I got to far when I'm trying the code it refreshes a whole physical of page on the div & not the desired div itself. . .
Sorry guys I am poor with jQuery and BTW this is in CodeIgniter.
Your problem is, that codeigniter obviously returns a whole html page. You have two choices:
Either return only a fragment (I don't know how to do this in CI) or use jQuery to parse out the div you want. This can be done with the following code, assuming that the div you want is named <div id="results_div">...</div>
$("a.follow").click(function(event) {
event.preventDefault();
$("#flash").show();
$("#flash").fadeIn(300).html('<img src="ajax-loader-transp.gif" />Loading Result.');
$("#results_div").load('http://localhost/<app_name>/index.php/<contoller>/index #results_div', function(){ $('#flash').hide(); });
});
Can you include the HTML with the #results_div div?
This is my best guess without html to work with:
$("a.follow").click(function(event) {
event.preventDefault();
// show the linke
$("#flash").fadeIn(300).html('Loading Result.');
//ajax load the 'mini div' result -- i guessed that this url pulls back the div you want
$("#results_div").load('http://localhost/<app_name>/index.php/<contoller>/index', function(data, text, xhr){
$('#flash').fadeOut("fast");
});
});
I want to basically create a link which says:
Click here to show contact information
Upon clicking it, it will ping a script via an ajax request, the ajax request will look up the user table where the ID is what is contained in the alt tag, it will return a certain field from the database and then the div will change from this link, to a contact number.
I'm sure some of you have seen this done before, for example:
Click to see persons phone number
They click it, and it changes to their phone number.
How would I go about doing this? I want to do it using ajax instead of having the phone number in the source code, because that really defeats the purpose of them having to click to reveal if bots can get it from the source code.
Thanks :)
Somethign along the lines of
$("#reveal").click(function(){
$.get('getphoneNumber.php',{id:$(this).attr('alt')}, function(data) {
$('#reveal').html(data);
});
});
with a php script called getphoneNumber.php that accepts a get parameter of id
Try this one
$('#reveal').click(function () {
var th = $(this);
$.get('/get-the-phone-number', { id: th.attr('alt') }, function (response) {
th.text(response);
});
});
Also, I'd recommend you put the id number inside a data-contact-id attribute and access it via th.data('contact-id') instead of using the alt attribute. Ignore me if you have other reasons to do this.
$("#reveal").live('click',function(event) {
var link = $(this).attr('alt');
var dataString = 'alt=' + link ;
$.ajax({
type: "POST",
url: "url",
cache:false,
data: dataString,
success: function(data){
this.href = this.href.replace(data);
}
});
}
Click here to show contact information
<div id="myHiddenDiv"></div>
$("#reveal").click(function(){
$.get("test.php", { id: $(this).attr("alt") },
function(data){
$("#myHiddenDiv").html(data);
$("#myHiddenDiv").show();
});
});
This example works assuming you've only got one of these "plugins" on your site, if you'll have multiple, use this:
Click here to show contact information
<div class="myHiddenDiv"></div>
$(".reveal").click(function(){
var divSelector = $(this).next("div");
$.get("test.php", { id: $(this).attr("alt") },
function(data){
divSelector.html(data);
divSelector.show();
});
});