Request gets overridden with other data - javascript

I'm trying to get data for autocomplete using laravel.
Controller:
public function collection_search(Request $request) {
$term = $request->search;
$serveurapObj = new Serveurap();
$result = $serveurapObj->collectionAutocomplete();
return response()->json($result);
}
Model:
public function collectionAutocomplete($term) {
$where= ['m.supprime'=>'0', 's.supprime'=>'0'];
return DB::table('serveuraps AS s')
->select(DB::raw('s.nom as hostname'))
->join('machines AS m','m.id','=','s.machine_id')
->join('typeserveurs AS t','t.id','=','m.typeserveur_id')
->where($where)
->where('hostname','like','%'.$term.'%')
->get();
}
View:
<div class="col-md-12">
<div class="form-group">
<label class="col-md-3 control-label">{!! __('script.serveur') !!}</label>
<div class="col-md-4">
<input class="form-control" type="text" name="serveur" id="relance-serveur" role="textbox" aria-autocomplete="list" aria-haspopup="true">
</div>
</div>
</div>
Jquery/Ajax:
$(document).ready(function () {
// relance serveur autocomplete textbox
$('#relance-serveur').autocomplete({
source: function (request, response) {
alert(request.term)
$.ajax({
url: '/scripts/relanceCollection/collection',
dataType: 'json',
data: {
search: request.term
},
success: function (data) {
response(data);
}
});
},
});
});
I'm getting error when accessing the search from js in controller.
Error:
I printed $request but it showed the json data from model. how would I get the search from js to controller so that I can search data based on that term ?

The key you are sending is search, not term. Either change your controller code to reflect that, or change the ajax data.
$.ajax({
...
data: {
→ search: request.term
},
...
});
public function collection_search(Request $request)
{
$term = $request->search; ←
...
}
$.ajax({
...
data: {
→ term: request.term
},
...
});
public function collection_search(Request $request)
{
$term = $request->term; ←
...
}

You aliased the wrong class. You don't want an instance of a Facade, ever. If you want an instance of something you want the underlying instance, not the facade.
use Illuminate\Http\Request;
Now, $request would be an instance of that class and not the Facade, Illuminate\Support\Facades\Request.

I got the result by adding $.map function in success function in JS. if anyone needs it, please refer below js code:
$(document).ready(function () {
var headers = {
'X-CSRF-TOKEN':'<meta name="csrf-token" content="{{ csrf_token() }}">'
};
// relance serveur autocomplete textbox
$('#relance-serveur').autocomplete({
source: function (request, response) {
$.ajax({
url: '/scripts/relanceCollection/collection',
data: {
term: request.term
},
headers: headers,
dataType: 'json',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.hostname,
value: item.hostname
};
}));
}
});
},
select: function (event, ui) {
$('#relance-serveur').val(ui.item.label); // display the selected text
return false;
},
minLength: 1
});
});

Related

Razor autocomplete doesen't work when submitted

I'm having some problem with the autocomplete on my Razor project. Everytime it returns me error/failure. Maybe it could be even a stupid thing but I'm new to ASP so it would be difficult for me to notice.
Javascript Code
$(function () {
$('#searchCliente').autocomplete({
source: function (request, response) {
$.ajax({
url: '/Index?handler=Search',
data: { "term": request.term },
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#idCliente").val(i.item.val);
$("#idFatt").val(i.item.val);
},
minLength: 3
});
});
Page Model Code
public IActionResult OnPostSearch(string term)
{
var clientefatt = (from cliente in this.context.Arc_Anagrafiche
where cliente.RagioneSociale.StartsWith(term)
select new
{
label = cliente.RagioneSociale,
val = cliente.IdAnag
}).ToList();
return new JsonResult(clientefatt);
}
HTML Code
<input asp-for="intervento.Cliente" class="form-control" id="searchCliente" />
<input asp-for="intervento.IdClienteFatturazione" class="form-control" id="idCliente" type="hidden" />
Perhaps the issue is related to the AntiForgeryToken, try to add the XSRF-TOKEN property in the request header before sending the Ajax request.
Please refer to the following samples and modify your code:
Add AddAntiforgery() service in the ConfigureServices method:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
In the Ajax beforeSend event, get the RequestVerificationToken from the hidden field, and set the request header:
#page
#model RazorPageSample.Pages.AutocompleteTestModel
<form method="post">
#Html.AntiForgeryToken()
<input type="text" id="txtCustomer" name="label" />
<input type="hidden" id="hfCustomer" name="val" />
<br /><br />
<input type="submit" value="Submit" asp-page-handler="Submit" />
<br />
</form>
#section Scripts{
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#txtCustomer").autocomplete({
source: function (request, response) {
$.ajax({
url: '/AutocompleteTest?handler=AutoComplete',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "prefix": request.term },
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
position: { collision: "flip" },
select: function (e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
}
Code in the .cshtml.cs file:
public IActionResult OnPostAutoComplete(string prefix)
{
var customers = new List<Customer>()
{
new Customer(){ ID=101, Name="Dillion"},
new Customer(){ID=102, Name = "Tom"},
new Customer(){ ID=103, Name="David"}
};
return new JsonResult(customers.Where(c=>c.Name.ToLower().StartsWith(prefix.ToLower())).Select(c=> new { label = c.Name, val = c.ID }).ToList());
}
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
}
Then, the screenshot as below:
Reference: jQuery AutoComplete in ASP.Net Core Razor Pages
Maybe you shall assign the ajax datatype property, and also change the "type" property from post to get, as below:
$.ajax({
url: '/Index?handler=Search',
data: { "term": request.term },
datatype: 'json'
type: "GET",
success: function (data) {
response($.map(data, function (item) {
return item;
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
Also in the Model code you can try one of the following,
as when returning json the JSONRequestBehavior property shall be specified as AllowGet:
return Json(new {clientefatt = clientefatt}, JsonRequestBehavior.AllowGet);
Change the Model code method's return type to JsonResult, as below
public JsonResult OnPostSearch(string term){
return new JsonResult(clientefatt);
}
Most probably the first options, since you're using .net core, will give you an error "ASP.NET Core - The name 'JsonRequestBehavior' does not exist in the current context"

Passing reference number to data controller

I am trying to pass my reference data to controller via ajax. The controller didnt receive the data that's why it cannot return query.
This is my button upon click:
$('#inquire_t tbody').on('click', '#mensahe', function () {
var refNumber = $(this).attr('value');
// console.log(refNumber);
getMessageThread(refNumber);
});//btn-message
this is my function:
function getMessageThread(refNumber) {
console.log('This is the reference number: ' + refNumber);
$.ajax({
url: "/getMessageThread",
type: "POST",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: refNumber,
dataType: "TEXT",
success: function (msg) {
}//each
});
}// getMessageThread
and this is my controller:
public function getAllMessage(Request $request) {
$refNumber = $request -> get('refNumber');
$messageThread = DB:: table('i_di_thread')
-> select('message')
-> where('refNumber', $refNumber)
-> get();
return view('showInquiries', ['messageThread'=> $messageThread]);
}
I wanted to get the refNumber value controller to use to my where query
Instead of using $(this).attr('value'), use $(this).val().
Link to API for .val()

jQuery autocomplete not working with JSON

I am trying to implement the jQuery autocomplete. I feel like everything is set up just fine, however It's not working.
SearchSkies method
public JsonResult SearchSkies(string query)
{
SkiDao skiDao = new SkiDao();
IList<Ski> skies = skiDao.SearchSkies(query);
List<string> brands = (from Ski s in skies select s.Brand).ToList();
return Json(brands, JsonRequestBehavior.AllowGet);
}
The script in View
<script type="text/javascript">
$( function() {
$( "#searchBox" ).autocomplete({
source: function( request, response ) {
$.ajax( {
url: '#Url.Action("SearchSkies","Skies")',
dataType: "json",
data: {
query: request.term
},
success: function (data) {
response(data);
}
} );
},
minLength: 2,
});
});
</script>
You are not mentioning type of request(GET/POST) in ajax call.
$(document).ready(function () {
$("#searchBox").autocomplete({
source: function(request,response) {
$.ajax({
url: "/Skies/SearchSkies",
type: "POST", <<----
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
And the controller
public class SkiesController : Controller
{
// GET: Home
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult SearchSkies(string query)
{
SkiDao skiDao = new SkiDao();
IList<Ski> skies = skiDao.SearchSkies(query);
List<string> brands = (from Ski s in skies select s.Brand).ToList();
return Json(brands, JsonRequestBehavior.AllowGet);
}
}

Mvc 5 ajax display collection doesn't work

I have class :
public JsonResult refreshMap(int time)
{
// Some code before
List<User> lista = new List<User>();
lista.Add(usr11);
lista.Add(usr22);
return Json(lista, JsonRequestBehavior.AllowGet);
}
And view :
<div id="PersonList"></div>
<input type="radio" name="time" value="5">Last 5min
<input type="radio" name="time" value="15">Last 15min
And the attached JS :
$(document).ready(function () {
$(':radio[name="time"]').change(function () {
$.ajax({
url: '/Connection/refreshMap',
cache: false,
dataType: "JSON",
data: {
time: $(':radio[name="time"]:checked').val()
},
success: function (data) {
$.each(data, function (index, value) {
$("#PersonList").append(value.Email);
});
}
});
return false;
});
});
And I want do this : when i checked radio I use method and I get data from controller and I want display this collection. But my function in ajax doesn't work. But when I return in method refreshMap only one object: [...] return Json(usr11, JsonRequestBehavior.AllowGet);
And if I change my ajax function like below, this work !
$(document).ready(function () {
$(':radio[name="time"]').change(function () {
$.ajax({
url: '/Connection/refreshMap',
cache: false,
dataType: "JSON",
data: { time: $(':radio[name="time"]:checked').val() },
success: function (data) {
$("#PersonList").append(data.Email +"</br>");
}
});
return false;
});
});
Have you idea what I can repair it?
data comes wrapped in 'd', by using $each you seem to enter the data object but in the second one it does not 'project' the values.
i usually do if(data.d){...} just to make sure the data will not shortcircuit my code, or the absence of it to be concrete.
Will also look at what type is 'Email' and how it serialised.

Ajax search - Laravel

I am trying to create a live search using jquery, ajax and laravel. I also use pjax on the same page, this might be an issue?. Quite simply it should query the database and filter through results as they type.
When using Ajax type:POST I am getting 500 errors in my console. I get zero errors using GET but instead of returning in #foreach it will a full page view (this might be because of pjax).
Where am I going wrong?
Route:
Route::post('retailers/{search}', array(
'as' => 'search-retailers', 'uses' => 'RetailersController#search'));
Controller:
public function search($keyword) {
if(isset($keyword)) {
$data = array('store_listings' => RetailersListings::search($keyword));
return $data;
} else {
return "no results";
}
}
Model:
public static function search($keyword)
{
$finder = DB::table('retailers_listings')
->Where('city', 'LIKE', "%{$keyword}%")
->orWhere('country', 'LIKE', "{$keyword}")
->orderBy('country', 'asc')
->get();
return $finder;
}
View (store.blade.php):
<div id="flash"></div> //loading
<div id="live"> // hide content
<div id="searchword"><span class="searchword"></span></div> //search word
<table class="table">
<tbody>
#foreach($store_listings as $store)
<tr>
<td></td> //echo out all fields eg: {{ $store->name }}
</tr>
#endforeach
</tbody>
</table>
</div>
Form:
<form method="get" action="">
<input type="text" class="search-retailers" id="search" name="search">
</form>
Ajax and JS:
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
var dataString = 'keyword='+ keyword;
if(keyword=='') {
} else {
$.ajax({
type: "GET",
url: "{{ URL::route('search-retailers') }}",
data: dataString,
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
Additional, Here is my controller for pjax, It is important to note I am using the view store.blade.php foreach in for the search and for this store listing.
public function stores($city)
{
$this->layout->header = $city;
$content = View::make('retailers.stores', with(new RetailersService())->RetailersData())
->with('header', $this->layout->header)
->with('store_listings', RetailersListings::stores($city));
if (Request::header('X-PJAX')) {
return $content;
} else {
$this->layout->content = $content;
}
}
Your route is Route::post('retailers/{search}', [...]) and there you go. You pass data to your ajax-call. In GET you get something like url?key=value but using POST the data are added to the request body not to the url.
Knowing this your route is no longer valid since it only looks up for retailers/{search} and not for retailers only (which is the url POST is using).
Well maybe it could help somebody.
As a first problem you are defining the route as POST and then in the ajax request the type GET so it would not work
Also when making POST request Laravel has the csrf check so in order to work, provide it. The js function will be like
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
if(keyword=='') {
} else {
$.ajax({
type: "post",
url: "{{ URL::route('search-retailers') }}",
data: {
'keyword': keywork,
'_token': '{{ csrf_token() }}';
},
dataType: 'html',
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
And you can test your PHP search method doing separate tests for it.

Categories