How can I refresh a select list with another - ajax

I am trying hard to refresh a list after selecting an option of a second.
I have this list
<select id="ArticleShopId">
<option>Some options</option>
<option>Some options 2</option>
<option>Some options 3</option>
</select>
I have a seond
<select id="ArticleCategoryId">
<option></option>
<option></option>
<option></option>
<option></option>
</select>
When I select an option of the first, ajax should load the table Shop and update the second select
I create an action called admin_refreshCategoriesAjax
function admin_refreshCategoriesAjax($id = null){
$this->loadModel('Category');
// Le list recupere la valeur des IDs et cherche un champs qui a la valeur "name"
$categories = $this->Category->find('list',array('order'=>'name ASC','conditions'=>array('shop_id'=>$id)));
//return "toto";
return $categories;
#return json_encode($categories);
}
I wish t create a ajax code to do it. Then I try doing it
$('select#ArticleShopId').on('change',function(){
//alert($(this).val());
//alert("/articles/refreshCategoriesAjax/"+$(this).val());
$.ajax({
type: "GET",
url: "<?php echo $this->Html->url(array('controller' => 'articles', 'action' => 'refreshCategoriesAjax', 'admin' => true)); ?>",
data: "id="+$(this).val(),
success: function(msg){
console.log(msg);
}
})
})
but msg does not return my an array with the $categories values.
How can I correctely call my action admin_refreshCategoriesAjax and update my second select with the value of $categories?
many thank for your help, I spend half day on it :o(
Note:
If I enter this in my URL
http://localhost:8888/web/admin/articles/refreshCategoriesAjax/1
it return me well the array I looking for. If I changer 1 with 2, it return my other value. Then this part seams to work nice

I believe your problem is that in your function admin_refreshCategoriesAjax you are returning the array rather than doing something that will actually output it to the webpage. You could do echo json_encode($categories); to get some output you can use without explicitly creating a view for that action.

Instead of finding an id in the parameter, you will find an id in $this->request->data. To make your ajax request secure, use the following code into your view file:
$('select#ArticleShopId').on('change',function(){
//alert($(this).val());
//alert("/articles/refreshCategoriesAjax/"+$(this).val());
$.ajax({
type: "POST",
url: "<?php echo $this->Html->url(array('controller' => 'articles', 'action' => 'refreshCategoriesAjax', 'admin' => true)); ?>",
data: {id:$(this).val()},
success: function(msg){
console.log(msg);
}
});
});
And the following code into your controller:
function admin_refreshCategoriesAjax(){
$categories = array();
if($this->request->is('post'))
{
$id = $this->request->data['id'];
$this->loadModel('Category');
// Le list recupere la valeur des IDs et cherche un champs qui a la valeur "name"
$categories = $this->Category->find('list',array('order'=>'name ASC','conditions'=>array('shop_id'=>$id)));
//return "toto";
}
return $categories;
#return json_encode($categories);
}
Now to fill the data in dropdown, return json_encode($categories) from your controller. And use var result = $.parseJSON(msg); in your ajax success method.

Related

Laravel ajax is not returning success data

I am trying to achieve a functionality, If I select a category in dropdown, then in next dropdown, subcategory of that chooces category will appear. I wrote below ajax in script tag for it.
$("#category").change(function(e){
e.preventDefault();
var category = $("#category").val();
$.ajax({
type:'POST',
url:"{{ route('ajaxRequest.post') }}",
data:{category:category},
success:function(data){
alert(data.success);
$("#subcategory").replaceWith(data.subcats);
}
});
});
Here is my route setup for the same
Route::get('add_product', [dashboardController:: class, 'addProduct']);
Route::post('add_product', [dashboardController::class, 'getSubCategories'])->name('ajaxRequest.post');
This is my controller function
function getSubCategories(Request $request){
//$input = $request->all();
$subCategoryList = DB::table('ajax_categories')->where('pid', $request->post('category'))->get();
$sub = '<option desabled selected>Choose sub category</option>';
foreach($subCategoryList as $subCategory):
$sub .= '<option value="'.$subCategory->id.'">'.$subCategory->category.'</option>';
endforeach;
return response()->json(array(
'success' => 'Success',
'subcats' => $sub
));
}
Everything seems fine, I am not getting what causing it to be fail.
Screenshot of network tab
On clicking on checkbox, I got this in reponse
You are echoing result before returning response so ajax is not able to parse json properly.And other is csrf token not passed properly.
In ajax you can pass csrf token like below
data:{_token: "{{ csrf_token() }}",category:category},
instead of appending in controller better do like this
function getSubCategories(Request $request){
$subCategoryList = DB::table('ajax_categories')->where('pid', $request->post('category'))->get();
$view=(string)view('dropdown',['subCategoryList'=>$subCategoryList])
return response()->json(array(
'success' => 'Success',
'subcats' =>$view
));
}
in your view dropdown.blade.php you can
#if(isset($subCategoryList)&&count((array)$subCategoryList))
#foreach($subCategoryList as $key=>$value)
<option value="{{$subCategory->id}}">{{$subCategory->category}}</option>
#endforeach
#endif

Select default value in dropdown Ajax

i am trying to set default values in select.
Ajax:
$.ajax({
type: "GET",
url: "teachers/" + $(this).attr("value") + "/edit",
dataType: 'json',
success: function (data) {
$('.qual_id option[value=' + data.qualifs + ']').attr('selected', true);
}
Controller:
public function edit($id)
{
$qualifs = DB::table('qualif_teachers')
->join ('qualifs','qualif_teachers.qualif_id','=','qualifs.id')
->where('teacher_id', '=' , $id)
->pluck('qualifs.id');
return response()->json([
'status' => 'success',
'qualifs'=> $qualifs,
]);
}
View:
<select class="form-control qual_id">
<option value="">-Select Degree-</option>
<option value="1">SSC</option>
<option value="2">HSC</option>
<option value="3">BBA</option>
<option value="4">MBA</option>
</select>
Error:
Syntax error, unrecognized expression: .qual_id option[value=1,2]
Without being specific about the javascript framework you're using and without knowing the format of your ajax response, this works (assuming that defaultValue holds your desired option value):
var defaultValue = 1
$(`.qual_id option[value=${defaultValue}]`).attr('selected', true);
Here's a working fiddle.

Post 403 forbidden on Yii2 Ajax Call

I know there's other topic on this in stackoverflow but it still didn't work for me. I try to make a simple dynamic menu that generate dynamic content based on the chosen <li> id.
This is the code to generate the menu :
foreach($cabang as $index=>$model){
echo '<li id='.$model->idDpd->id_dpd.'>
<a class="nav-link" href="#" role="tab" data-toggle="tab">'.$model->idDpd->dpd.'</a>
</li>';
}
The menu is created successfully. But I have the problem with the content generated with Ajax
This is what I have in my view file :
$script = <<< JS
$(document).ready(function(){
function load_page_details(id)
{
$.ajax({
url: "<?=Url::to(['/site/fetch']) ?>",
method:"POST",
data:{id:id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success:function(data)
{
$('#page_details').html(data);
}
});
}
//load page-details where the id in the database table equals 1. Set the default to 1 while page is loading for the first time.
/* load_page_details(1);*/
$('.nav li').click(function(){
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script)
?>
This is my SiteController and the action :
public function actionFetch(){
if (Yii::$app->request->isAjax) {
// fetch the $_POST["id"]
$data = Yii::$app->request->post('id');
if(isset($data))
{
$query= Cabang::find()->where(['id_dpd'=> $data])
->joinWith('idDpd')
->all();
$output = '';
foreach($query as $model)
{
$output .= '
<div role="tabpanel" class="col-lg-4 tab-pane fade show active" >
<div class="col-md-12">
<h4>'.$model->kota.'</h4>
<p>'.$model->alamat.'</p>
<p>'.$model->telp.'</p>
<p>'.$model->email.'</p>
<p>'.$model->jadwal.'</p>
</div>
</div>
';
}
/* echo $output;*/
// return Json
return \yii\helpers\Json::encode($output);
}
}
}
The error caught in my console in chorome dev tool : jquery.js:9175 POST http://localhost/%3C?=Url::to([%27/site/fetch%27])%20?%3E 403 (Forbidden)
I tried to make the fetch function to a new php file and link the URL in my Ajax to that file (not to a controller or SiteController in my case) like : url: url:"site/fetch.php",but it returned jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)
What am I doing wrong? I have spent two days without solution. Thanks for the help!
Your PHP is not correct - you cannot use <?= /* ... */ ?> inside of heredoc. You need to use temporary variable:
$url = Url::to(['/site/fetch']);
$script = <<<JS
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
url: "$url",
method: "POST",
data: {id: id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success: function (data) {
$('#page_details').html(data);
}
});
}
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script);

I want to show a window modal without any error after hide if it´s success

I´ve my controller
public function postCreate()
{
//validamos reglas inputs
$rules = array(
'inputuser' => 'required|max:10',
'inputpassword' => 'required|min:8',
'inputpassword1' => 'required|min:8',
'inputemail' => 'required|email|unique:users,email'
);
$validation = Validator::make(Input::all(), $rules);
//Si no pasa la validacion
if($validation->fails())
{
//Obtenemos los mensajes de error de la validation
$messages = $validation->messages();
//Redireccionamos a nuestro formulario de atras con los errores de la validación
if(Request::ajax())
{
return Response::json(array('errors' => $messages));
}
else
{
return Redirect::back()->withInput()->withErrors($validation);
}
}
//Si todo ha ido bien guardamos
$password = Input::get('inputpassword');
$user = new User;
$user->username = Input::get('inputuser');
$user->password = Hash::make($password);
$user->email = Input::get('inputemail');
$user->admin = (Input::get('es_admin') == '1') ? 1 : 0;
//guardamos
$user->save();
//redirigimos a usuarios
return Redirect::to('admin/users.index')->with('status','ok_create');
}
My main.js in ajax
$("document").ready(function()
{
$("#formuser-create").submit(function()
{
event.preventDefault();
var form = $(this);
$.ajax({
url: 'users/create',
dataType:'json',
data: form.serialize(),
type: "POST",
success: function(response)
{
if(response.success)
{
$("#box-modal").modal('hide');
}
else(response.error)
{
$.each(response.errors, function( index, value ) {
$("input[name='"+index+"']" ).css('border: 2px solid #FF0000;');
$("input[name='"+index+"']" ).parent().append(value[0]);
});
}
},
error: function(xhr, textStatus, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
console.log(textStatus);
}
});
});
});
I want to redirect to admin/user and load the view index.blade, with a message of that´s "ok_create" if it´s sucess. But don´t hide the window modal.
I think that don´t hide the modal window in the ajax, because I redirect in my controller when it´s correct.
will I have to make all the code in ajax? , with window.location.href and send a value ok_correct
I´m confused, anyone could help me, with an example?
If you redirect to another page then only option is to open the modal again as it will be totally new page load. You can use #if statements with some boolean flags.
In this scenario you can redirect the user to another URL and include param that controller will set again in the view. In the view you can trigger the modal programmatically after page load event.
If you want the modal to stay open and view behind modal to change then you need to make dynamic ajax website. It is relatively complex and I do not believe this is worth it.

CakePHP AJAX call

I am using CakePHP and this is my first project on this framework. I am going to send the value of an input to UsersController's check_username() action. And fill an element having id na with the string returned by check_username(). So far what I did is:
//in my form
<input type="text" name="data[User][username]" style="width: 60%" required="required" id="username" oninput="check_username(this.value)">
<label style="margin-left: 20px; color: red" id="na">Not Available!</label>
//after the form
<script type="text/javascript">
function check_username(un) {
$.ajax({
type: 'POST',
url: '/oes/users/check_username',
data: {username:un},
cache: false,
dataType: 'HTML',
beforeSend: function(){
$('#na').html('Checking...');
},
success: function (html){
$('#na').val(html);
}
});
}
</script>
//and my check_username() is
public function check_username(){
return 'Test string';
}
But this isn't working. Anybody know why or how to modify it so that it works?
It could be problem with your check_username controller action. CakePHP-way is to use JsonView class to send any data throw XHR (see http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). It allows you to call any action with .json extension (ex.: /oes/users/check_username.json) and get response in serialized JSON format without manual conversion beetween array data and JSON.
This method is recommended for your needs, but not obligated, of course.
Now I think that CakePHP tries to render check_username view, but could not do this because you have not specified or created it. Try to change your action code to something like this:
public function check_username(){
$this->autoRender = false;
echo 'Test string';
}
Also, try not to use such code construction in the future.
CakePHP has a JS Helper to help write aJax functions. The only catch is to include jquery in your head our cake will throw jQuery errors.
Your Form:
<?php
echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
echo $this->Form->input('username');
echo $this->Form->submit('Check Username');
echo $this->Form->end();
?>
The Ajax Function:
<?php
$data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourForm')->event(
'submit',
$this->Js->request(
array('action' => 'checkUsername', 'controller' => 'user'),
array(
'update' => '#na',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
?>
The Function in User Controller
function checkUsername(){
$this->autoRender = false;
//run your query here
if ( $username == true )
echo 'Username is taken';
else
echo 'Username is not taken';
}
There are many examples through google. Here is a good one to visit.

Resources