AJAX Request not working in Laravel 5.8.33 - php

I am trying to make a dependent select field but When I select the first field Nothing happen to the other field. I think the ajax code is not working because I use an alert in the starting of the function call by ajax and alert didn't appear but still I am not sure what's the problem. What's wrong with my code can anyone help me in solving this problem.
Html code
<form method="POST" action="{{url('search')}}">
#csrf
<div class="input-group col-sm-10 mt-5 offset-sm-1">
<select class="form-control" name="city">
<option value="none">---Choose City---</option>
<?php foreach ($result['city_data'] as $city) {
?>
<option value="<?php echo $city->id;?>"> <?php echo $city->name;?> </option>
<?php } ?>
</select>
<select class="form-control" name="area">
<option>Choose City</option>
</select>
<div class="input-group-append">
<input type="submit" class="btn searchbutton" value="Search" name="search_button">
</div>
</form>
Ajax code
<script type="text/javascript">
$(document).ready(function() {
$('select[name="city"]').on('change', function(e) {
var cityID = $(this).val();
if(cityID) {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }})
e.preventDefault();
$.ajax({
url: '/myform/ajax/'+cityID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="area"]').empty();
$.each(data, function(key, value) {
$('select[name="area"]').append('<option value="'+ key +'">'+value+'</option>');
});
}
});
}
else{
$('select[name="area"]').empty();
}
});
});
</script>
web.php
Route::get('myform/ajax/{id}','services4uController#myformAjax');
Controller.php
public function myformAjax($id)
{
echo "<script>alert('Code reached to this stage');</script>";
$area = DB::table("area")
->where("id_city",$id)
->lists("name","id");
return json_encode($area);
}

Related

How to create filter for options value using ajax in php and zf2

How to make filter using ajax i want to get single option value for each selection and when click on filter button it sends data to getproductlistcb controller.
please help
HTML CODE is-
<div class="filter-category">
<form>
<input type="submit" value="filter" class="btn filter-btn">
<div class="user-category-select">
<select required="" name="sort" form="filter-form" class="btn filter-form-select" >
<option value="" disabled="">Sort</option>
<option value="popularity" selected="">Most Popular</option>
<option value="highest-rated">Highest Rated</option>
<option value="newest">Newest</option>
<option id="aesc" value="price-low-to-high">Lowest Price</option>
<option id="desc" value="price-high-to-low">Highest Price</option>
</select>
<label class="filter-category-select"><i class="fa fa-angle-down" aria-hidden="true"></i></label>
</div>
</form>
</div>
AjaX-
<script type="text/javascript">
$(document).ready(function(){
$('.btn filter-form-select').on('change',function(){
var data=$('#search_form');
$.ajax({
type: "POST",
url: "<?php echo $this->url('page', array('controller' => 'page', 'action' => 'getproductlistcb')); ?>",
data:data,
success:function(data){
console.log(data);
alert(data);
$("#").html(data);
}
});
});
});
</script>
Did you try to use :option in selector? For example, in that way: $('select.filter-form-select option:selected').val();?
I think you are looking for DOM-selector like that:
$('.filter-form-select option:selected').
So, in your case, in your code the code below might be helpful:
var $formData = $('#search_form');
var $formFilters = $formData.find('select.filter-form-select');
var $firstFilter = $formFilters.first();
var $option = $firstFilter.find('option:selected');
var optionText = $option.length ? $option.text() : null;
var optionValue = $option.length ? $option.val() : null;
Be aware, that $formFilters is not just one element, it's jQuery object that represents a set of DOM elements.
An additional way, try to debug and check what you have in your this-context and event:
$('.btn filter-form-select').on('change',function(event) {
console.log('clicked: ' + event.target.nodeName);
console.log('Context: ' + this);
});
I hope, something from that will help you a bit.

PHP Ajax dependent dropdown not working

I am trying to implement dependent dropdown using ajax and php. But anyhow the response from second dropdown is not coming. after checking in console, I am able to see the id of first dropdown but no response from second dropdown. So, When i click on first dropdown, I just get a blank value in Second dropdown.
HTML Code
<div class="col-md-6">
<?php
require_once('db.php');
$varient_result = $conn->query('select * from tv_varient');
?>
<select name="varient" id="varient-list" class="form-control c-square c-theme" required>
<option value="">Select Varient</option>
<?php
if ($varient_result->num_rows > 0) {
// output data of each row
while($row = $varient_result->fetch_assoc()) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
}
?>
</select>
</div>
</br></br>
<label for="inputPassword3" class="col-md-4 control-label" style="margin-left: 15px;">Price:</label>
<div class="col-md-6">
<select name="price" id="price-list" class="form-control c-square c-theme" required>
<option value=''>Select Price *</option>
</select>
<div>
</div>
</div>
</div>
</div>
</div>
AJAX Code
<script>
$('#varient-list').on('change', function(){
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
</script>
get_price.php
?php
require_once('db.php');
//$country_id = mysqli_real_escape_string($_POST['country_id']);
//var_dump($country_id);
//var_dump($_POST['country_id']);
$varient_id = $_POST['veriant_id'];
echo $varient_id;
//var_dump($varient_id);
var_dump($_POST['varient_id']);
if($varient_id!='')
{
$states_result = $conn->query('select * from tv_price where veriant_id='.$varient_id.'');
$options = "<option value=''>Select Price</option>";
while($row = $states_result->fetch_assoc()) {
$options .= "<option value='".$row['price']."'>".$row['price']."</option>";
}
echo $options;
}
?>
Try below code,
$(document).on('change', '#varient-list', function(e)
{
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
varient_id & veriant_id on the POST is wrong (the e & a difference).
$varient_id = $_POST['veriant_id']; should be $varient_id = $_POST['varient_id'];

jQuery - Serialize Form Post Values

How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal&param2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.

im not able to call my ajax request in new added div in angular js

i have a three dropdowns like country,state,city it's using ajax reuest.
then i add new dropdowns div using my buttion , myfirst dropdown div's data passed and displayed and it's work fine, but others div's dropdown data not passed and not display and ajax request can't send .
it's my ajax request
<script>
function getstatedetails(id)
{
//alert('this id value :'+id);
$.ajax({
type: "POST",
url: 'ajax_get_finish/'+id,
data: id='cat_id',
success: function(data){
// alert(data);
$('#old_state').html(data);
},
});
}
function getcitydetails(id)
{
$.ajax({
type: "POST",
url: 'ajax_get_size/'+id,
data: id='st_id',
success: function(data){
$('#old_city').html(data);
},
});
}
it's my angular js code
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('shanidkvApp', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
and its my html
<div class="content-wrapper" ng-app="shanidkvApp">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Add Challan Details
<i class="fa fa-list"></i> challan Details List
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="row"> <div class="col-md-12 display_alert"></div></div>
<div class="row">
<div class="col-md-6">
<div class="box box-primary" ng-app="angularjs-starter" ng-controller="MainCtrl">
<div class="box-body table-responsive">
<form action="insert" method="post" data-parsley-validate novalidate enctype="multipart/form-data">
<div data-ng-repeat="choice in choices">
<div class="form-group">
<label for="form-address">Model Name</label>
<select name="country_details" class="form-control countries" id="country_details" onChange="getstatedetails(this.value)">
<option value="" selected="selected" >Select Model</option>
<?php foreach($groups as $count): ?>
<option value="<?php echo $count->model_id; ?>"><?php echo $count->model_name; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="form-address">Finish Name</label>
<select name="select_state" class="form-control countries" id="old_state" onChange="getcitydetails(this.value)">
<option selected="selected">Select Finish</option>
</select>
</div>
<div class="form-group">
<label for="form-address">Size</label>
<select name="selectcity" class="form-control countries" id="old_city" >
<option selected="selected">Select Size</option>
</select>
</div>
<div class="btn btn-primary" ng-show="$last" ng-click="removeChoice()">Remove</div>
</div>
<div class="btn btn-primary" ng-click="addNewChoice()">Add fields</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
</section>
<!-- /.content -->
data in ajax should be in object form
function getstatedetails(id)
{
//alert('this id value :'+id);
$.ajax({
type: "POST",
url: 'ajax_get_finish/'+id,
data: id='cat_id',
success: function(data){
// alert(data);
$('#old_state').html(data);
},
});
}
pls try
$.ajax({
...
data: { id: 'cat_id' }
})
Stop using JQuery and AngularJS together.
If you want your data, use AngularJS too.
For instance,
app.factory('requestFactory', function($q, $http) {
var ret = {
getStateDetails: getStateDetails,
getCityDetails: getCityDetails
};
return ret;
function getStateDetails(id) {
//Use of promises
var deffered = $q.defer();
$http.post('ajax_get_finish/' + id, {id: 'cat_id'})
.then(function(success) {
deferred.resolve(success.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
function getCityDetails(id) {
//Use of promises
var deffered = $q.defer();
$http.post('ajax_get_size/' + id, {id: 'st_id'})
.then(function(success) {
deferred.resolve(success.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
});
Then, load your data in your controller, and use the two-way binding to display it.

refresh div in ajax

I build search query with option value.i get the country,state,city by json code.i get country list on onload by json code.but when i change value of country then top content are also show before get result with pagination.The loading img work fine in pagination but not in option values.
this is first link of select option image:-https://www.dropbox.com/s/jvie2x82l2vx4kp/search1.png?dl=0
second link is search image:-https://www.dropbox.com/s/1pe5r5uy9wi19m8/search2.png?dl=0
session_start();
if(isset($_GET['search']))
{
$q=$_GET['profession'];
$_SESSION['name']=$_GET['profession'];
}
else
{
session_unset();
}
if(isset($_GET['country']))
{
$_SESSION['country']=$_GET['country'];
}
if(isset($_GET['state']))
{
$_SESSION['state']=$_GET['state'];
}
if(isset($_GET['region']))
{
$_SESSION['region']=$_GET['region'];
}
enter code here
<script>
$(document).ready(function(){
$("#country").bind("change", function() {
$.ajax({
type: "GET",
data: "country="+$("#country").val(),
cache: false,
beforeSend: function(){ $("#ajaxLoader").show(); },
complete: function(){ $("#ajaxLoader").hide(); },
success: function(html) {
$("#pagination").html(html).show();
}
});
});
});
</script>
<div id="mhead"><h2>Search Result</h2></div>
<div class="content">
<body onload="listOfCountries('country');">
<form>
<p>Country:
<select name="country" id="country" onchange="listOfStatesOrCities(this,'state');" style="width:150px;"> */
<option value=""></option>
</select>
State:
<select name="state" id="state" onchange="listOfStatesOrCities(this,'region');" style="width:150px;">
<option value=""></option>
</select>
city:
<select name="region" id="region" style="width:150px;" >
<option value=""></option>
</select>
</p>
</form>
<div id="ajaxLoader" style="display:none"><img src="images/loading.gif" alt="loading..."></div>
<div id="loading" style="display:none"><img src="images/loading.gif" alt="loading..."></div>
<div id="pagination" cellspacing="0">
</div>
</div>
You can pass selector #pagination to fetch only the div with id pagination.
Try this:
$("#country").bind("change", function() {
$("#ajaxLoader").show();
$("#pagination").load(window.location.href + ' #pagination', { country: $("#country").val() }, function() {
$("#ajaxLoader").hide();
});
});

Categories