i have products on my website and i made ajax call to insert product to shopping cart, but there is problem with clicking button. when i click on first product in list everything works but other product buttons do not react
<?php foreach ($products as $product):?>
<?php if($product['kateg'] == "men"):?>
<h5 style="color: #0669b4; min-height: 70px;"><?php echo $product['dasax']?></h5>
<p style="text-align: left; text-decoration: overline">Old price: <strong><span style="text-decoration: line-through"><?php echo round($product['fasi1'], 2)?> GEL</span></strong><br></p>
<p style="text-align: left">New Price: <strong><?php echo round($product['fasi2'], 2)?> GEL</strong><br></p>
<input type="hidden" value="<?php echo $product['id']?>" id="product_id">
<input type="hidden" value="<?php echo $product['dasax']?>" id="product_name">
<input type="hidden" value="<?php echo $product['fasi2']?>" id="product_price">
</a>
<button class="btn btn-primary" type="submit" id="add_to_cart">Add</button>
<?php endif;?>
<?php endforeach;?>
<script>
$(document).ready(function () {
$('#add_to_cart').click(function () {
var product_id = $("#product_id").val();
var product_name = $("#product_name").val();
var product_price = $("#product_price").val();
$.ajax({
url: "/uketesi/index",
method: "POST",
dataType: "json",
data: {
product_id:product_id,
product_name:product_name,
product_price:product_price,
},
success:function (data) {
alert("produqti warmatebit daemata")
$("#კალათა").html("<table id=\"example2\" class=\"table table-bordered table-hover\">" +
"<thead>" +
"<tr>" +
"<th>დასახელება</th>" +
"<th>ფასი</th>" +
"<th>იდენტიფიკატორი</th>" +
"</tr>" +
"<tr>" +
"<td>" + product_name + "</td>" +
"<td>" + product_price + "</td>" +
"<td>" + product_id + "</td>" +
"</tr>" +
"</thead>" +
"</table>");
}
});
});
});
</script>
I figured out how to solve the problem above, i have another question how can i add multiple products with this code. for now i only can add one product when i click on another product the old one dissepears.
You can get the data from data-*="" attribute on the button. So no need hidden inputs. For the click event you should use class name. Other case ID wont be unique. Please try following code.
<?php foreach ($products as $product):?>
<?php if($product['kateg'] == "men"):?>
<h5 style="color: #0669b4; min-height: 70px;"><?php echo $product['dasax']?></h5>
<p style="text-align: left; text-decoration: overline">Old price: <strong><span style="text-decoration: line-through"><?php echo round($product['fasi1'], 2)?> GEL</span></strong><br></p>
<p style="text-align: left">New Price: <strong><?php echo round($product['fasi2'], 2)?> GEL</strong><br></p>
</a>
<button class="btn btn-primary" type="submit" class="add_to_cart" data-id="<?php echo $product['id']?>" data-name="<?php echo $product['dasax']?>" data-price="<?php echo $product['fasi2']?>">Add</button>
<?php endif;?>
<?php endforeach;?>
<script>
$(document).ready(function () {
$('.add_to_cart').click(function () {
var product_id = $(this).data('id');
var product_name = $(this).data('name');
var product_price = $(this).data('price');
$.ajax({
url: "/uketesi/index",
method: "POST",
dataType: "json",
data: {
product_id:product_id,
product_name:product_name,
product_price:product_price,
},
success:function (data) {
}
});
});
});
</script>
Now that we have the form, and jQuery included in our document, we need to store it’s values in 2 variables, ( val1 and val2 ) so then we can pass it to the PHP file to process it.
$('#button').click(function() {
var val1 = $('#text1').val();
var val2 = $('#text2').val();
$.ajax({
type: 'POST',
url: 'process.php',
data: { text1: val1, text2: val2 },
success: function(response) {
$('#result').html(response);
}
});
});
As you can see in the code above, we create a .click event. This means that when the button with the ID of #button is click, out function will run. Then we get the value of each text field and store it in val1 and val2.
Related
I have the following php code:
<tr>
<td class="vacancyID">
<?php echo $vacancyID; ?>
</td>
<td class="roleLongTitle">
<?php echo $roleLongTitle; ?>
</td>
<td class="roleRequirements">
<?php echo $roleRequirements; ?>
</td>
<td class="roleResponsibilities">
<?php echo $roleResponsibilities; ?>
</td>
<td class="roleQualifications">
<?php echo $roleQualifications; ?>
</td>
<td class="closeDate">
<?php
//Convert the mySQL date to PHP date
echo convertToDate($closeDate);
?>
</td>
<td>
And the following jquery code:
$(document).ready(function(){
var btn = $('a.btn-primary');
var closeDate = $('td.closeDate');
var applyBtn = $('<input type="button" value=" Apply " class="toggleButton" />');
//var applyLnk = $('Apply');
//Rmove a link
btn.remove();
//Add button
applyBtn.insertAfter(closeDate);
//applyBtn.appendTo(closeDate);
//applyLnk.insertAfter(closeDate);
$('.toggleButton').click(function(){
var obj = $(this).closest('tr');
var data = {
vacancyID: obj.find('td.vacancyID').text(),
closeDate: obj.find('td.closeDate').text(),
roleLongTitle: obj.find('td.roleLongTitle').text(),
roleRequirements: obj.find('td.roleRequirements').text(),
roleResponsibilities: obj.find('td.roleResponsibilities').text(),
roleQualifications: obj.find('td.roleQualifications').text(),
}
//Post the data to the page
$.ajax({
type: 'POST',
url: 'vacancy.php',
data: data,
success: function(data){
window.location.assign("applyForVacancy.php");
}
});
//console.log(data);
});
});
Is there any way for me to make this better? I have tried many option and this one is the only one that's working and that can get access to those posted values based on the button I clicked.
I am new to codeigniter and ajax. I can add item to cart and remove it as well. but when i am trying to update the quantity of the first row it works fine. but if i change the quantity of other rows and when i leave the mouse it updates the price * quanity, but it wont take the quantity what we enterd instead it takes the value of the first row quantity. can anyone please help me out.
view file :
<html>
<head>
<title>Codeigniter Shopping Cart with Ajax JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br /><br />
<div class="col-lg-6 col-md-6">
<div class="table-responsive">
<h3 align="center">Codeigniter Shopping Cart with Ajax JQuery</h3><br />
<?php
foreach($product as $row)
{
echo '
<div class="col-md-4" style="padding:16px; background-color:#f1f1f1; border:1px solid #ccc; margin-bottom:16px; height:400px" align="center">
<img src="'.base_url().'images/'.$row->product_image.'" class="img-thumbnail" /><br />
<h4>'.$row->product_name.'</h4>
<h3 class="text-danger">$'.$row->product_price.'</h3>
<input type="text" name="quantity" class="form-control quantity" id="'.$row->product_id.'" /><br />
<button type="button" name="add_cart" class="btn btn-success add_cart" data-productname="'.$row->product_name.'" data-price="'.$row->product_price.'" data-productid="'.$row->product_id.'" />Add to Cart</button>
</div>
';
}
?>
</div>
</div>
<div class="col-lg-6 col-md-6">
<div id="cart_details">
<h3 align="center">Cart is Empty</h3>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.add_cart').click(function(){
var product_id = $(this).data("productid");
var product_name = $(this).data("productname");
var product_price = $(this).data("price");
var quantity = $('#' + product_id).val();
if(quantity != '' && quantity > 0)
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/add",
method:"POST",
data:{product_id:product_id, product_name:product_name, product_price:product_price, quantity:quantity},
success:function(data)
{
alert("Product Added into Cart");
$('#cart_details').html(data);
$('#' + product_id).val('');
}
});
}
else
{
alert("Please Enter quantity");
}
});
$('#cart_details').load("<?php echo base_url(); ?>shopping_cart/load");
// $(document).ready(function(){
// $("input").blur(function(e){
// e.preventDefault();
// }).blur(function() {
// alert("opo");
// });
// });
$(document).on('mouseleave', '#myqty', function(){
var rowid = $(this).attr("class");
var product_price = $(this).attr("title");
//var proqty = $('#myqty').val();
var fieldId = $(this).attr("class");
var proqty = $('#myqty').val();
alert(proqty);
$.ajax({
url:"<?php echo base_url();?>shopping_cart/update",
method:"POST",
data : {rowid:rowid,proqty:proqty,product_price:product_price},
//data: "rowid="+rowid+"&proqty="+proqty+"&product_price="+product_price,
success:function(data)
{
$('#cart_details').html(data);
}
});
});
$(document).on('click', '.remove_inventory', function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to remove this?"))
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/remove",
method:"POST",
data:{row_id:row_id},
success:function(data)
{
alert("Product removed from Cart");
$('#cart_details').html(data);
}
});
}
else
{
return false;
}
});
$(document).on('click', '#clear_cart', function(){
if(confirm("Are you sure you want to clear cart?"))
{
$.ajax({
url:"<?php echo base_url(); ?>shopping_cart/clear",
success:function(data)
{
alert("Your cart has been clear...");
$('#cart_details').html(data);
}
});
}
else
{
return false;
}
});
});
</script>
controller file :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Shopping_cart extends CI_Controller {
function index()
{
$this->load->model("shopping_cart_model");
$data["product"] = $this->shopping_cart_model->fetch_all();
$this->load->view("shopping_cart", $data);
}
function add()
{
$this->load->library("cart");
$data = array(
"id" => $_POST["product_id"],
"name" => $_POST["product_name"],
"qty" => $_POST["quantity"],
"price" => $_POST["product_price"]
);
$this->cart->insert($data); //return rowid
echo $this->view();
}
function load()
{
echo $this->view();
}
function remove()
{
$this->load->library("cart");
$row_id = $_POST["row_id"];
$data = array(
'rowid' => $row_id,
'qty' => 0
);
$this->cart->update($data);
echo $this->view();
}
function clear()
{
$this->load->library("cart");
$this->cart->destroy();
echo $this->view();
}
function view()
{
$this->load->library("cart");
$output = '';
$output .= '
<h3>Shopping Cart</h3><br />
';
echo count($this->cart->contents());
$output .= '
<div class="table-responsive">
<div align="right">
<button type="button" id="clear_cart" class="btn btn-warning">Clear Cart</button>
</div>
<br />
<table class="table table-bordered">
<tr>
<th width="40%">Name</th>
<th width="15%">Quantity</th>
<th width="15%">Price</th>
<th width="15%">Total</th>
<th width="15%">Action</th>
</tr>
';
$count = 0;
foreach($this->cart->contents() as $items)
{
$count++;
$output .= '
<tr>
<td>'.$items["name"].'</td>
<td><input id="myqty" title="'.$items["price"].'" class="'.$items['rowid'].'" type="number" min="1" value="'.$items['qty'].'">
</td>
<td><span id='.$items["price"].'>'.$items["price"].'</span></td>
<td>'.$items["subtotal"].'</td>
<td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'">Remove</button></td>
</tr>
';
}
$output .= '
<tr>
<td colspan="4" align="right">Total</td>
<td><span>'.$this->cart->total().'</span></td>
</tr>
</table>
</div>
';
if($count == 0)
{
$output = '<h3 align="center">Cart is Empty</h3>';
}
return $output;
}
function update(){
$this->load->library("cart");
// Recieve post values,calcute them and update
$rowid = $_POST['rowid'];
$price = $_POST['product_price'];
$qty = $_POST['proqty'];
$data = array(
'rowid' => $rowid,
'price' => $price,
'qty' => $qty
);
$this->cart->update($data);
echo $this->view();
}
}
<input class="qty_set" name="quantity" data-rowid="your rowid" type="number" value="5">
this will not work "quantity = document.getElementById ("qty_set"). value;"
// use this var quantity = $(this).val();
$(document).on('change', '.qty_set', function(){
var quantity = $(this).val();
var row_id = $(this).data("rowid");
$.ajax({
url:"<?php echo base_url(); ?>Sepet/setliste",
method:"POST",
data:{row_id:row_id, quantity:quantity},
success:function(data)
{
//alert("Güncellendi");
$('#sepetload').html(data);
}
});
I have a list of users in my table. At first run it will load using the data from my controller. And I have a remove button function in every row. And then in my remove button I have an ajax load AFTER the successful removal of the user. Now I load the data using ajax. But the problem is the same functionality I have at first wont work anymore. I don't know why.
Here's my code:
Initial load of user from my controller
<table class="table table-bordered table-striped table-hover" id="user-group-list">
<thead>
<tr>
<th></th>
<th>Group Name</th>
<th>Description</th>
<th class="text-center">
<span class="fa fa-plus"></span>
<button class="btn ink-reaction btn-raised btn-danger btn-sm"><span class="fa fa-trash-o"></span></button>
</th>
</tr>
</thead>
<tbody>
<?php if($user_groups) { ?>
<?php foreach($user_groups as $g) { ?>
<tr>
<td class="text-center">
<input type="checkbox" name="group_id[]" value="<?php echo $g['id']; ?>" />
</td>
<td>
<label><?php echo $g['name']; ?></label>
</td>
<td>
<label><?php echo $g['definition']; ?></label>
</td>
<td class="text-center">
<a class="btn btn-icon-toggle btn-primary edit_group" data-id="<?php echo $g['id']; ?>"><i class="fa fa-pencil"></i></a>
<?php if($g['id'] > 2) { ?>
<a class="btn btn-icon-toggle btn-danger remove_group" data-id="<?php echo $g['id']; ?>" data-name="<?php echo $g['name']; ?>"><i class="fa fa-trash-o"></i></a>
<?php } ?>
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td colspan="4" class="text-center">
<p>There are no user group set</p>
</td>
</tr>
<?php } ?>
</tbody>
</table>
Then in my JS
$('.remove_group').on('click', function(e) {
e.preventDefault();
var group_id = $(this).data('id');
var name = $(this).data('name');
alert(group_id); //wont work anymore after ajax load
bootbox.dialog({
message: "Are you sure you want to remove the group <span class='text-danger'>" + name.toUpperCase() + "</span>",
title: "Notification",
buttons: {
success: {
label: "Yes, remove it",
className: "btn-info",
callback: function() {
$.ajax({
url: "<?php echo site_url('users/user/remove_user_group'); ?>",
data: {group_id: group_id},
dataType: 'json',
type: 'post',
beforeSend: function() {
console.log('Loading...');
},
success: function(d) {
loadUserGroup();
makeToast(d.status, d.toast_info);
},
error: function() {
alert('Error Found!');
}
});
}
},
danger: {
label: "Cancel",
className: "btn-default",
callback: function() {
$(this).modal('hide');
}
}
}
});
});
function loadUserGroup() {
$.ajax({
url: "<?php echo site_url('users/user/load_group_list'); ?>",
dataType: 'json',
beforeSend: function() {
var loader = "<tr>";
loader += " <td colspan='4' class='text-center'><span class='fa fa-spinner fa-pulse fa-3x'></span></td>";
loader += "</tr>";
$('#user-group-list tbody').empty();
$('#user-group-list tbody').html(loader);
},
success: function(data) {
$('#user-group-list tbody').empty();
var group_list = '';
$.each(data.user_groups, function(k, v){
group_list += "<tr>";
group_list += " <td class='text-center'><input type='checkbox' /></td>";
group_list += " <td><label>" + v.name + "</label></td>";
group_list += " <td><label>" + v.definition + "</label></td>";
group_list += " <td class='text-center'>";
group_list += " <a class='btn btn-icon-toggle btn-primary edit_group' data-id='" + v.id + "'><span class='fa fa-pencil'></span></a>";
if(v.id > 2) {
group_list += " <a class='btn btn-icon-toggle btn-danger remove_group' data-id='" + v.id + "' data-name='" + v.name + "'><span class='fa fa-trash-o'></span></a>";
}
group_list += " </td>";
group_list += "</tr>";
//console.log(v.id);
});
$('#user-group-list tbody').html(group_list);
},
error: function() {
alert('Error Occured!');
}
});
}
My ajax load
public function load_group_list() {
$json['user_groups'] = array();
$groups = $this->aauth->get_all_groups();
if(count($groups) > 0) {
foreach($groups as $group) {
$json['user_groups'][] = array(
'id' => $group['id'],
'name' => $group['name'],
'definition' => $group['definition'],
'href' => site_url('users/user/user_group_info?group_id=' . $group['id'])
);
}
}
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json");
echo json_encode($json);
}
Hope the below function fails
$('.remove_group').on('click', function(e) {//your code}
Change that to the below code
$(document).on('click','.remove_group', function(e) {//your code}
It occur because you load the class dynamically and DOM can't identify the element any more
There is a div element :
...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
rechercheSecteursEtProduits(0); // setting the div's content
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
});
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html); // this is the div element
}
</script>
Code of ListerProduitsUserParSecteursAjax.php :
<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display " >
<thead style="background-color:#CCC">
<tr>
<th><?php echo _getText("service.produit.form.secteur_activite");?></th>
<th><?php echo _getText("service.produit.form.titre");?></th>
<th></th>
<th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
</tr>
</thead>
<tbody style="background-color:#FFF">
<?php
if($data["secteur"]["cnt"] > 0){
for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
<tr class="odd gradeX">
<td><?php echo $data["secteur"][$i]["secta_lib_fr"] ?></td>
<td><?php echo $data["secteur"][$i]["produit_lib"] ?></td>
<td align="center" style="vertical-align:middle"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></td>
<td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
</tr>
<?php } ?>
<?php
}
else{
?>
<tr class="odd gradeX">
<td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
</tr>
<?php }?>
</tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>" class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>
When the page loads for the first time then the delete button works fine : the selected rows are deleted , and the list reappears accordingly to new database data. But later when I want to delete other rows then the alert does not show when I check some checkboxes and clicking the delete button !
So what is wrong in my approach ?
From what I am reading you are having problems with the row that are added from the database.
What could be the problem is when you execute this peace of code:
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
When you call the $.click() function you add a event to all the existing DOM object that have a id of 'btnSupprimer', however this doesn't update if you add a new DOM object. So what you should do is call this function every time you add a new row. you would get something like this:
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').click(addClickHandler()); // this is the div element
}
function addClickHandler(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
}
I hope it helps
Try using on instead of click as below
$('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
Use the dynamic jquery selector instead of the regular 'click' event
$('#liste_secteurs').on('click', '#btnSupprimer', function() {});
// $("container").on("event", "button", function() {});
As from Caveman's answer I made some updates :
function rechercheSecteursEtProduits(pn) {
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_usermer="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').on('click',function(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
if (confirm("Do you want to remove these records ?")) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0);
}
}
});
}
And it works !
i am trying to send the variables to server but url does not go to the php file.. What am i doing wrong? Is it because i am not using a submit button? Here is my code..
<table id="table">
<?php for($i=0; $i<$totalbesin; $i++) { ?>
<tr>
<td class="td" id="<?php echo "name".$i?>"><?php echo $besin[$i]['n']?></td>
<td class="td" id="<?php echo "kal".$i?>"><?php echo $besin[$i]['kal']?></td>
<td class="td" id="<?php echo "pro".$i?>"><?php echo $besin[$i]['pro']?></td>
<td class="td" id="<?php echo "kar".$i?>"><?php echo $besin[$i]['kar']?></td>
<td class="td" id="<?php echo "yag".$i?>"><?php echo $besin[$i]['yag']?></td>
<td class="ekle" id="yuk<?php echo $i?>">Ekle</td>
</tr>
<script type="text/javascript" >
$(function() {
$("#yuk<?php echo $i?>").click(function()
{
var name = $("#<?php echo "name".$i?>").val();
var kal = $("#<?php echo "kal".$i?>").val();
var pro = $("#<?php echo "pro".$i?>").val();
var kar = $("#<?php echo "kar".$i?>").val();
var yag = $("#<?php echo "yag".$i?>").val();
var dataString = '&name='+ name + '&kal=' + kal + '&pro=' + pro + '&kar=' + kar + '&yag=' + yag;
$.ajax({
type: "POST",
url: "dietup.php",
data: dataString,
cache: false,
success: function(html){
$("span#sonuc").text("<?php echo $i?>");
}
});
return false;
}); });
</script>
<?php } ?>
</table>
you need to change the val() to text(); like below as"td" tags not having an value tag
var name = $("#<?php echo "name".$i?>").text();
var kal = $("#<?php echo "kal".$i?>").text();
var pro = $("#<?php echo "pro".$i?>").text();
var kar = $("#<?php echo "kar".$i?>").text();
var yag = $("#<?php echo "yag".$i?>").text();
Take a look at ajaxForm & ajaxSubmit, otherwise you need a submit button.
http://malsup.com/jquery/form/
Try this
$.ajax({
type: "POST",
url: "dietup.php",
data: {
name: name,
kal: kal,
pro: pro
//and so on
},
cache: false,
success: function(html){
$("span#sonuc").text("<?php echo $i?>");
}
});
Use this to set the value into your variables:
var name = $("#name<?php echo$i?>").val();
var kal = $("#kal<?php echo $i?>").val();
var pro = $("#pro<?php echo $i?>").val();
var kar = $("#kar<?php echo $i?>").val();
var yag = $("#yag<?php echo $i?>").val();
In your code, as I understand, it seems that you are trying to assign values to your javscript variables using php.
There is a problem with syntax where you are assigning the values to your javscript variables.
Notice the following snippet from your code below:
var name = $("#<?php echo "name".$i?>").val();
var kal = $("#<?php echo "kal".$i?>").val();
var pro = $("#<?php echo "pro".$i?>").val();
var kar = $("#<?php echo "kar".$i?>").val();
var yag = $("#<?php echo "yag".$i?>").val();
Does anything seems not right?
Gotcha!!!! You are using double quotes to assign value in to your jquery selector and as well as for the php echo statement which is terminating your double quote.
Try using single quotes for the jquery selector and double quotes for the php echo statement as follows:
var name = $('#<?php echo "name".$i?>').val();
First of all, ajax parameter data must be object, not url string. If you want to send string url, add url string to url like this:
$.ajax({
url: "dietup.php?&name='+ name + '&kal=' + kal + '&pro=' + pro + '&kar=' + kar + '&yag=' + yag;"
})
But it will be wrong approach
I have divided yours script into two logical components.
First: is php loop generates the html table
Second: javascript function, who's sending ajax request
<table id="table">
<?php for($i=0; $i<$totalbesin; $i++) { ?>
<tr rel="<?php echo $i ?>">
<td class="td name" id="<?php echo "name".$i?>"><?php echo $besin[$i]['n']?></td>
<td class="td kal" id="<?php echo "kal".$i?>"><?php echo $besin[$i]['kal']?></td>
<td class="td pro" id="<?php echo "pro".$i?>"><?php echo $besin[$i]['pro']?></td>
<td class="td kar" id="<?php echo "kar".$i?>"><?php echo $besin[$i]['kar']?></td>
<td class="td yag" id="<?php echo "yag".$i?>"><?php echo $besin[$i]['yag']?></td>
<td class="ekle" id="yuk<?php echo $i?>">Ekle</td>
</tr>
<?php } ?>
</table>
<script type="text/javascript" >
$(function() {
$(".ekle").click(function()
{
var parent = $(this).closest('tr');
var data = {
name: parent.find('.name').val(),
kal: parent.find('.kal').val(),
pro: parent.find('.pro').val(),
kar: parent.find('.kar').val(),
yag: parent.find('.yag').val()
};
$.ajax({
type: "POST",
url: "dietup.php",
data: data,
cache: false,
success: function(html){
$("span#sonuc").text(parent.attr('rel'));
}
});
return false;
});
});
</script>
I found the problem.. It is because it does not get data from td, i tried getelementById but it did not work either.. Then i used
var name = '<?php echo $besin[$i]['n']?>';
and put the data in var like this.. Now it works.. Thank you for your time.. It would be better if i could get the data from td but its ok for now.. :)
I have a similar script, hope this help you:
<script type="text/javascript">
$(function() {
$("#yuk<?php echo $i?>").click(function(event)
{
var name = $("#<?php echo "name".$i?>").text();
var kal = $("#<?php echo "kal".$i?>").text();
var pro = $("#<?php echo "pro".$i?>").text();
var kar = $("#<?php echo "kar".$i?>").text();
var yag = $("#<?php echo "yag".$i?>").text();
var dataString = 'name='+ name + '&kal=' + kal + '&pro=' + pro + '&kar=' + kar + '&yag=' + yag;
//Uncomment to check the querystring
//alert("dietup.php?"+dataString);
$.ajax({
url:"dietup.php?"+dataString,
type:'GET',
dataType:'text',
cache:false,
success:function(data){
alert (data);
},
error:function(jxhr){
alert('Ops, error: '.jxhr.responseText);
}
}); //End Ajax
}); //End Click Function
}); //End Root Function
And here is the dietup.php example:
<?
//Get the parameters
$name = $_GET['name'];
//Do and return what you need
echo "your name is: ". $name;
?>