multiple option boxes same name jquery ajax - javascript

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();
}
});

Related

get states of country return null

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

Send file with jquery and recive in PHP (No plugIn)

I'm trying to send a file using AJAX with the form but the PHP file seems to receive nothing, not only the files but also the form elements. In PHP if i try to get a value from the $_POST i get an Undefined Index.
I've tried:
$("#animal-insert").click((e) => {
e.preventDefault();
var fd = $("#animal-form-input");
var files = $("#file")[0].files[0];
fd.append("file", files);
$.ajax({
url: "php_utility/ajax/admin-animal.php",
type: "post",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
and the method you see in the code below. I'm restricted to do this without plugins.
I was also trying with the $.post() but if i understood correctly i have to use $.ajax() to add the processData: false to send files.
HTML
<form method="POST" action="" id="animal-form-insert" enctype="multipart/form-data">
<div class="span-1-of-2">
<label for="specie" class="label">Specie Animale:</label>
<input type="text" class="animal-input" id="specie" name="specie" required placeholder="Pavo cristatus">
<label for="an-name" class="label">Nome Comune:</label>
<input type="text" class="animal-input" id="an-name" name="an-name" required placeholder="pavone comune">
</div>
<div class="span-1-of-2">
<label for="biom" class="label">Bioma/Habitat:</label>
<select class="animal-input" name="biom" id="biom" required>
<option value="Savana">Savana</option>
<option value="Tundra">Tundra</option>
<option value="Pianura">Pianura</option>
</select>
<label for="zoo-zone" class="label">Zona Zoo:</label>
<select class="animal-input" name="zoo-zone" id="zoo-zone">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="F">F</option>
<option value="PN">PN</option>
</select>
</div>
<label for="animal-photo" class="label">Foto Animale:</label>
<input type="file" id="animal-photo" name="animal-photo" accept=".jpg,.jpeg.png" required>
<label for="aniaml-desc" class="label">Descrizione:</label>
<textarea class="animal-input-desc" name="animal-desc" id="animal-desc" required></textarea>
<button type="submit" name="animal-insert" id="animal-insert" class="btn btn-block">Aggiungi</button>
</form>
JS
$("#animal-insert").click((e) => {
e.preventDefault();
var formData = {
specie: $("#specie").val(),
anname: $("#an-name").val(),
biom: $("#biom").val(),
zoozone: $("#zoo-zone").val(),
animaldesc: $("#animal-desc").val(),
animalphoto: $("#animal-photo")[0].files[0],
submit: "submit",
};
console.log(formData);
$.ajax({
url: "php_utility/ajax/admin-animal.php",
type: "post",
data: JSON.stringify(formData),
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
});
PHP
<?php
error_log($_POST['specie']);
if (isset($_POST['specie'])) {
$animalspecie = $_POST['specie'];
$animalName = $_POST['anname'];
$animalBiom = $_POST['biom'];
$animalZone = $_POST['zoozone'];
$animalDesc = $_POST['animaldesc'];
$animalPhoto = $_FILES['animalphoto'];
$animalPhotoName = $animalPhoto['name'];
$photoTmp = $animalPhoto['tmp_name'];
$photoErr = $animalPhoto['error'];
$photoType = $animalPhoto['type'];
error_log("not here");
$formats = ["image/jpg", "image/jpeg", "image/png"];
require_once '../sql/utility.php'; //file with functions for db
require_once '../checks.php'; //file with some type checks
if (empty($animalspecie) || empty($animalName) || empty($animalBiom) || empty($animalZone) || empty($animalDesc) || empty($animalPhoto)) {
echo "emptyinput";
exit();
}
if (!preg_match('/[A-Z]+[a-z]+\s[a-z]+/', $animalspecie)) {
echo "invalidspecie";
exit();
}
if (!in_array($photoType, $formats)) {
echo "invalidformat";
exit();
}
if ($photoErr !== 0) {
echo "fileerror";
exit();
}
$tmpExtension = explode("/", $photoType);
$photoExtension = end($tmpExtension);
$photoNewName = preg_replace('/\s+/', '', $animalName) . preg_replace('/\s+/', '', $animalName) . "." . $photoExtension;
$photoDestination = "//resurces/images/animals/" . $photoNewName;
move_uploaded_file($photoTmp, $_SERVER['DOCUMENT_ROOT'] . $photoDestination);
$result = insertAnimal($conn, $animalspecie, $animalName, $animalBiom, $animalZone, $animalDesc);
echo $result;
}
You should create a new FormData() and append your form values and files to it, and then send it as 'multipart/form-data' in the data (not body) param.
$("#animal-insert").click((e) => {
e.preventDefault();
var formData = new FormData();
formData.append("specie", $("#specie").val())
formData.append("anname", $("#an-name").val())
formData.append("biom", $("#biom").val())
formData.append("zoozone", $("#zoo-zone").val())
formData.append("animaldesc", $("#animal-desc").val())
formData.append("animalphoto", $("#animal-photo")[0].files[0])
formData.append("submit", "submit")
$.ajax({
url: "php_utility/ajax/admin-animal.php",
method: "post",
data: formData,
cache: false,
mimeType: "multipart/form-data",
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
});
In PHP Your files will be avaiable in $_FILES array, and the other data will be in $_POST array.
More on FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData

Change event not triggered on ajax call

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();
},
});

Get value in textbox using ajax response

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;
?>

Ajax + Controller Action in Yii2

I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.
Here is the example code I'm trying:
views/index.php:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
success: function (data) {
alert(data);
}
});
}
</script>
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<select id="searchby">
<option value="" disabled="disabled" selected="selected">Search by</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>
Controller:
public function actionSample(){
echo "ok";
}
My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!
This is sample you can modify according your need
public function actionSample()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$searchname= explode(":", $data['searchname']);
$searchby= explode(":", $data['searchby']);
$searchname= $searchname[0];
$searchby= $searchby[0];
$search = // your logic;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'search' => $search,
'code' => 100,
];
}
}
If this will success you will get data in Ajax success block. See browser console.
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
console.log(data.search);
}
});
you have to pass _csrf tokin as a parameter
_csrf: yii.getCsrfToken()
or you can disable csrf valdation
The correct way to get the CSRF param is this:
data[yii.getCsrfParam()] = yii.getCsrfToken()

Categories

Resources