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);
});
Related
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
});
}
});
I am trying to code a simple search functionality for learning purposes, but I am failing to make it work.
What I want for now is simply to pass some data(to a controller function) in a blade view with ajax and then display this data in another view via the same controller function.
What I currently have is this :
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$data = $request->data;
return view('search-results')->with('data',$data);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1>{{$data}}</h1>
#endsection
And finally the ajax :
var data = "success";
$.ajax({
url: 'search-results',
type: "get",
data: {data : data},
success: function(response){
if(data == "success")
console.log(response);
}
});
Can someone help me make this work? I am not sure what am I doing wrong...
You should return JsonResponse object to easy use data in JavaScript
Action:
public function search(Request $request){
$data = $request->data;
return new JsonResponse(compact('data'));
}
JavaScript:
$.ajax({
url: "/search",
type: "get",
data: {data : data},
success: function(response){
console.log(response);
}
});
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$result = [];
$result['data'] = $request->data;
return response()->json($result);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1 class="header"></h1>
#endsection
Ajax call :
var data = "success";
$.ajax({
url: "{{ route('search') }}",
type: "get",
data: {'data' : data},
success: function(response){
if(response.data == "success")
console.log(response.data);
$('.header').text(response.data);
}
});
Hope it's help you!!!
An AJAX call is asynchronous therefore you can make a call and return the results in a separate form. If you want to show your results in a separate form, i advise that you submit the form and then return the view with your data return view('search-results')->with('data',$data); or if you stick to an an ajax call, you return a response which will be sent to the form where the data was submitted from return response()->json(["data" => $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));
}
this is my controller:
public function index(Request $request)
{
$items = Post::latest()->paginate(5);
$cmnt = Comment::all();
return response()->json(array('posts'=>$items,'comment'=>$cmnt));
}
this my ajax request
function getPageData() {
$.ajax({
dataType: 'json',
url: "{{route('post_status.index')}}",
data: {page:1}
}).done(function(data){
manageRow(data.data);
});
}
function manageRow(data) {
console.log(data.comment);
}
why i am getting error ??
help me out of this plzz
laravel returns json by default if it doesn't return view, in your case index() should return:
return ['posts' => $items,'comment' => $cmnt];
also I don't think this is correct
{{route('post_status.index')}}
probably should be
{{ url('post_status/index') }}
You can use the type of response from the server.
function getPageData() {
$.ajax({
dataType: 'json',
url: "{{route('post_status.index')}}",
type: 'GET'
data: {page:1}
}).done(function(data){
manageRow(data.data);
});
}
function manageRow(data) {
console.log(data.comment);
}
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');
});