display a json response - ajax

I have this json when sending json post request and fetching the return data
$.post("/employees", {id:"3"}, function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
console.log(response.employees);
$.each(response.employees, function(user_no, firstname, lastname){
$('<option/>', {
value:user_no,
text: firstname + " " + lastname
}).appendTo(branchName);
});
}
}, 'json');
and in my controller, it gets the id and find record/records where $branch_no is equal to $id and get the column user_no, firstname and lastname and return those as a json response.
public function getemployee(){
$id = $_POST['id'];
$employees = mot_users::where("branch_no", $id)
->select(array('user_no', 'lastname', 'firstname'))
->get()->toArray();
return response()->json(['success' => true, 'employees' => $employees]);
}
now it supposed to display the response as
<select>
<option value="1">Firstname Lastname</option>
<option value="2">Firstname Lastname</option>
<option value="3">Firstname Lastname</option>
<option value="4">Firstname Lastname</option>
</select>
but it display as
<select>
<option value="0">[object object]</option>
<option value="1">[object object]</option>
<option value="2">[object object]</option>
<option value="3">[object object]</option>
</select>
i got no error in my console and I think i fetch the json response incorrectly so any ideas, help, clues, suggestions, recommendations to make this work?

Try this
$.post("/employees", {id:"3"}, function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
console.log(response.employees);
$.each(response.employees, function(index, value){
$('<option/>', {
value:user_no,
text: value.firstname + " " + value.lastname
}).appendTo(branchName);
});
}
}, 'json');

Related

The data from input dropdown select2 is not fetch into datatables

I did a multiselect input dropdown using select2. However, I dont really sure how to fetch the data that I call from database in the dropdown so that I can view it in datatable. Here are my codes:
Script for input dropdown select2:
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
dataType: 'json',
delay: 250,
processResults: function ($ethnicity) {
return {
results: $.map($ethnicity, function (item) {
return {
text: item.Bangsa_updated,
id: item.id,
}
})
};
Controller for input dropdown so it will select the input typed:
public function ethnicity(Request $request)
{
$ethnicity = [];
if($request->has('q')){
$search = $request->q;
$ethnicity = DB::table("user")
->select("id","ethnic")
->where('ethnic','LIKE',"%$search%")
->get();
}
return response()->json($ethnicity);
}
The above code only to select the data from database without fetch data to datatable.
The controller below to catch data into datatable (I used this for simple dropdown, however dont know how to change so it is useful for above input dropdown.
public function fnFilter(Request $request)
{
if(request()->ajax())
{
if(!empty($request->dataGender))
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln')
->where('ethnic', $request->ethnicity)
->get();
}
else
{
$data = DB::table('user')
->select('id', 'Fn', 'Ln', 'Umur', 'Phone', 'Dob','St', 'Country','Zip','Ct','Jantina')
->get();
}
return datatables()->of($data)->make(true);
}
$dataName = DB::table('modified_dpprs')
->select('ethnic','Jantina')
->groupBy('ethnic')
->orderBy('ethnic', 'ASC')
->get();
return response()->json($dataName);
Blade is:
<select id="ethnicity" class=" ethnicity form-control select2-allow-clear" style="width:200px;" name="namaDUN" multiple >
<option value="">Select</option>
My idea is to put the result from controller function ethnicity into function fnFilters. But I dont know how can do it.
you can return response in select2 (controller function) required format
like
$final_array = [];
$ethnicity = DB::table("user")
->select("id","ethnic");
if ($request->search != '') {
$search = $request->search ;
$ethnicity=$ethnicity->where('ethnic','LIKE',"%$search%");
}
// loop the results to make response
foreach($ethnicity->get() as $key => $value):
$final_array[$key]['id'] = $value->id;
$final_array[$key]['text'] = $value->ethnic;
endforeach;
return ['results' => $final_array];
// function ends here
and select 2 tag in blade file like this
$('.ethnicity').select2({
placeholder: 'Select..',
ajax: {
url: '/select2-autocomplete-ajax_ethnicity',
minimumInputLength: 3,
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
return query;
}
}
});

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.

Dynamic dependent select option using AJAX and Laravel 5.8

I am actually trying to obtain a dynamic dependent select option for city based on region and in my controller i am returning a string(using echo) but unfortunately the string is not rendering in the select option(of cities) on the browser. but i can see it by inspection or by printing on the console.
my jquery:
<script >
$(document).ready(function(){
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#cityName').html(result);
console.log(result);
console.log(result);
}
})
}
});
$('#RegionName').change(function(){
$('#cityName').val('');
});
});
</script>
: my controller
class DynamicDependent extends Controller
{
public function fetch(Request $request)
{
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = city::where($select,$value)->get();
$output = '<option value="">Select '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
}
:no eroor message
Here is the picture of the actual outpout :
I suspect that the response might not be that well formed.
Try to return a proper response instead of echoing yourself.
// other code in the controller ...
return response()->json($output);
If it doesn't help, please include the actual response you get in the browser/console.
thanks. actually i was using bootstrap select library and there is a class called selectpicker when i removed this class from the select tag of city it worked fine

Symfony UserPassword validation in ajax form

I have a problem validating User Password in Symfony 2.4.
I have a form created with html code inside twig and i am not using form builder because i am submitting the form via ajax.
The form is a change password form and i have a password field which must match with the user passord.
Code:
Html.twig code of the form:
<form id="changePassword" name="changePassword">
<label id="labelPassword">Write your current password </label>
<input type="password" id="CurrentPassword" name="CurrentPassword" />
<label id="labelNewPassword">Write your new password </label>
<input type="password" id="NewPassword" name ="NewPassword" />
<label id="labelNewPassword2">Repeat your new password</label>
<input type="password" id="NewPassword2" name ="NewPassword2" />
<input type="submit" class="btn-primary btn" value="Change"/>
</form>
ajax code:
var ServerData;
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("name");
var id = $(this).attr("id");
if(validates(url)){
$.ajax({
url: url+"/" ,
method: "post",
dataType: "json",
data: data,
success: function (ServerData){
successFunction();
},
error: function (){
errorFunction();
}
});
}
else{
novalidFunction();
}
});
});
function validate(url){
//Just length and matching new password with repeat new password validations
}
// succesFunction(), errorFunction() and novalidFunction() and all this code are
//working great
php code of the controller:
public function changePasswordAction ($request Request){
$user= $this->getUser();
$password = $user->getPassword();
$currentPassword = $request->get("CurrentPassword");
$newPassword = $request->get("NewPassword");
//here is where i need the code to compare $password with $currentPassword;
//the problem is that $password is encoded
//then i got the code to insert new values in Users table and its working;
}
Thanks in advance and sorry about my english
i have resolved the problem:
Since you cant decode the user password you have to encode the new password. Here is the code to complete my last code:
public function changePasswordAction(Request $request){
$user = $this->getUser();
$upassword = $user->getPassword();
$password = $request ->get("CurrentPassword");
$newPassword = $request ->get("NewPassword");
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$salt = $user->getSalt();
$passwordSecure = $encoder->encodePassword($password, $salt);
$em = $this->getDoctrine()->getManager();
if ($passwordSecure == $upassword){
if($newPassword == $newPasswordtwo){
$newsalt = md5(time() * rand(1, 9999));//just a random number
$user->setSalt($newsalt);
$user->setPassword($encoder->encodePassword($newPassword, $newsalt));
$em->persist($user);
$em->flush();
return new \Symfony\Component\HttpFoundation\JsonResponse(array("estado" => "success", "msg" => "Password Changed"));
}
else{
return new \Symfony\Component\HttpFoundation\JsonResponse(array("estado" => "error", "msg" => "New password doesn't match in both fields"));
}
}
else{
return new \Symfony\Component\HttpFoundation\JsonResponse(array("estado" => "error", "msg" => "User password is not correct"));
}
}
That is working great for me. I hope that could help someone. :)

How can I refresh a select list with another

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.

Resources