I have in my controller a function to make a search filter.
The search parameter is obtained from a select field of my twig template.
The selected option is passed to the controller to see where results are with that value.
The query result is returned in JSON format.
Controller:
public function categoryAction(Request $request)
{
$category = $request->request->get('category');
$contentCategory = $em->getRepository('MyAppBundle:Content')->findByCategory($category);
$filterContent = new JsonResponse();
$filterContent->setData([
'categoryResult' => $contentCategory
]);
return $filterContent;
}
Twig template:
$('#selectCategory').change(function() {
var optionSelect = $(this).val();
$.ajax({
url: '{{path('playlist_category') }}',
data: '&category='+optionSelect,
type: 'POST',
success: function(filterContent) {
},
error: function(e){
console.log(e.responseText);
}
});
});
How I can display the result returned in JSON in my function 'success'?
You should change your JS code to the following. I would rather user $.post than $.ajax. And don't forget to pass json as fourth arg.
$('#selectCategory').on('change', function () {
var optionSelect = $(this).val();
$.post("{{path('playlist_category') }}", {category: optionSelect}, function (res) {
console.log(res);
}, 'json');
});
Related
I have a problem.
I have an ajax call that have two data to send, one is a form serialized the other is a other variable, i don't know how to use the variables into the first data of ajax call ( the form serialized ) into PHP, how can i do this?
JS:
$.ajax
({
url: "/update",
type: "post",
data:
{
form: $("#formTeamLeaderProduzione").serialize(),
type: "TeamLeaderProduzione"
},
success: function (data)
{
alert(JSON.stringify(data))
},
error: function (msg)
{
alert(JSON.stringify(msg));
}
});
PHP:
Route::post('/update', function (\Illuminate\Http\Request $request)
{
$value = \Illuminate\Support\Facades\Input::get('form');
return response()->json($request->form->inputModificaNomeTeamLeaderProduzione1,200);
});
This is my anwser
Route::post('/update', function (\Illuminate\Http\Request $request)
{
parse_str($request->input('form'), $form);
return response()->json($form['inputModificaNomeTeamLeaderProduzione1'],200);
});
I use laravel and now I want to search from DB by ajax. It work but I want to show the result any where that I want not in the footer in current situation.
Do you now how get and show data in this section?
<script>
$(document).ready(function() {
src = "{{ url('/')}}/users/searchhistory";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 1,
});
});
</script>
And controller
public function autoComplete(Request $request) {
$query = $request->get('term','');
$products=User::where('fullname','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($products as $product) {
$data[]=array('value'=>$product->fullname,'id'=>$product->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
use json() in return statment of controller
public function autoComplete(Request $request)
{
//othercodes
return response()->json($data);
}
Then in your ajax result you have the proper json-formatted response
You can add data to html tag
$.ajax({
success: function(data) {
$.each(data,function(prodcut){
// now you have every product
use javascript append function to a add new element with this product data
});
}
});
JSON response is not populating in dropdown perhap query gat the result perfectly.
alert the success function i.e
alert(result.data);--[object object]
here is my html code
Jquery
function fillTransferJobPositionAreaDropDown( job_type_id,province_id,region_id,district_id,tehsil_id,uc_id, area_id) {
var loadDDUrl = baseApiUrl + "Employee/all_new_job_positions_area/"+job_type_id+"/"+province_id+"/"+region_id+"/"+district_id+"/"+tehsil_id+"/"+uc_id+"/"+area_id;
console.log(loadDDUrl);
debugger;
newJobPositionIDFld.empty();
newJobPositionIDFld.append($("<option />").val("0").text("Select New Job Position"));
newJobPositionIDFld.select2('val', '0');
var url = loadDDUrl;
$.ajax({
url: url,
accepts: 'application/json',
cache: false,
type : 'GET',
dataType: 'jsonp',
success: function (result) {
alert(result.data);
console.log(result.data);
// Handle the complete event
if(result.data == null) return;
$.each(result.data, function () {
newJobPositionIDFld.append($("<option />").val(this.job_position_id).text(this.job_position_id+'-'+this.job_name));
});
}
});
}//End Ajax call
PHP
$this->db->select('jp.job_position_id,jp.jobposition_title as job_name');
$this->db->from('job_positions jp');
$this->db->where('jp.job_type_id', $job_type_id);
$this->db->where('jp.province_id', $province_id);
$this->db->where('jp.region_id', $region_id);
$this->db->where('jp.district_id', $district_id);
$this->db->where('jp.tehsil_id', $tehsil_id);
$this->db->where('jp.uc_id', $uc_id);
$this->db->where('jp.area_id', $area_id);
$this->db->get()->row_array();
Your query returns a object, not an array of objects, so remove the loop:
success: function (result) {
newJobPositionIDFld.append($("<option/>").val(result.data.job_position_id).text(result.data.job_position_id+'-'+result.data.job_name));
}
I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that
I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.