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
Related
I have a trouble with my request AJAX. When I click on it, in the process, it calls an other php function which I don't need for this request (function switch, change statut).
http://www.noelshack.com/2022-31-1-1659342824-undefined-index.png
This line with error corresponds to another function.
My HTML :
<table id="list_client_pris" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client) :
?>
<tr id="tr1">
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="info">Info client</button></td>
<td><button type="button" class="hide_client" data-id="<?php echo $client["id_client"]; ?>">Masquer client</button></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="switch">Change statut</button></td>
</tr>
<?php endforeach; ?>
</table>
3 buttons call each their ajax's request.
The conflict is between the first button (class info) and the last, (class switch)
Why ?
The buttton class' info call a function which correspond to the error showed, but which is not called with the last button.
My JS , request for the first button, info:
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "POST",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
});
PHP corresponding function :
function read()
{
global $db;
$id_client = $_POST['id_client']; **(error showed)**
$query = $db->prepare("SELECT *,FROM client WHERE id_client = :id_client");
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
return ($result);
}
My other ajax's request for button switch :
$(".switch").click(function () {
var datas = {
cmd :' id_client_statut',
id_client: $(this).attr('data-id_statut'),
};
console.log(id_client);
$.ajax({
url: 'function.php',
type: 'POST',
data: datas,
done: function (click_result) {
console.log(click_result);
if (click_result.statut=2){
//transfer to libre
$('#tr2').append($('#tr1').html());
$('#tr1').html('');
}
}
}
);
});
Corresponding php function :
function change_statut(){
global $db;
$id_client_statut = $_POST['id_client'];
$query=$db->prepare(" UPDATE alarme INNER JOIN client_alarme ON client_alarme.id_alarme = alarme.id_alarme
INNER JOIN client on client.id_client=client_alarme.id_client
SET id_statut = 2
WHERE client.id_client= :id_client");
$query->bindValue(':id_client', $id_client_statut, PDO::PARAM_INT);
$query->execute();
$click_result = $query->fetch(PDO::FETCH_ASSOC);
return ($click_result);
}
My php function to distinguish :
if (isset($_POST['cmd'])){
if ($_POST['cmd'] == 'id_client_statut') {
change_statut();
}
else if ($_POST['cmd'] == 'id_client') {
read();
}
}
I don't really see why the first button would call the wrong function, but there is a problem with the way you setup the button events: via the onclick you are just binding the event handlers.
In function d_info() you currently just tell what should happen when the button .info is clicked. Idem for function change_statut().
So currently you have to click the buttons twice. First to bind the event and again to trigger the event (the second time it will also rebind the event).
You should get rid of the onclick attributes and bind the button events via the document ready event.
$( document ).ready(function() {
$(".switch").click(function () {
//...
});
$(".info").click(function () {
//...
});
});
In your Request you write :
$(".info").click(function () {
var datas = {
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: {cmd :' id_client', datas},
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
But the line data: {cmd :' id_client', datas}, gives you a new object witch is :
data: {
cmd :' id_client',
datas: {
id_client: $(this).attr('data-id'),
}
},
Now you can easily understand why your php gives you an error while reading $id_client = $_GET['id_client']; **(error showed)** as the real path to your value is $id_client = $_GET['datas']['id_client'];
But why using this kind of syntax while you have create datas in order to prepare ajax data object ?
The simpliest way to correct the error is to replace all object argument in the datas :
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
Hope it's helpfull ;)
Happy coding
I have a from inside of a while loop. I am processing it with ajax. Its working only on the first from and not on the other results. Please have a look.
<?php while($a = $stmt->fetch()){ ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $mbs_id; ?>" class="memid">
<select class="validity" class="upgrade-valsel">
<?php while($mv = $mval->fetch()){ extract($mv); ?>
<option value="<?php echo $mv_id; ?>"><?php echo $mv_validity; if($mv_validity == 1){ echo " month"; }else{ echo " months"; } ?></option>
<?php } ?>
</select>
<input type="submit" value="Upgrade" class="submit">
<div class="center-align" style="margin-left: -20px"><img src="images/loading.gif" width="auto" id="loading-rent" style="margin-right: 0px; height: 40px"></div>
</form>
<?php } ?>
When I click on submit button on the first result it process the result. But when I click on other buttons then its just refreshing the page. I tried replacing all the IDs with CLASS but after that not even the 1st one is working. Please help me.
Script
$(document).ready(function() {
$(".submit").click(function() {
var dataString = {
memid: $(".memid").val(),
validity: $(".validity").val()
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to upgrade your membership to <?php echo $mbs_name; ?>?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "upgrade-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$("#submit").show();
$("#loading-rent").hide();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Upgrade Cancelled!</span>');
}
}
});
return false;
});
});
As #Alive to Die and Jeff try to explain it, you use selector which returns several objects so when you use a function on this set of objects, jquery only use the first object of this set.
You have to use "this" to work on the context :
$(".submit").click(function(e) {
e.preventDefault();
// $(this) : your input with class .submit (the one you click)
// parent() : the parent of $(this) (the form)
// and then find the child with the unique class you want
var dataString = {
memid: $(this).parent().find(".memid").val(),
validity: $(this).parent().find(".validity").val()
};
// EDIT: Get the loading image (you should use a class instead of this selector)
var loader = $(this).parent().find("> div");
// After you can use loader in this function and all sub functions
loader.hide();
// And then the rest of your code with the same logic...
});
Pay attention each function has a different $(this) linked to its execution context.
Use preventDefault() to prevent the page from refreshing when you click the submit button. Use this to get the current form's values. Change your dataString to use this to get the values of the current form.
$(document).ready(function() {
$(".submit").click(function(e) {
e.preventDefault();
var dataString = {
memid: $(this).parent().find(".memid").val(),
validity: $(this).parent().find(".validity").val()
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to upgrade your membership to <?php echo $mbs_name; ?>?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "upgrade-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$("#submit").show();
$("#loading-rent").hide();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Upgrade Cancelled!</span>');
}
}
});
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'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);
}
});
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
}