I've been trying to alert some thing onclick of Bootstrap Switch Button.
But every time I do that, nothing fires up.
So I tried onchange, and it alert something, but when I added the ajax function for the onchange. It didn't work again.
Here are my codes:
<input type='checkbox' onclick='switchStatus($id,$status)' data-size='mini' name='my-checkbox' $status>
Here is the code for my function:
function switchStatus(id,status){
alert(id);
/*var theID = id;
var theStatus = status;
var dataString = "projectID=" + theID + "&status=" + theStatus,
$.ajax({
url: "ajax/updateProjectStatus.php",
type: "POST",
data: dataString,
cache: false,
success: function (data){
alert(data);
}
});*/
}
Here's the rest of the code:
<?php
$sql = $db->prepare("SELECT * from tbl_project where col_status <> 2");
$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC))
{
$id = $result['projectID'];
$name = $result['col_projName'];
$date = $result['col_createdDate'];
$status = ($result['col_status']==1) ? "checked" : "";
$sd = "asd";
echo "
<tr>
<td>$id</td>
<td>$name</td>
<td>$date</td>
<td>
<input type='checkbox' onchange='switchStatus($id,$status)' data-toggle='toggle' $status>
</td>
<td>
<div class='btn-group' role='group'>
<input type='button' value='Manage' onclick='Xmanage($id,\"$name\")' class='btn btn-info'>
<input type='button' value='Remove' onclick='Xdelete($id)' class='btn btn-danger'>
</div>
</td>
</tr>
";
}
?>
On you dataString variable, you end it with a comma, this indicates that a next property is coming, which is not the case.
Replace that with a semicolon and see what that does..
var theID = id;
var theStatus = status;
var dataString = "projectID=" + theID + "&status=" + theStatus;
$.ajax({
url: "ajax/updateProjectStatus.php",
type: "POST",
data: dataString,
cache: false,
success: function (data){
alert(data);
}
});
Related
few days ago I change my PHP version from 5.4 to 5.5 due to some code needed for render QR code. And today i found error in this function:
$(function changeStav() {
$("#selPismoSet<?php echo $id;?>").change(function() {
var del_id = $(this).attr("id");
del_id = del_id.replace("selPismoSet","");
var id = del_id;
var val = $('#selPismoSet<?php echo $id;?> option:selected').val();
$.ajax({
type: "GET",
url: "actions.php?action=changeStav",
data: 'id=' + id+ '&stav=' + val,
success: function(data){
e.preventDefault();
$('#content, #ok<?php echo $id;?>').html(data);
console.log();
}
});
return false;
});
});
I got this error:
I dont know where is the problem. Its possible that error is due to change PHP version?
You are missing an argument in your function. e is not defined
$(function changeStav() {
$("#selPismoSet<?php echo $id;?>").change(function(e) {
var del_id = $(this).attr("id");
del_id = del_id.replace("selPismoSet","");
var id = del_id;
var val = $('#selPismoSet<?php echo $id;?> option:selected').val();
$.ajax({
type: "GET",
url: "actions.php?action=changeStav",
data: 'id=' + id+ '&stav=' + val,
success: function(data){
e.preventDefault();
$('#content, #ok<?php echo $id;?>').html(data);
console.log();
}
});
return false;
});
});
(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});
I looked for many answers here but couldn't resolve this. I'm trying to submit form with two different submit button in the form but in the result it is like asking for method and action for the form. Though i have used e.preventDefault()
for preventing default form submission. thanks
Here is my form
<form class='detail-button'>
<input type='hidden' id='sell_id' value='$pro_id' />
<input type='hidden' id='sell_name' value='$pro_name' />
<input type='hidden' id='sell_vd' value='$vendor' />
<input type='submit' id='sell_add' class='btn' value='ADD TO CART'/>
<input type='submit' id='sell_buy' value='BUY NOW'/>
</form>
And here is script used
$(document).ready(function() {
$('#sell_add').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=cart',
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
}
});
});
});
$(document).ready(function() {
$('#sell_buy').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=buy',
success: function(data) {
window.location.href = data;
}
});
});
});
PLease Use :
detail-button is Your Form Class
$('.detail-button').on('submit',function(event){
// Write Your AJAX Code Here
}
Change Your submit button type. It will work because you have set event on button click by using its id.
<input type='button' id='sell_add' class='btn' value='ADD TO CART'/>
<input type='button' id='sell_buy' value='BUY NOW'/>
and submit through JS
$(".detail-button").submit();
I propose to use the submit event for submitting the form and a click event for adding to cart. Furthermore change the submit type for "add to cart" to button
You can use this script:
$('#sell_add, #sell_buy').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
var click = this.id == "sell_add" ? "cart" : "buy"; // <---check if clicked button is "sell_add"
$.ajax({
type: "POST",
url: "add_to_cart.php",
context:this, // <----------add context to get the clicked button
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click='+click ,
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
if(this.id == "sell_id"){ // <--------------execute for sell_add
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
} else { // <----------execute for buy.
window.location.href = data;
}
}
});
});
or a better one is to use data-* attribute to store specific information:
<input type='submit' data-click='cart' id='sell_add' class='btn' value='ADD TO CART'/>
<input type='submit' data-click='buy' id='sell_buy' value='BUY NOW'/>
use this script below:
$('#sell_add, #sell_buy').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
var click = $(this).data('click'); //<------get the data-click here
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click='+click,
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
if(click == "cart"){ // <--------------execute for data-click="cart"
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
} else { // <----------execute for data-click="buy".
window.location.href = data;
}
}
});
});
See the updated code i have added here.
usually e.preventDefault() work but if u added return false at the end of event then it help much.
see the code snippet might be it will help you
$(document).ready(function() {
$(document).on("click","#sell_add",function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=cart',
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
}
});
return false;
});
$(document).on("click","#sell_buy",function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=buy',
success: function(data) {
window.location.href = data;
}
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='detail-button'>
<input type='hidden' id='sell_id' value='$pro_id' />
<input type='hidden' id='sell_name' value='$pro_name' />
<input type='hidden' id='sell_vd' value='$vendor' />
<input type='submit' id='sell_add' class='btn' value='ADD TO CART' />
<input type='submit' id='sell_buy' value='BUY NOW' />
</form>
Following is my table where each row have 2 onClick event. When I click on each row it call the method's which I defined but Now you see that there are a check box to last column. I want if click on this check box then no need to call this method in Javascript onClick, is that possible ?
note: here php while loop is running :
echo "<tr onclick='getDetails($cdid), visited(this);'>";
echo "<td class='' valign='top' align='left' width='20'>$companyName</td>";
echo "<td class='' valign='top'>$family_name</td>";
echo "<td class='' valign='top'>$given_name</td>";
echo "<td class='' valign='top'>$department</td>";
echo "<td class='' valign='top'>$title<input type='checkbox' name='add_to_project'/></td>";
echo "</td>";
echo "</tr>";
Update:
function getDetails(id) {
try {
keepcontact = false;
if($("#contentText").val() != "" && $("#contentText").val() != null)
{
var toCharNotes = $('#saveToChrNote').is(':checked');
//AUTO save the charnotes if is checked without prompt
if( toCharNotes == true ){
var formData = new FormData($("#addNewNotes").parents('form')[0]);
var cid=$(this).parents('form:first').find('#cdid').val();
$.ajax({
url: 'response.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
getDetails2(id);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
} else {
var saveNote = confirm("Save or clear Enter Note before proceeding ?");
if (saveNote == true) {
var formData = new FormData($("#addNewNotes").parents('form')[0]);
var cid=$(this).parents('form:first').find('#cdid').val();
$.ajax({
url: 'response.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
getDetails2(id);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
} else {
keepcontact = true;
// do nothing.. :D
//getDetails2(id);
}
}
}
else{
getDetails2(id);
}
}
catch(err){
alert(err);
}
}
Just modify your function a bit
function visited(a)
{
if(a.getAttribute("name")=="add_to_project") return;
// Rest of the code of your function
}
Put this line on the top of the function visited
if(a.getAttribute("name")=="add_to_project") return;
Modify the PHP a bit
echo "<tr onclick='getDetails($cdid, this), visited(this);'>";
And modify the getDetails function
function getDetails(a, b)
{
if(b.getAttribute("name")=="add_to_project") return;
// Rest of the function
}
You can stop event bubbling using return false; at the end of the handler.
Try this demo scenario,
HTML :
<table id="infoTable">
<tr>
<td>Click Here</td>
<td>
<input type="checkbox" id="innerCheckBox" />
</td>
</tr>
</table>
jQuery :
$("#infoTable tr").on("click", function(){
alert("tr");
});
$("#innerCheckBox").on("click", function(){
alert("checkbox");
return false;
});
jsFIddle
Well, I'm validating my html form with jquery/ajax request. It's process by add_contact_process.php page. In this page if data (family or given name) is exit then I'm showing a message with a button which value is Yes and Cancel.
So
1) If Yes button is press I want to call a another jquery/ajax request which save the data to db.
2) If Cancel button is press then I want to remove/hide the message.
Can someone suggest me how can I do this ?
Html form code :
<form id="addcontact">
<table width="450" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Family name</td>
<td><input type="text" name="family_name" maxlength="50" placeholder="Family name"/></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="given_name" maxlength="30"placeholder="Given name"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add Contact" class="submit"></td>
</tr>
</table>
</form>
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
$('#success').delay(3000).fadeOut('slow');
</script>
add_contact_process.php page :
<?php
$family_name = inputvalid(ucfirst($_POST['family_name']));
$given_name = inputvalid(ucfirst($_POST['given_name']));
$exitfname = mysqli_query($link, "SELECT family_name FROM contact_details WHERE family_name = '$family_name'");
$numfname = mysqli_num_rows($exitfname);
$exitgname = mysqli_query($link, "SELECT given_name FROM contact_details WHERE given_name = '$given_name'");
$numgname = mysqli_num_rows($exitgname);
$msg = array();
$msg['error'] = false;
if(empty($family_name)){
$msg[] = "<div class='error'>Family name required.</div>";
$msg['error'] = true;
}
if(strlen($given_name) > 30){
$msg[] = "<div class='error'>Given name is too big.</div>";
$msg['error'] = true;
}
// If error is not found
if($msg['error'] === false){
if(!empty($family_name) && $numfname >= 1 || !empty($given_name) && $numgname >= 1){
$msg[] = "<div class='error'>A contact with this name exists. Do you wish to continue adding this new contact?
<input type='submit' name='warning' value='yes' id='yes' class='submit' style='margin:0px;'/>
<input type='submit' name='warning' value='Cancel' id='cancel' class='submit' style='margin:0px;'/>
</div>";
$msg['error'] = true;
}else{
$query_2 = "INSERT INTO contact_details (family_name, given_name) VALUES('$family_name', '$given_name')";
$query_2 = mysqli_query($link, $query_2);
$last_id = mysqli_insert_id($link);
if($query_2){
$msg[] = "<div class='success'><strong>Successfully added a new contact</strong>. </div>";
$msg['last_id'] = "$last_id";
$another = "close";
}else{
$msg[] = "<div class='success'>Sorry we can not add a new contact details. </div>";
$msg[] .= mysqli_error();
$another = "close";
}
}
}
echo json_encode($msg);
?>
Call Second ajax within success
<script>
$("#addcontact").submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#success').html('');
$('#success').show();
$.each( data, function( key, value ) {
if(key !== 'error' && key !== 'last_id') {
$('#success').append('<p>'+value+'</p>');
}
/*------------------------------------------------------------------*/
if(confirm('Write your message here')){
/* Second ajax after clicking ok on confirm box */
$.ajax({
url : 'Second URL',
method :'POST',
data : {'data1':data1},
success:function(response){
// code after success
},
error: function(e){
return false;
}
});
}else{
$('#success').hide();
$('#success').hide();
}
/*----------------------------------------------------------*/
});
if( ! data.error) {
$('#hide').hide();
setTimeout(function () {
$('input[type=submit]').attr('disabled', false);
var last_id = data.last_id;
window.location.href = "../index.php?redcdid="+last_id;
}, 5000);
}
}
});
});
You should define the second Ajax call in first Ajax call complete method. By default Ajax call is asynchronous, it will start executing the code or statements in success method with out waiting for response from the server. you code should me like this
$.ajax({
type: 'POST',
url: 'add_contact_process.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
// some code
},
complete:function () {
//you second ajax call
}