aJax update a specific row in sqlite and php using a button - javascript

I've got a table that lists values inputted by a user, with 2 buttons on the side to remove or to mark completed. On the page the table is visable, there are 3 tabs, we will call these Tab1, Tab2, and Tab3
Each tab has a table (As described above) with information about a specific type of entry.
These buttons are simple <a href> links, so when clicked they reload the page. This is a problem because the users view is refreshed and it takes the tabs back to the default tab, and is also an inconvenience when trying to mark several entries.
I would like to make these buttons send Ajax requests to another page to process the data. The only problem is, I am not really sure how to make the ajax call.
This is what I have right now
My buttons
echo "<td class='td-actions'>";
echo " <a href='?complete=".$row['uniqueID']."' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'> </i>
</a>
<a href='?remove=".$row['uniqueID']."' class='btn btn-danger btn-small'>
<i class='btn-fa fa-only fa fa-remove'> </i>
</a>";
echo "</td>";
There is one called Complete, and one called Remove.
When either of these are pressed, it currently reloads the page which triggers a few php if statements.
if(isSet($_GET['remove'])) {
$sql = "DELETE from rl_logged where uniqueID='".$_GET['remove']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
if(isSet($_GET['complete'])) {
$sql = "UPDATE rl_logged set complete=1 where uniqueID='".$_GET['complete']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
These are relatively simple functions. My problem is that I do not know javascript very well.
Any help would be much appreciated.
the javascript that I have come up with is this
$(document).ready(function() {
$('#markComplete').click(function() {
var input = input = $(this).text()
$.ajax({ // create an AJAX call...
data: {
onionID: input,
},
type: 'POST', // GET or POST from the form
url: 'pages/ajax/markCompleteRL.php', // the file to call from the form
success: function(response) { // on success..
refreshAllTabsWithFade();
}
});
});
});
using this button
<div name='markComplete' id='markComplete' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'></i>".$row['uniqueID']."
</div>
But, while inspecting with firebug, this seemed to work ONCE, but now the button doesn't do anything.
I tried again this morning, the button presses and the first time it sends this post, then the button doesn't do it again - even on page reload.

I was able to get it to work with the following:
javascript:
$('.markComplete').submit( function( event ) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // serialize the form
type: "POST", // GET or POST from the form
url: "pages/ajax/repairlogMarks.php", // the file to call from the form
success: function(response) { // on success..
refreshAllTabs();
}
});
return false;
});
button:
<form class="markComplete">
<input type="text" style="display:none;" class="form-control" name="uniqueid" value='<?=$row['uniqueID'];?>'>
<input type="text" style="display:none;" class="form-control" name="markcomp" value='1'>
<button type="submit" class="btn btn-success">
<i class="btn-fa fa-only fa fa-check"></i>
</button>
</form>
Basically, I made the button into a form which I knew how to create an ajax request for.
--
Update to make it work for multiple buttons that do the same function for different unique ID's.

Well for since you're sending the ajax call using "POST", it seems to me that if(isSet($_GET['complete'])) would evaluate to false. Also if your button is generated dynamically using php then change your click handler to the following:
$('document').on('click', '#markComplete', function (){
// Your code here
})

If you have more than one "Mark Complete" button; you need to use classes rather than ID to bind the event.
<button id="test">
Test 1
</button>
<button id="test">
Test 2
</button>
<script>
$('#test').click(function (e) {
console.log('test', e.target);
});
</script>
In this example, only the first button works. jQuery will only return the first element when you specify an ID.
If you use classes to bind the event; both buttons will work:
<button class="test">
Test 1
</button>
<button class="test">
Test 2
</button>
<script>
$('.test').click(function (e) {
console.log('test', e.target);
});
</script>

i think you have an error in your javascript at this line...
var input = input = $(this).text()
try to replace by this..
var input = $(this).text();

Related

jQuery prompt before submitting a form, PHP distinguishing which button was used

Good morning everyone.
I have problem with displaying user a prompt using sweetalert (that's kinda irrelevant)
Simplified HTML
<form class="form-horizontal" method="post" action="post.php?id=<?php echo $wid; ?>">
<button type="submit" name="submit1" class="btn btn-success">Submit #1</button>
<button type="submit" name="submit2" class="btn btn-warning">Submit #2</button>
<button type="button" class="btn btn-danger "onclick="remove()">REMOVE()</button>
</form>
PHP that form is submited to. I have to distinguish between buttons used so simplified:
if(isset($_POST['submit1'])){
//do stuff
} elseif(isset($_POST['submit2'])) {
//do second stuff
}
Finally JS code that displays the prompt:
function remove() {
var id = <?php echo $wid ?>;
swal({
title: "Sure?",
type: "warning",
}).then(function() {
swal({
title: "Removed!",
});
removeRow();
});
return false;
}
function removeRow() {
var id = <?php echo $wid ?>;
window.location = 'delete.php?&id=' + id;
}
However I cannot do the same prompt with those two submit buttons.
What's the issue there:
It has to be submit button otherwise PHP won't recognise which
button was used to submit
When i click submit button form automatically submits before "reading" javascript code (what's kinda logic) but even though I stop the event and then try to .submit() with jQuery it wont work out because I cannot submit a form from button-level so form won't pass name of button that was used to be submitted - won't work
How can i show user prompt and it holds submitting untill users accepts warning and yet be able to distinguish which button was used to submit it (so php get's submitted button name)?
I edited PHP into two separate files.
Afterwards I added two listeners on click on both of buttons. I removed submit type of them and then added jQuery code:
$( "#submit1" ).click(function() {
var id = <?php echo $wid ?>;
swal({
title: "Sure?",
type: "warning",
}).then(function() {
swal({
title: "Success!",
});
$('#formW').attr('action', 'script.php?id='+id);
$('#formW').submit();
});
return false;
});

jQuery AJAX Button Click - Remove Table Row after AJAX Call is Successful

I'm displaying an HTML table and would like to include a button in the last column that, when clicked, performs an AJAX call which will result in the removal of the table row from the table. I'm new to jQuery and AJAX and working things out as I go - I've managed to setup some AJAX calls that run when a field is edited, but now I'm struggling to attach one to a button in a table row.
Here's how the table looks:
<tr class="" id="tableRow1"><td>Store 1</td><td>lorem ipsum</td><td>John Smith</td><td>20/11/2014 12:53:52 AM</td><td><button type="button" id="closeNote" class="btn btn-primary">Acknowledge</button></td></tr>
<tr class="" id="tableRow2"><td>Store 2</td><td>lorem ipsum</td><td>Sally Jones</td><td>20/11/2014 12:53:52 AM</td><td><button type="button" id="closeNote" class="btn btn-primary">Acknowledge</button></td></tr>
<tr class="" id="tableRow3"><td>Store 3</td><td>lorem ipsum </td><td>Bill Howden</td><td>12/11/2014 01:43:03 PM</td><td><button type="button" id="closeNote" class="btn btn-primary">Acknowledge</button></td></tr>
I know that the ID for the button is not unique - at the moment the script only fires when the button in the first row is clicked. I'm not sure how to assign a unique ID for each button which the script can see.
Here's my script:
<script type="text/javascript">
$(document).ready(function() {
$("#closeNote").click(function(){
$.post('editNote.php', { type: 'hideNote', id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
data = JSON.parse(data);
if (data.error) {
$("#ajaxAlert").addClass("alert alert-danger").html(data.text);
$("#ajaxAlert").show();
return; // stop executing this function any further
} else {
$("#ajaxAlert").hide();
$(this).closest('tr').remove();
}
}).fail(function (xhr) {
// no data available in this context
$("#ajaxAlert").addClass("alert alert-danger");
//display AJAX error details
$("#ajaxAlert").html(xhr.responseText);
$("#ajaxAlert").show();
});
});
});
</script>
I just need some help in bring this altogether so that when the button is clicked on any row it calls the script which in turn, if the PHP script it then calls is successful, it then removes the row where the button was clicked.
Rather than applying the button to an ID give each link a class:
<button class="btn btn-primary close-note"
Then amend your JS as follows:
$("button.close-note").click(function(){
Inside your callback functions the keyword this no longer refers to the element, but instead refers to the XHR object.
To solve this assign $(this) to a variable outside of the $.post
var $self = $(this);
$.post( ... ... function(response){
// code and stuff
$self.closest('tr').hide();
});
You also need to ensure that the browser doesn't then follow the link; amend the click line again:
.click(function(e){
e.preventDefault();

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

JQuery Ajax call stop refresing the page

I have the following html code:
<div>
<form id="ChartsForm">
<div id="optionsheader">
<p>Choose your page:</p>
<div id="dateoptions">
<p>Until date: <input type="date" name="until_date" value="Until date"></p>
<p>Since date: <input type="date" name="since_date" value="Since date"></p>
</div>
</div>
<select name="accmenu" id="accmenu" style="width:300px; float:left; clear:both;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<div class="insightsoptions">
<p>Choose your insights:</p>
<input id="newLikes" class="insightsbuttons" type="submit" name="submit" value="Daily new likes">
<input id="unlikes" class="insightsbuttons" type="submit" name="submit" value="Daily unlikes">
</div>
<div class="insightsgraphs">
<div id="dailyNewLikes"></div>
<div id="dailyUnlikes"></div>
</div>
</form>
</div>
which has a form with the id=ChartForm that contain two date inputs until_date and since_date, one select accmenu and two submit inputs with the values Daily new likes and Daily unlikes. I use the following Jquery function:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").attr("class","insightsbuttons");
});
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setSize(960, 320);
myChart.setAxisNameX('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setAxisNameY('');
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
$("#dailyUnlikes").html(response);
}});
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
});
});
for the application flow in the following manner: every time I click on one of the input submit buttons the script will make only one Ajax GET request to a specific php file that send me back a response with which I create a Chart in a hidden div with the id=dailyNewLikes or id=dailyUnlikes by case (for testing purposes I work for the moment only on the first button). The button it will change his background color into green and the div it will be shown. I use $("#newLikes").on('click', function(){ for change back and forth the background color and the display time of the div. (from green and display:block to red and display:none, you get the point I hope :D). Also I use $('#accmenu').change(function() { to change all buttons to red and hide the respective div in case an option from the select is changed. My problem is that after I refresh the page (Ctrl+R) choose since and until date, click on the first button (it change to green and the div is shown, also the toggle is working fine) and then click on the second button which works fine on the first click (is becoming green and div is shown) but on the second click I have an issue: the script is making another Ajax GET request (a wrong URL one) and the page is refreshed. Ex. of a good reguest URL:
http://localhost/smd/unlikes.php?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701
and an ex. of a wrong request URL:
http://localhost/smd/?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701&submit=Daily+unlikes#_=_
Like it can be seen (it doesn't need in the first to make this extra request) the php file is not present and also a new submit parameters is added. This also happen if I change from the select with another option. What am I do wrong? I really need to know, not just to have my code "fixed". It bugging me for a little while. Any feedback is more than welcomed. P.S. Also, how can I start the .one function only if both date inputs has been choosen? Something like how could help me?
var until = $('#dateoptions input[name="until_date"]').val();
var since = $('#dateoptions input[name="since_date"]').val();
if (until == "" || since == "") {
alert('Until date or Since date missing!');
return;
}
it will work that way? Sorry for the long question...
i think you should make your question a little shorter and just point what you need and what errors are you getting ..anyways...going through your code i see you have two click event for same button at the end for $("#unlikes").one and $("#unlikes").on(..and no return false in other function.
try adding return false
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
my guess is that , since you have two click event..when it gets clicked ..these event will fire and since you are missing return false in second click function...the form gets submitted hence refreshing the form.
however its better if put your codes in single click function than creating two seperate click event.

Delete Record Confirmation Message

I wonder whether someone may be able to help me please.
Firstly, my apologies because I'm really very new to this, so please forgive me what some may seem a very basic question/error.
The extract of code below, successfully creates a table of records pertinent to the current user.
Working Solution - Baylor Rae' worked tirelessly with me over the last 3-4 days to find a solution. All Baylor Rae' was unable to provide a fully successful script, they certainly helped considerably in moving this on . However the full working script below is Courtesy of jazzman1 # PHP Freaks
Main Script
<script type="text/javascript">
$(document).ready(function(){
$('form.delete').submit(function(e){
console.log('submit'); return false;
})
})
</script>
<script type="text/javascript">
$(document).ready(function(){
$('form.delete').submit(function(e){
e.preventDefault();
var elem = $(this).closest('.delete');
var lid = $(this).serialize();
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this Location. <br />It cannot be restored at a later time! Do you wish to continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
//elem.slideUp();
$.ajax({
url: 'deletelocation.php',
type: 'POST',
data: lid,
success: function(response) {
console.log('success', response);
},
error: function() {
console.log('error')
}
});
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
})
</script>
jqueryconfim.js
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
Form In Main Script
<form name="delete" id="delete" class="delete">
<input type="hidden" name="lid" id="lid" value="<?php echo $theID ?>" />
<input type="submit" value="Delete Record"/>
</form>
deletelocation.php
<?php
$lid = intval($_POST['lid']);
$query = mysql_query("DELETE FROM table WHERE locationid='".$lid."'");
?>
You'll see that the end of the table are four buttons, which, through the locationsaction.php script navigate the user to four different screens all linked back to the main table record via the lid value. This script is shown below.
I'm now trying to implement a confirmation message for the Delete function. The source code for this can be found here.
This is where I've become a little unsure about what to do next. I've tried to link the button on click event with the name of the Delete function, but rather than the confirmation message, the user is taken to a blank screen and the record is deleted.
I've run the JavaScript Console and there are no errors created, so I'm a little unsure about how to continue.
I just wondered whether someone could possibly take a look at this please and let me know where I'm going wrong.
Many thanks and kind regards
Prevent the Redirection
It looks like you're getting the redirection because the form is still submitting. You need to prevent the form from submitting by adding the following line at the beginning of your click event.
$('#btn-delete').click(function(e) {
e.preventDefault();
var elem = $(this).closest('.item');
Calling e.preventDefault() will prevent the browser's default action from occuring, in this case submitting the form.
Changing the way buttons are handled
As far as I can tell locationsaction.php redirects to a page based on the value of the button.
A better way to do this would be to create a link to each page and pass the lid as a parameter. This is the standard way of linking pages while providing some context for the next page.
Note: You will need to change each page to use $_GET['lid'] instead of $_SESSION['lid'].
Note 2: It is perfectly valid to "close" and "open" PHP tags in the middle of a page. In the code I provided below I closed PHP so I could write HTML, and reopened PHP when I was done.
<?php // this line is for syntax highlighting
/* display row for each user */
$theID = $row['locationid'];
?>
<tr>
<td style="text-align: center"><?php echo $row['locationname'] ?></td>
<td>Images</td>
<td>Add Finds</td>
<td>View Finds</td>
<td>
<form method="post" action="deletelocation.php" class="delete-record">
<input type="hidden" name="lid" value="<?php echo $theID ?>" />
<input type="submit" value="Delete Record" />
</form>
</td>
</tr>
<?php
The only time I didn't use a link was when I linked to the deletelocation.php file. This is because you should never use a GET request when modifying a database.
Using a POST request is an easy way to prevent Cross-site Request Forgery.
Rename your table column names
I noticed that your column names for locationid and locationname didn't have any type of separation. I would recommend renaming these to location_id and location_name.
This applies to your file names as well. You can include an underscore or dash to separate the words in your filename. I usually use an underscore because I think it reads better, but it's your choice.
POST directly to the delete page
Because you're using AJAX, you can specify the deletelocation.php url directly. With the changes I've suggested above, there isn't a reason to keep locationsaction.php.
$.ajax({
url: 'deletelocation.php',
type: 'post',
data: $(this).parent().serialize(),
success: function () {
img.parent().fadeOut('slow');
}
});
I also changed how the data was passed. .serialize() will automatically grab the location id from input[name=lid] and create a query string like lid=1.
Edit #1
If possible, I'd like to keep the locationsaction script. A lot of my pages further down the line rely on a SESSION id, and using a Get isn't an option without re-writing a lot of code.
The way you're using locationsaction.php and sessions isn't the way I'd do it. But it's your application structure and you can build it however you like.
Could I change the button type to button rather than submit, keeping the id the same so the JS code will pick this up?
You can change the type to button, but when javascript is disabled it won't submit the form. In general, you write your page to work without JS, and then write the JS to modify the browser's default behavior.
Could you also confirm for me whether your AJAX just replaces the top section of my code?
No, I only changed the way you set the lid. You still need to include all the JS wrapped around it, I just didn't want to paste the whole block of code.
Observation 1:
function delete(){
$(document).ready(function(){
Is that really the order of the lines in your code? The jQuery ready hook lies INSIDE of your function definition? Or have you, by mistake, posted them here in the wrong order here.
If it's the former case, then please, fix this first before anything else. Otherwise, read on:
Why $('.item .delete')? I don't see any markup with class .item? Where is it? Are you sure that this selector matches some elements in the first place? Also, you should use #delete for referencing elements through their id attributes, not .delete, as that looks for elements with the class delete.
Your id:delete button and the other buttons are submit type buttons, which means that their click handlers simply will not block the submission flow. You can change all the button types to button, instead of having them as submit. Code example below.
Why the declarative onClick on the delete button? Get rid of it.
(Also, you really don't need a form in this case, unless you want to deserialize the form, which doesn't seem like a requirement or intent given your markup).
<td><input type='button' name='type' id='details' value='Details'/></td>
<td><input type='button' name='type' id='images' value='Images'/></td>
<td><input type='button' name='type' id='addFinds' value='Add Finds'/></td>
<td><input type='button' name='type' id='viewFinds' value='View Finds'/></td>
<td><input type='button' name='type' id='delete' value='Delete' /></td>
And your JS:
//please, be careful with the selector.
//it could be that it is not matched at all,
//hence jQuery will not bind to anything
//and nothing will ever fire!
//note the #delete for Id! .delete is for a class!!!!!!
$('.item #delete').click(function () {
var elem = $(this).closest('.item');
$.confirm({
'title': 'Delete Confirmation',
'message': 'Delete?',
'buttons': {
'Yes': {
'class': 'blue',
'action': function () {
//elem.slideUp();
$.ajax({
url: 'locationsaction.php',
type: 'post',
data: {
lid: "VALUE",
type: 'Delete' //you need to add the type here!
},
success: function () {
img.parent().fadeOut('slow');
}
});
}
},
'No': {
'class': 'gray',
'action': function () {} // Nothing to do in this case. You can as well omit the action property.
}
}
});
Also, you can redudantly add a false return to your form's onsubmit event.
Actually I don't find any button of id btn-delete on your form.If your using delete button present in form then change this
<input type="submit" value="Delete Record" />
to
<input type="button" id="btn-delete" value="Delete Record" />
Or your using any other input then make sure that it type is not submit for example
<input type="submit" value="Your button" />
should be
<input type="button" value="Your button" />
u can use jquery ui dialog for confirmation :
<script type="text/javascript">
$('#btn-delete').click(function (e) {
e.preventDefault();
var elem = $(this).closest('.item'), formSerialize = $(this).parent().serialize(), objParent = $(this).parent();
$('<div></div>').appendTo('body')
.html('<div><h6>Delete?</h6></div>')
.dialog({
modal: true, title: 'Delete Confirmation', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
$.ajax({
url: 'deletelocation.php',
type: 'post',
data: formSerialize//,
//success: function (data) {
// objParent.slideUp('slow').remove();
//}
});
//Or
objParent.slideUp('slow').remove();
$(this).dialog("close");
},
No: function () {
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
});
</script>
The problem isn't anything to do with JavaScript.
The fundamental problem seems to be that your form's action is to delete the record (regardless of what you've coded in JavaScript). Change the form's action to "." and onsubmit="return false" (which stops the form from doing anything on its own). Now attaching your $.confirm to the appropriate button should work.
Stepping back from this -- you don't need a form at all (or a submit button). Then you wouldn't have to fight the default behavior of a form.
Try to use e.stopPropagation();
$('#btn-delete').click(function(e) {
e.preventDefault();
e.stopPropagation();

Categories

Resources