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.
Related
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);
}
});
});
});
Can You Please Find Out The Problem In The Following Code
I am trying to populate 1 select option based on previous 2 select options.
For example, you will select option 1 and then select option 2 based on those 2 options I will get 3rd option.
Here is my jquery part
/*This Is Basically My Jquery Part Which will Take 2 values from selects*/
$(".asset").change(function(){
var id=$(this).val();
console.log(id);
var dataString1 = 'id='+ encodeURIComponent(id);
console.log(dataString1);
$(".amc").change(function(){
var aid=$(this).val();
console.log(aid);
var dataString2 = 'aid='+ encodeURIComponent(aid);
console.log(dataString2);
//console.log(data);
$.ajax({
type: "POST",
url: "fetch.php",
data : {dataString1: id,dataString2: aid},
cache: false,
success: function(html)
{
$(".scheme").html(html);
}
});
});
});
Here is the fetch part
<?php
include('dbconfig.php');
if($_POST['id'] && $_POST['aid'])
{
$id=$_POST['id'];
$aid=$_POST['aid'];
$stmt = $DB_con->prepare("SELECT * FROM Master_MutualFundMasters WHERE AssetClassID=:id AND AMCID = :aid");
$stmt->execute(array(':id' => $id));
$stmt->execute(array(':aid' => $aid));
?><option selected="selected">Select City :</option>
<?php while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['WW_UniqueInvestmentCode']; ?>"><?php echo $row['PrimarySchemeName']; ?></option>
<?php
}
}
?>
When I check my console it is showing me the data but its not passing on next page
You should use select at beginning.
Example:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi" selected>Audi</option>
</select>
since you are asking
In your console it is showing me the data but its not passing on next page means (fetch.php).
then you can do-
$.ajax({
type: "POST",
url: "fetch.php",
data : {"id":dataString1,"aid":dataString2},
cache: false,
success: function(html)
{
$(".scheme").html(html);
}
});
and in fetch.php page.
if($_POST["id"] && $_POST["aid"])
{
$id=$_POST["id"];
$aid=$_POST["aid"];
//write ur code here...
}
I Hope this help u.
I tried everything but I can not figure it out.
This is old discussion: PHP Group By value - JSON
In this other thread I was told that the ajax approach is different. I tried to run their advice but when I write the code Javascript in ajaxData.php file seems not to work.
I need to populate reservationTime dropdown with time array (splitted in ajaxData) and dependent by reservationDate (grouped Date Array).
The code below works and fills reservationDate dropdown with date(splitted). Now I would like populate second dropdown.
Dropdown Image
reservationDate Dropdown Image
I have index.php with:
<form id="my-form" method="post" autocomplete="off">
<div class="a-row">
<div id="input-parent">
<select name="company" required="" id="company">
<option value="">Select company</option>
<option value="1">Rome</option>
<option value="2">New York</option>
<option value="3">Madrid</option>
<option value="4">Tokyo</option>
</select>
</div>
<div id="input-parent">
<select name="productCode" required="" id="product">
<option value="">Select product</option>
<option value="IPAD">iPad</option>
<option value="GALAXY">Samsung Galaxy</option>
<option value="LGTV">LG TV</option>
</select>
</div>
<div id="input-parent">
<select name="reservationDate" required="" id="date">
<option>Select date</option>
</select>
</div>
<div id="input-parent">
<select name="reservationTime" required="" id="time">
<option>Select time</option>
</select>
</div>
</div>
<div class="a-row">
<div>
<input type="submit">
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // serializzo
})
.done(function(data){
})
.fail(function(){
alert('Error');
});
});
// Company change
$('#company').on('change', function(e) {
e.preventDefault(); // Prevent Default Submission
var productID = $("select#product option:checked" ).val();
var companyID = $(this).val();
if(companyID && productID != ""){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{company:companyID,productCode:productID},
success:function(html){
$('#firstSelect').html(html);
}
});
}else{
console.log("Nothing");
}
});
// Product change
$('#product').on('change', function(e) {
e.preventDefault(); // Prevent Default Submission
var companyID = $("select#company option:checked" ).val();
var productID = $(this).val();
if(companyID && productID != ""){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{company:companyID,productCode:productID},
success:function(html){
$('#firstSelect').html(html);
}
});
}else{
console.log("Nothing");
}
});
});
</script>
And ajaxData.php where I split date and time and insert loop date values into date dropdown of index.php:
<?php
if(isset($_POST["company"]) && isset($_POST["productCode"]))
{
// Token ID
$authToken = 'XXXXXXXXXXXXXXXXX';
// To send API
$companyData = $_POST["company"];
$productData = $_POST["productCode"];
// Setup cURL
$ch = curl_init('https://.../'.$companyData.'/'.$productData.'' );
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Aythorization: '.$authToken,
'Content-Type: application/json'
),
));
// Send Request
$response = curl_exec($ch);
// Response
$responseData = json_decode($response, TRUE);
$responseData = json_decode($response);
// Setup Var
$availableSlots = $responseData->availableSlots;
$slots_start = $responseData->availableSlots->slots;
// Check if errors
if($response === FALSE){
die;
}
$times = array();
foreach($slots_start as $option){
list($date, $time) = explode(" ", $option->start);
if (!array_key_exists($date, $times)){
$times[$date] = array();
}
if (!in_array($time, $times[$date])){
$times[$date][] = $time;
}
}
foreach ($slots_start as $option){
echo '
<option value="' . $option->start. '">' . $option->start . '</option>';
}
}
?>
My JSON data:
{
"response": {
"storeTimeZone": "Europe/Paris",
"slots": [
{
"start": "2017-01-23T08:00:00Z"
},
{
"start": "2017-01-23T08:20:00Z"
},
{
"start": "2017-01-23T08:40:00Z"
},
{
"start": "2017-01-16T08:00:00Z"
},
{
"start": "2017-01-16T08:20:00Z"
},
{
"start": "2017-01-16T08:40:00Z"
}
...
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');
}
});
});
I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
And, another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
You can use ajax. See example below
$(function(){
$('#brand').on('change', function(){
var brand = $(this).val();
$.ajax({
type : 'post',
url : '<?php echo base_url();?>controller_name/function_name',
data : 'brand='+brand,
dataType : 'json',
success : function(msg){
// here you can populate data into category select option
var options;
for(var i = 0; i<msg.length; i++)
{
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options); // your html part for category should look like this <select id="category"></category>
}
});
});
});
php code in controller part(function name showCategory)
function showCategory(){
$brand = $this->input->post('brand');
$data['category'] = $this->your_model->your_function_to_select_data();
echo json_encode($data);
}
<?php
?>
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
<p>Category:</p>
<select name="category">
<!--Content will be popullated from ajax call-->
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>
<script type="text/javascript">
(function($){
$(function(){
$(document).on('change' , '[name=brand]', function(){
var brand_selected = $(this).val();
$.ajax({
url: '[your url to fetch category based on categoryid]' ,
dataType:"json",
data: {brand : brand_selected},
success: function(r){
/**
* your response should be in json format
* for easy work
{catd_id: catname, cat_id :catname}
*/
var html = '';
if(r && r.length){
$.each(r, function(i, j){
html +='<option value="'+i+'">'+j+'</option>';
})
}
/**
* finaly populat ethe category data
*/
$('[name="category"]').html(html);
}
})
})
})
})(jQuery)
</script>
Change the portion as per yours...
Use this approach to detect changing value of select tag.
$( "#brand" ).change(function() {
var myOption = $(this).val();
// use ajax to get data for 'category' select by using "myOption"
});
then when you get ajax response add new select tag with
for (var i = 0 ; i < response.length; i++)
{
$('#category').append('<option>'+response[i]+'</option>')
}
I still don't get the required answer. Below is my view.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
My Controller:
function showCategory() {
if($this->session->userdata('success')) {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
$this->load->helper('url');
}
}
My category table contains: category_id, category_name, brand_id.