jquery ajax success php while - javascript

why do everytime i success ajax request, the output will execute for each of my php while? i just want one of them which has uniq id_cart execute.
HTML :
<ul>
<?php while { ?>
<li class="changeweight">
<form>
<select name="changeq" class="<?php echo $datacart['id_cart']; ?>">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</li>
<?php } ?>
</ul>
AJax :
$("select[name=changeq]").change(function() {
var selectq = $(this).val();
var selectidcart = $(this).attr("class");
$.ajax({
context : this,
type : "GET",
url : "ajax/changequantity.php",
dataType : "json",
data : {idcart : selectidcart, q : selectq},
success : function(changeq) {
$("li.changeweight").hide().html(changeq.totalweight).fadeIn('slow');
}
});
});
changequantity.php :
<?php
$q = $_GET['q'];
$idcart = $_GET['idcart'];
mysqli_query($connect,"UPDATE cart SET quantity = '$q' WHERE id_cart = '$idcart'");
$cart = mysqli_query($connect,"SELECT * FROM cart WHERE id_cart = '$idcart'");
$datacart = mysqli_fetch_assoc($cart);
$product = mysqli_query($connect,"SELECT * FROM product WHERE id_product = '$datacart[id_product]'");
$dataproduct = mysqli_fetch_assoc($product);
$totalweight = $datacart['quantity'] * $dataproduct['weight'];
echo json_encode(array("totalweight" => $totalweight));
?>
everything works good, the data store on my database, but the problem was
ajax success will do for every php while li.changeweight.
what's wrong here?
thanks you so much.

Hello try to work with current object and get it's parents
$("select[name=changeq]").change(function() {
var self = this;
var selectq = $(this).val();
var selectidcart = $(this).attr("class");
$.ajax({
context : this,
type : "GET",
url : "ajax/changequantity.php",
dataType : "json",
data : {idcart : selectidcart, q : selectq},
success : function(changeq) {
$(self).parent().parent().hide().html(changeq.totalweight).fadeIn('slow');
}
});
});

Related

How i pass the dropdown value to ajax controller?

This is my dropdown box:
I am sending drop down value to ajax controller function to get some value.But the value is not passed correctly and i can't find the error;
My ajax code:
<script type="text/javascript">
$(function() {
$('.states').change(function(){
$id = $('.states').val();
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{id:$(this).val()},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>
My controller code;
public function Fetch_Item(){
$name = $this->input->post('id');
$result = $this->db->query("SELECT * FROM acc_master WHERE accName = '$name'")->row();
echo json_encode($result);
}
Front drop down box :
<div id="item3">
Party Name Selection:
<select multiple="multiple" style="width:400px;height:205px;" name="PName"id="Name" class="form-control states">
<option value=""></option>
</select>
<?php echo form_error('Area', '<div class="text-danger">', '</div>'); ?><br><br><br></div>
Dropdown ajax code:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "<?php echo base_url();?>Reports/get_countries1",
data:{id:$(this).val()},
beforeSend :function(){
$('.states').find("option:eq(0)").html("Please wait..");
},
success: function (data) {
$('.states').find("option:eq(0)").html("");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.states').append(option);
});
}});
});
</script>
Can you try this
<script type="text/javascript">
$(function() {
$('.states').change(function(){
var id = this.value;
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{'id':id,},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>
The $(this).val() returns an array, you have to change your backend code to handle the array.
Something like below.
public function Fetch_Item(){
$name = implode(",", $this->input->post('id'));
$result = $this->db->query("SELECT * FROM acc_master WHERE accName in ('$name')")->rows();
echo json_encode($result);
}
Note: Fetch_Item methon sql will return multiple results so you have to handle this as well.

Insert to mysql with PHP and AJAX not working

I try to make a form for updating status (select) with AJAX. What I have is:
HTML + JS:
<select id="Bname">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript">
var sel = document.getElementById('Bname');
sel.addEventListener("change", myFunction);
function myFunction() {
jQuery.ajax({
url : "insert.php",
type : "post",
contentType : 'application/json',
dataType : 'json',
data : {
stat : sel.value
}
})
.done(function() {
console.warn('ok!');
})
.fail(function() {
console.warn('error');
});
console.log(sel.value);
}
</script>
In insert.php file I have:
<?php
defined('_JEXEC') or die;
$stat = $_POST["stat"];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$fields = array(
$db->quoteName('cars') . ' = ' . $db->quote($stat)
);
$conditions = array(
$db->quoteName('id') . ' = 1'
);
$query->update($db->quoteName('#__cars'))->set($fields)->where($conditions);
$db->setQuery($query);
$result = $db->execute();
?>
Question is – why PHP file is not inserting? Any kind of script in insert.php isn't working. It's made with Joomla.
Thanks guys!
You need to first import the joomla libraries if you are calling ajax with single file.

php dopdown filter is not working

This is product filter page. I want to filter data by drop down. by php and mysqli database. I fetch data from database and put in dropdown. But it is not filtering after selecting value. trying from long time. did all possible way. please help me out in this code thank you.
var colour,brand,size,achievements ;
$(function(){
$('.item_filter').click(function(){
$('.product-data').html('<div id="loaderpro" style="" ></div>');
colour = multiple_values('colour');
brand = multiple_values('brand');
size = multiple_values('size');
achievements = multiple_values('achievements');
$.ajax({
url:"ajax.php",
type:'post',
data:{colour:colour,brand:brand,size:size,achievements:achievements,sprice:$(".price1" ).val(),eprice:$( ".price2" ).val()},
success:function(result){
$('.product-data').html(result);
}
});
});
});
function multiple_values(inputclass){
var val = new Array();
$("."+inputclass+":checked").each(function() {
val.push($(this).val());
});
return val;
}
<div class="list-group">
<select>
<option class="item_filter" value="showAll" selected="selected">Show All Products</option>
<?php
$query = "select your_achievements from info_user where user_status = '1'";
$rs = mysqli_query($con,$query) or die("Error : ".mysqli_error());
while($achievementsdata = mysqli_fetch_assoc($rs))
{
?>
<option selected="selected" class="item_filter" value="<?php echo $achievementsdata['your_achievements']; ?>"><?php echo $achievementsdata['your_achievements']; ?></option>
<?php
}
?>
</select>
</div>
try to use onchange event like this
$('select').on('change', function() {
alert( this.value );
})
and your data variable should be like this
data:{'colour':colour,'brand':brand,'size':size,'achievements':achievements,'sprice':$(".price1" ).val(),'eprice':$( ".price2" ).val()},
make sure your all variable's value are exist.
your ajax code should be like this
$(function(){
$('select').on('change', function() {
$('.product-data').html('<div id="loaderpro" style="" ></div>');
colour = multiple_values('colour');
brand = multiple_values('brand');
size = multiple_values('size');
achievements = multiple_values('achievements');
$.ajax({
url:"ajax.php",
type:'post',
data:{'colour':colour,'brand':brand,'size':size,'achievements':achievements,'sprice':$(".price1" ).val(),'eprice':$( ".price2" ).val()},
success:function(result){
$('.product-data').html(result);
}
});
});
});

How to populate a dropdown with AJAX

I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js

jquery Ajax POST posted but not received?

I am completely confused:
This is my php script "add_credits.php". It runs perfectly if I create a form and call it via method="post".
$stmt = "UPDATE sites SET credits=:credits WHERE id=:id";
$stmt = $db->prepare($stmt);
$stmt ->execute( array( ":credits" => $_POST['cred'], ":id" => $_POST['id'] ) );
This is my input field that triggers the jquery/ajax.
<input id="<?php echo $row['id']; ?>" type="text" class="credits" value="<?php echo $row['credits']; ?>" />
This is my jquery, which will echo eitther variable in an alert box correctly on success.
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = 'id=' + add_id;
var add_cred = $(this).attr("value");
var info2 = 'cred=' + add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {info:info, info2:info2},
success : function() {
alert(info2);
}
});
return true;
});
So why is it that its reporting success, yet no UPDATE is being performed, as if the php is not receiving the $_POST details? Am I missing something??
You don't have to manually serialize the data like that
$('.credits').on('input', function() {
var req = $.post('add_credits.php', {
info: $(this).attr('id'),
info2: $(this).attr('value')
});
req.done(function(res) {
console.log(res);
});
req.fail(function(err) {
console.error(err);
});
});
On the PHP side of things, make sure you're reading info and info2
// info and info2 were set in the POST request in the jQuery above
$info = $_POST['info'];
$info2 = $_POST['info2'];
do_something($info, $info2);
// respond in some way
header('content-type: application/json');
echo json_encode(['ok'=> true]);
You can name the fields id and cred if that's what you wish. That would change the jQuery data to this
var req = $.post('url', {
id: $(this).attr('id'),
cred: $(this).attr('value')
});
Then make sure you read $_POST['id'] and $_POST['cred'] in the PHP
Use the following jquery code:
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = add_id;
var add_cred = $(this).attr("value");
var info2 = add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {id:info, cred:info2},
success : function() {
alert(info2);
}
});
return true;
});

Categories

Resources