Ajax Change class name of a link upon button submit - php

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>

Related

i had to click twice to open modal after hide modal using jquery

I want to add new data using form in a modal(id=modal_add_item) and reload related datatable without refreshing the page.
I used $.post() to post the data to the specific page.
But, the modal did not disappear. Thus, I tried googling and found some solution.
From my intense searching, i found these guys:
$('#modal_add_item').hide();
$('.modal-backdrop').remove();
$('#form_add_item')[0].reset();
and then i tried applying it into my code:
$('#form_add_item').submit(function(event) {
event.preventDefault();
var button = $("#btn_add_item");
var post_url = $(this).attr('action');
var form_data = $(this).serialize()
+ '&' + encodeURI(button.attr('name'))
+ '=' + encodeURI(button.attr('value'));
$.post(post_url, form_data, function(response) {
if(response.includes("msgE")) {
swal(
'Error!',
response.replace("msgE", ""),
'error'
)
} else {
swal(
'Success!',
response.replace("msg", ""),
'success'
)
}
$('#modal_add_item').hide();
$('.modal-backdrop').remove();
$('#form_add_item')[0].reset();
func_reload();
});
});
It works perfectly.. until I need to insert another data right after that process.
The button has to be clicked twice to open the dedicated modal.
Here, in case you need to see my code button
<button type="button" class="btn btn-sm btn-amber" data-toggle="modal" data-target="#modal_add_item">Add New Item</button>
What I need is that:-
The modal to disappear after the submit button is clicked.
The submitted data to be erased from the modal.
After post ajax response, display alert(in this case i used sweet alert) and in focus
Datatable refreshed(ajax.reload() is used)
No twice clicking to open modal after all of the above processes has been completed
image of twice clicking-GIF
To open a modal $('#modal_add_item').modal('show'); use
$('#id').modal('show' or 'hide')
$('#modal_add_item').modal('hide');
$('.modal-backdrop').remove();
$('#form_add_item')[0].reset();
I found an answer from these question
It has almost the same problem as mine
It used .then() (to focus on the swal alert) followed by $('#modal_add_item').modal('hide') instead of $('#modal_add_item').hide()

Simple AJAX bookmark

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/

ajax $_POST data then redirect to new page

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.

Need some guidance on creating a jEditable custom input

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.

jQuery UI dialogs based on dynamically generated information

Right now I have a table with a few items, each of which has an Edit icon. When the edit icon is clicked, the corresponding database ID of the item (its name) is sent via a $.get() AJAX method to process.php, which generates a JQuery UI dialog consisting of a few of that database item's attributes.
The first item that I click on brings up the proper dialog box with all of the attributes filled in the text boxes. However, when I click a different item, the same dialog box appears with the first item's information. Any other ones I click on still have that first item's information in the dialog box.
What I'm guessing is happening is that the data sent back to index.php, the new div and the jquery dialog call, has already been echo'd through and appended to the page--thus I get the same first box over and over. I just can't figure out how to fix it.
portion of index.php:
$('#edit_link').live('click', function(e){
var ID = $(this).attr('name');
console.log(ID);
$.get('process.php', {taskID: ID}, function(data){
$('body').append(data);
});
e.preventDefault();
})
...the console successfully logs each item's taskID, so that's not the problem.
process.php:
if(isset($_GET['taskID'])){
$taskID = $_GET['taskID'];
$task = TaskDB::getTask($taskID);
$duration = $task->getDuration();
$description = $task->getDescription();
$deadline = $task->getDeadline();
echo '<script>$("#dialog").dialog({
height: 150,
width: 300,
modal: true,
buttons: {
"Save Task": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});</script><div id="dialog" title="Edit Task" style="display:none;">
<p>Deadline: <input type="text" style="margin-right:10px;" value="'.$deadline.'"/> Duration (hours): <input type="text" style="width:20px;" value="'.$duration.'"/></p>
<p>Description: <input type="text" style="width: 200px;" value="'.$description.'"/></p>
</div>';
}
The echo portion is where I think the problem is, as the previous echoed data is not cleared out if another Edit was clicked.
Any help would be greatly appreciated. Also, I'm not entirely sure if what I'm doing is the best means for carrying out this goal (having PHP generate so much html/javascript), so any suggestions regarding that would also be very much appreciated. Thanks!
I think you should first remove the previous dialog from body. Try this:
$('#edit_link').live('click', function(e){
var ID = $(this).attr('name');
console.log(ID);
$("#dialog").remove(); // Delete the previous dialog
$.get('process.php', {taskID: ID}, function(data){
$('body').append(data);
});
e.preventDefault();
})
That sounds like you have to use .destroy() function when close the dialog. This function will reset your dialog
$('.dialog').dialog({
// your options
close : function() {
$('.dialog').dialog("destroy");
}
});

Categories