In the below code I have a dropdown (id-name) which populated from listplace.php'. Also made another ajax call which when the dropdown item is selected it lists the specific product fromdataprod.php`
Problem: when I click on the specific item from drop-down it does not trigger the Ajax event
I checked the dataprod.php it works correctly, but even after binding the change event with my dropdown box I m not getting the result. Please help..
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<script>
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
</script>
<?php } ?>
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
You need to pass the selected value in the ajax call.
change this line from
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
to
var name1 = this.value;
$.ajax ({
data: {name1: name1},
type: 'POST',
HTML:
you can store the values in hidden field like:
<input type='hidden' name='name1' id='name1' value='<?= $_GET["name1"] ?>'>
Javascript:
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = $('#name1').val();
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
Related
I am trying to get country states but it returns null
here is my code
the adding form
<select class="form-control" id="country-dropdown">
<option value="">Select Country</option>
<?php
$countries = get_rows('tbl_countries');
foreach($countries as $country):
echo '<option value='.$country['id'].'>'.$country['name'].'</option>';
endforeach;
?>
</select>
<select name="state" class="form-control" id="state-dropdown" required="required">
</select>
<select name="city" class="form-control" id="city-dropdown" required="required">
</select>
Ajax Code
to get country states
<script>
$(document).ready(function() {
$('#country-dropdown').on('change', function() {
var country_id = this.value;
$.ajax({
url: "getStates.php",
type: "GET",
data: {
country_id: country_id
},
cache: false,
success: function(result){
$("#state-dropdown").html(result);
$('#city-dropdown').html('<option value="">Select State First</option>');
console.log("this is "+ result);
}
});
});
$('#state-dropdown').on('change', function() {
var state_id = this.value;
$.ajax({
url: "getCities.php",
type: "GET",
data: {
state_id: state_id
},
cache: false,
success: function(result){
$("#city-dropdown").html(result);
}
});
});
});
</script>
code in getStates file
<?php
//connect file
include "../init.php";
$country_id = $_GET['country_id'];
$stmt = $con->prepare("SELECT * FROM tbl_states WHERE country_id = ?");
$stmt->execute(array($country_id));
$rows = $stmt->fetchAll();
foreach($rows as $row){
echo '<option value='.$row['id'].'>'.$row['name'].'</option>';
}
The result is null
if I remove the country_id condition it returns all states not the choosen country states
wheres the problem with my code
I have a codeigniter website, where I have done an add to cart function, on button click the product is added to cart after page reloads which is working fine, I did the following code in controller:
public function buy($id)
{
$color= $this->input->post('color');
$size=$this->input->post('size');
$product = $this->product->find($id);
$item = array(
'id' => $product->id,
'name' => $product->pname,
'quantity' => 1
);
if(!$this->session->has_userdata('cart')) {
$cart = array($item);
$this->session->set_userdata('cart', serialize($cart));
} else {
$index = $this->exists($id);
$cart = array_values(unserialize($this->session->userdata('cart')));
if($index == -1) {
array_push($cart, $item);
$this->session->set_userdata('cart', serialize($cart));
} else {
// $cart[$index]['quantity']++;
// $this->session->set_userdata('cart', serialize($cart));
$this->session->set_flashdata("Error","Product Already In Cart !");
redirect($_SERVER['HTTP_REFERER']);
}
}
$this->session->set_flashdata("Success","Product Added To Cart Successfully !");
redirect($_SERVER['HTTP_REFERER']);
}
Now I am trying to call this function using ajax so that the product is added to cart without page reload. I did the following code:
$("#change").submit(function() {
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
<form action="" method="post" id="change">
<input type="hidden" value="<?php echo $product->id; ?>" id="prod">
<input type="submit" value="switch">
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
However it's not adding to cart, it simply reloads the page. Can anyone please tell me what is wrong in here?
Because the form is still submitting, you can use preventDefault();
$("#change").submit(function(e) {
e.preventDefault();
alert("Change");
var id = $('#prod').val();
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "index.php/homecontroller/buy/" + id,
data: {
'id': id
},
success: function(data) {
$('#resultdiv').html(data);
}
});
});
I've got multiple select boxes that have the same name. Right now when I select the value from the first select box its submitting that one and updating the database. When I select and item on an other select box its submitting the value from the first one. I feel like the javascript isn't right. Any idea what is wrong?
Heres my html:
<?php foreach ($result as $row): ?>
<select class="form-control" name="category[]" required>
<option value="" disabled selected>Select The Category </option>
<option value="station">Station</option>
<option value="equipment">Tools/Equipment</option>
<option value="supplies">Supplies</option>
</select>
<input id="taskID" value="<?php echo $row['id']; ?>" hidden></input>
<?php endforeach; ?>
jquery:
$(document).on('change', 'select[name="category[]"]', function(event){
$('select[name="category[]"]').each(function(){
var formData = {
'task': $('select[name="category[]"]').val(),
'name': $('input[name="taskID[]"]').val(),
};
$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
});
});
addressBook.php
if (isset($_POST['task'])) {
$task = $_POST['task'];
$id = $_POST['name'];
$stmt = $con->prepare("UPDATE members SET task = ? WHERE id = ?");
$stmt->bind_param('ss', $task, $id);
$stmt->execute();
}
Change the class attribute to: class="form-control categorySelect"
$('.categorySelect').change(function(event){
for(selectInstance of $('.categorySelect')){
var formData = {
'task': $(selectInstance).val(),
'name': $(selectInstance).next().val()
};
$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
}
});
I want Broker Commsion on Selection of Admin with the help of Ajax Only.
<select id="user_id" onchange="funCom(this);" >
<option value="" >Select Broker </option>
<?php $aData=$oGeneral->get_records('tbl_user');
$aUsertDetails = $oGeneral->aAdmin;
$iUserDetails = $oGeneral->iAdmin;
for($i=0;$i<$iUserDetails;$i++){?>
<option value="<?=$aUsertDetails[$i]['fld_id']?>">
<?php echo $aUsertDetails[$i]['fld_name']; ?></option>
<?php }?>
</select>
<input type="text" id="comm" name="fld_commision" value="" onkeyup="sum()" required>
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'text',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
It is Ajaxhandler.php.
Here I am geting the commsion value which needs to put into textbox. The value is showing in <div> but I want in text box.
<?php
require('../configuration/configuration.php');
$oGeneral = new GeneralClass();
$oUser = new UserClass();
$token= $_REQUEST['Token'];
switch($token) {
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo $total;
break;
}
?>
Change your datatype to json and try this.
Funtion calling
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
dataType: 'json',
type: 'post',
async: false,
data: SendData,
success: function(data)
{
//var commision=stripHTML(data);
//$('#comm').val(commision); again not working
//$('#comm').text(data); Tried this but fail
$('#comm').val(data.total); //output is <body></body></html>7000
// i want only 7000 i have tried
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
} });
}
is Ajaxhandler.php
$token= $_REQUEST['Token'];
switch($token)
{
case 'search-comm': $id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
break;
}
?>
try this code, I test in my computer and that works!
function funCom(id){
id = id.value;
Token= "search-comm";
SendData= "Token="+Token+"&id="+id;
$.ajax({ url: 'Ajaxhandler.php',
type: 'POST',
data: {Token:Token,id:id},
}).done(function( data ) {
$("#comm").val(data.total);
});
<?php
$token= $_REQUEST['Token'];
header('Content-type: application/json');
switch($token)
{
case 'search-comm':
$id=$_REQUEST['id'];
$oUser->project_commision($id);
$aUsertDetails = $oUser->aResults;
$iUsertDetails = $oUser->iResults;
$total=0;
for($i=0;$i<$iUsertDetails;$i++){
$total+= $aUsertDetails[$i]['fld_commsionprice'];
}
echo json_encode(array('total'=>$total));
die;
}
echo json_encode(array('total'=>""));
die;
?>
I applied some jquery on my paragraph fields and converted them in input fields.It works!! But when i post them to next page i.e address_update.php after giving some values through ajax it does not update the values in database. Any suggestions please.
html
<form method="post" action="">
<?php
$em=$_SESSION['login_email'];
$query = mysqli_query($con,"SELECT * FROM customers where email='$em'" );
while($row=mysqli_fetch_assoc($query)){
?>
<h5>Name:</h5><p id="name"><?= $row['name'] ?></p>
<h5>Email:</h5><p id="email"><?= $row['email'] ?></p>
<h5>Telephone:</h5><p id="phone"><?= $row['phone'] ?></p>
<h5>Address:</h5><p id="address"><?= $row['address'] ?></p>
<h5>City:</h5><p id="city"><?= $row['city'] ?></p>
<?php
}
?>
<input type="button" id="up" value="Update" >
<input type="submit" id="update" value="Update Address" >
</form>
Ajax
<script >
$(document).ready(function() {
$('#update').click(function(){
var name = $("#name").val(),
address = $("#address").val(),
phone = $("#phone").val(),
city = $("#city").val();
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name: name, Address: address, Phone: phone, City:city},
dataType: "json",
success: function(data) {
if(data)
{
$("#error").html("Done. ");
// $("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Cant update. ");
}
}
});
});
});
</script>
Js
<script>
$('#up').click(function() {
var $name = $('#name');
var $phone=$('#phone');
var $address = $('#address');
var $city=$('#city');
var $input_name = $("<input>", {value: $name.text(),type: "text", id:"name"});
var $input_phone = $("<input>", {value: $phone.text(),type: "text", id:"phone"});
var $input_address = $("<input>", {value: $address.text(),type: "text" ,id:"address"});
var $input_city = $("<input>", {value: $city.text(),type: "text",id:"city"});
$name.replaceWith($input_name);
$phone.replaceWith($input_phone);
$address.replaceWith($input_address);
$city.replaceWith($input_city);
document.getElementById("update").style.display="block";
document.getElementById("up").style.display="none";
$input_name.select();
$input_address.select();
$input_phone.select();
$input_city.select();
});
</script>
address_update.php
if(isset($_SESSION["login_email"]) || isset( $_SESSION["login_user"]))
{
$name=$_POST['Name'];
$address=$_POST['Address'];
$phone=$_POST['Phone'];
$city=$_POST['City'];
$email=$_SESSION['login_email'];
$sql=mysqli_query($con,"Update `customers` set `name`='".$name."',`address`='".$address."',`phone`='".$phone."',`city`='".$city."' where `email`='".$email."'");
if($sql)
{
echo "updated";
}
else{
echo "no";
}
}
You can not put the jquery selectors in the json array, but anyway supposig you have an "#add" element:
$(document).ready(function() {
$('#add').click(function()
{
var name = $("#name").val(),
address = $("#address").val(),
phone = $("#phone").val(),
city = $("#city").val(),
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name: name, Address: address, Phone: phone, City:city},
dataType: "json",
success: function(data) {
if(data)
{
$("#error").html("Done. ");
// $("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Cant update. ");
}
}
});
});
});