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.
Related
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
});
});
I have the following HTML multi-select code:
<select class="multi-select" multiple="multiple" id="multiSelectId">
And am trying to dynamically add elements into it using ajax:
function TestFunction(value) {
const selectMembers = $("#multiSelectId");
selectMembers.empty();
selectMembers.append('<option value="val">test1</option>');
$.ajax({
url: '#Url.Action("GetMemberById", "SystemAdmin")',
data: {
'memberId': value
},
success: function(data) {
selectMembers.append('<option value="val">test2</option>');
alert("test3");
}
});
selectMembers.multiSelect('refresh');
}
So the weird thing is, that test1 and test3 are working fine, whereas test2 doesn't work at all and I can't find why it doesn't work. Does anybody has an idea?
You need to refresh in the success callback handler. Remember ajax() is asynchronous.
function TestFunction(value) {
const selectMembers = $("#multiSelectId");
selectMembers.empty();
selectMembers.append('<option value="val">test1</option>');
$.ajax({
url: '#Url.Action("GetMemberById", "SystemAdmin")',
data: {
'memberId': value
},
success: function(data) {
selectMembers.append('<option value="val">test2</option>');
selectMembers.multiSelect('refresh');
alert("test3");
}
});
}
I have placed a bootstrap toggle switch in my application
Now i want is to send the On and Off values to my action method
Bellow is my razor syntax
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>}
For passing data to controller from JS i have searched many articles and found that ajax is the way to do it
Bellow is my script for ajax inside JS
<script>
var cmdName = '#Session["cmdName"]';
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'On',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'Off',
success: function () {
alert(data)
}
});
}
}); </script>
I have also used session variable but getting null value in it
Bellow is my controller code
public ActionResult MultiGraph(string search, string start_date, string End_date, string cmdName, int? page)
{
//search contain serial number(s)
//cmdName is for input checkbox
}
Bellow is the image for my switch button
When i switch it to Off then this Off string should be sent to my action method and vise versa
Updated Code
After reading comments i have done the following changes to my code
I have added a new action method of type Post
[HttpPost]
public ActionResult ToggleSwitch (string search, string cmdName)
{
List<SelectListItem> items = new List<SelectListItem>();
var dtt = db.ADS_Device_Data.Select(a => a.Device_Serial_Number).Distinct().ToList();
foreach (var item in dtt)
{
if (!string.IsNullOrEmpty(item))
{
items.Add(new SelectListItem { Text = item, Value = item });
}
}
ViewBag.search = items;
return View();
}
Bellow are changes in my razor
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "Off"}',
success: function () {
alert(data)
}
});
}
});
But still i get no alert message, when i inspect element i found this error
I am stuck to this problem from almost 2 days
Any help would be appreciated
You need to use the $ character to invoque jQuery functions and pass your data from page to controller with the same name you defined in the action method using Json notation:
'{"cmdName": "On"}',
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
Furthermore, you might need to decorate your mvc action whith the [HttpPost] attribute.
I am attempting to use an AJAX call to render a partial view when a radio button is selected. I have searched and have tried what appears to be the best approach via comments on Stack. When I click the radio button, I have no result, in debug, I get a Status Code: 500 Internal Server Error? Any assistance would be great.
Partial View Names:
_BOA.cshtml
_TA.cshtml
_MNB.cshtml
View:
<td class="radio-inline">
#Html.RadioButton("bankSelect", "MNBConvert", false, new { #class = "radioMNB" }) MNB Conversion
#Html.RadioButton("bankSelect", "BOAConvert", false, new { #class = "radioBOA" }) BOA Conversion
#Html.RadioButton("bankSelect", "TAConvert", false, new { #class = "radioTA" }) TA Conversion
</td>
Javascript:
<script src="~/Scripts/jquery-1.9.0.js"></script>
<script type="text/javascript">
$(function () {
$("[name=bankSelect]").on('change', function () {
// var $radio = $(this);
var checked = $("input[name='bankSelect']:checked").val();
$.ajax({
url: '#Url.Action("GetBankToConvert", "Home")',
data: checked,
type: 'GET',
success: function (data) {
$("#renderPartialView").html(data);
}
});
});
});
</script>
Controller:
[HttpGet]
public ActionResult GetBankToConvert(string bankSelect)
{
if (bankSelect == "MNBConvert")
{
return PartialView("_MNB");
}
else if (bankSelect == "BOAConvert")
{
return PartialView("_BOA");
}
else
{
return PartialView("_TA");
}
}
You aren't sending a key/value pair as data, only a value.
Try
$.ajax({
url: '#Url.Action("GetBankToConvert", "Home")',
data: {bankSelect: checked },
type: 'GET',
success: function (data) {
$("#renderPartialView").html(data);
}
});
WHen in doubt, inspect the actual request in network tab of browser dev tools to see exactly what is sent and received among all the other components of a request
I'm trying to get the remote using json from one php page,the JSON data:
[{"id":"0","name":"ABC"},{"id":"1","name":"DEF I"},{"id":"2","name":"GHI"}]
and the script is like this:
$(document).ready(function() {
$('#test').select2({
minimumInputLength: 1,
placeholder: 'Search',
ajax: {
dataType: "json",
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
term: term
};
},
type: 'GET',
results: function (data) {
return {results: data};
}
},
formatResult: function(data) {
return "<div class='select2-user-result'>" + data.name + "</div>";
},
formatSelection: function(data) {
return data.name;
},
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"name":elementText});
}
});
});
It works fine but it always reads the database whenever I typed one new character to search
. So i decided to use the another way (retrieve all data at first time and use select2 to search it):
$(document).ready(function() {
$("#test").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};}
},
multiple: false,
data: [{"id":"0","text":"ABC"},{"id":"1","text":"DEF I"},{"id":"2","text":"GHI"}]
});
});
But the problem is how can I pass a request to data_json.php and retrieve data from it?
Say
data: $.ajax({
url: "subject/data_json.php",
data: function (term, page) {// page is the one-based page number tracked by Select2
return {
college: "ABC", //search term
};
}
dataType: "json",
success: function(data){
return data
}
}
But its not working, can anyone help?
Thanks
Why did you move away from your original code?
minimumInputLength: 1
Increase this and the search won't be called on the first character typed. Setting it to 3 for example will ensure the ajax call isn't made (and the database therefore not queried) until after the 3rd character is entered.
if I understood your question correctly you have data_json.php generating the options for select2 and you would like to load all of them once instead of having select2 run an ajax query each time the user inputs one or more characters in the search.
This is how I solved it in a similar case.
HTML:
<span id="mySelect"></span>
Javascript:
$(document).ready(function () {
$.ajax('/path/to/data_json.php', {
error: function (xhr, status, error) {
console.log(error);
},
success: function (response, status, xhr) {
$("#mySelect").select2({
data: response
});
}
});
});
I've found that the above does not work if you create a <select> element instead of a <span>.