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
Related
I am now working in a POS System. My goal is, as the input is getting updated by the "keyup", the results that match this keyup show in a table.
Something like this:
Example
I think I have the code completed, just missing to echo the results in a table. This is my actual JS code:
$(document).ready(function(){
$("tablaClientesEnVenta").dataTable({
bFilter: false, bInfo: false
});
$("#inputNombreCliente").on('keyup', function(){
$("#tablaClientesEnVenta").css("visibility", "visible");
if (!$("#inputNombreCliente").val()){
$("#tablaClientesEnVenta").css("visibility", "hidden");
}
console.log("tecla detectada");
var nombreCliente = $(this).val();
console.log(nombreCliente);
var datos = new FormData();
datos.append("nombreCliente", nombreCliente);
$.ajax({
url:'ajax/crear-venta.ajax.php',
method: "POST",
data: datos,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success:function(respuesta){
console.log(respuesta);
}
});
});
});
This is my AJAX Code to call the function:
<?php
require_once '../controladores/clientes.controlador.php';
require_once '../modelos/clientes.modelo.php';
class AjaxVentas{
public $nombreCliente;
public function ajaxNombreCliente(){
$item = "nombre";
$valor = $this->nombreCliente;
$respuesta = ControladorClientes::ctrMostrarAjaxClientes($item,
$valor);
echo json_encode($respuesta);
}
}
if (isset($_POST['nombreCliente'])) {
$cliente = new AjaxVentas();
$cliente -> nombreCliente = $_POST['nombreCliente'];
$cliente -> ajaxNombreCliente();
}
This is the function that calls out for the model:
static public function ctrMostrarAjaxClientes($item, $valor){
$tabla = "clientes";
$respuesta = ModeloClientes::mdlMostrarAjaxClientes($tabla, $item,
$valor);
return $respuesta;
}
Finally, the function that calls out the data from the DB:
static public function mdlMostrarAjaxClientes($tabla, $item, $valor){
$statement = Conexion::conectar()->prepare("SELECT * FROM $tabla
WHERE $item = :item");
$statement->execute(array(":item" => $valor));
return $statement->fetchAll();
}
As a conclusion, I would like to know what I am missing, since the console.log(respuesta) in the JS is giving me an error. Thank you and have a nice day!
In your AjaxVentas class;
ControladorClientes::mdlMostrarAjaxClientes($item, $valor);
The static method requires 3 arguments ($table, $item, $valor) not two($item, $valor) being passed above
Edited
Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :item");
Table name is not being passed
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;
});
});
I have an editable table in my view.. At first, there's no data in the table but the user can add data in the table since it is editable. And there's no exact number of rows in the table since I have also a button that can add new row. I want to get the data that the user have added and save it in the database.
I have this code:
VIEW:
<table class="table " id="memberTB">
<thead><tr><th >First Name</th><th >Middle Name</th><th>Last Name</th></tr></thead>
<tbody>
<tr id="first"><td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td></tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow"><span class="fa fa-plus"> Add new row</span></button>
</table>
<br><button type="button" class="btn" id="savebtn">Save</button> Reset
JS:
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.showbuttons = false;
$.fn.editable.defaults.url = '/post';
$.fn.editable.defaults.type = 'text';
// make all items having class 'edit' editable
$('.edit').editable();
// this is to automatically make the next item in the table editable
$('.edit').on('save', function(e, params){
var that = this;
// persist the old value in the element to be restored when clicking reset
var oldItemValue = $(that)[0].innerHTML;
if (!$(that).attr('oldValue')) {
console.log('persisting original value: ' + oldItemValue)
$(that).attr('oldValue', oldItemValue);
}
setTimeout(function() {
// first search the row
var item = $(that).closest('td').next().find('.edit');
console.log(item);
if (item.length == 0) {
// check the next row
item = $(that).closest('tr').next().find('.edit');
}
item.editable('show');
}, 200);
});
$('#resetbtn').click(function() {
$('.edit').each(function() {
var o = $(this);
o.editable('setValue', o.attr('oldValue')) //clear values
.editable('option', 'pk', o.attr('pk')) //clear pk
.removeClass('editable-unsaved')
.removeAttr('oldValue');
});
});
$('#savebtn').click(function() {
var person = [];
var x=1;
$('tbody tr',$('#memberTB')).each(function(){
for(var i = 0 ; i < cells ; i++)
{
person[x][i]=$(this).find('td').eq(i).text();
}
x++;
});
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: { values: arraylng },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
});
$('#addrow').click(function() {
$('#memberTB > tbody:last').append(' <tr><td><span class="edit"></span></td><td><span class="edit"></span></td><td><span class="edit"></span></td></tr>');
$('.edit').editable();
});
Controller: [inside the test.php]
public function saveData(){
$this->load->model('test_model');
$myArray = $_REQUEST['values'];
echo sizeof($myArray);
}
Whenever I click the save button, there's no response at all.. Where did I go wrong? please help me..
ADDED INFO:
I didn't include my SQL insert statement here because I want to test first if there's data in $myArray if I added data in the table.
Better use this ajax
var arraylng = [3,4,7];
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: {values: JSON.stringify(arraylng)},
cache: false,
success: function (response) {
alert(response);
}
});
arraylng is an array, which doesn't exist in the code. I added it here for debugging.
Suppose you want to send person[] array, you write, data: {values: JSON.stringify(person)}.
Now, the person array may not exist, because of the "i < cells" in for. What is cells?
The word response is just a name, any name, but better avoid 'data'.
In test.php, what is sizeof($myArray)? Just, echo $myArray;
When you click save you must get the $myArray content in an alert.
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
}