Basically I'm trying to pass the value of my dropbox to a get action.
The submit-button re-directs to the correct action , but what is the correct way to add the value of the dropbox with the re-direction?
My view:
#model TrackerModel
#using (Html.BeginForm("MyAction", "MyController", FormMethod.Get, new { ???}))
{
<div>
<strong>#Html.LabelFor(m => m.CustomerName)</strong>
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #class = "customer-picker" })
</div>
<button class="styledbutton" onclick="window.location.href='/Tracker/Index'">Cancel</button>
<button type="submit" value="submit" id="selectCustomer-button" class="styledbutton">Submit</button>
}
[HttpGet]
public ActionResult MyAction(IPrincipal user, Tracker model)
Customer-picker
$(document).ready(function () {
CustomerPicker();
});
function CustomerPicker() {
$('.customer-picker').select2({
placeholder: 'Select customer',
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: '/JsonData/GetCustomers',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
query: term // search term
};
},
results: function (data) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return { results: data };
}
},
formatResult: function (data) {
return data;
},
formatSelection: function (data) {
return data;
}
});
}
I was expecting the value to be within my Tracker model parameter in the action, but this returns nulls. Also I'm not sure what to place in the "new" parameter in the form tag?
I also tried the following but all I get returning to the controller is text:"".
#Html.TextBoxFor(m => m.CustomerName, new { type = "hidden", #id = "selectedCustomer", #class = "customer-picker" })
<script type="text/javascript">
$(function () {
$("#Form1").submit(function (e) {
alert("boo");
e.preventDefault();
var selectCustValue = $("#selectedCustomer").val();
$.ajax({
url: '/CalibrationViewer/SentMultipleCalsToCustomer',
data: { text: selectCustValue }
});
});
});
OK got it,
var selectCustValue = $("#s2id_CustomerName span").text();
Found another piece of code the used the customer-picker and the javascript associated with view used the above.
I viewed the page source and it still show's both id and name as CustomerName, it has something to do with the "Select 2" helper.
I may get slated for marking this as the answer, considering I should have figured it out earlier, but there you have it !
Related
I am working on Symfony 4.4.
To refresh a table, users select three options with an input:
InProgress
Finished
All
Then they must press a validate button.
I want to improve the use of this page by automating the refresh of the table.
Currently on my model I have AJX which allows me to retrieve the value of my entry:
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data[$field.attr('name')] = $field.val()
console.log(data)
// On soumet les données
// $.post($form.attr('action'), data).then(function (data) {
// // On récupère le nouveau <select>
// $('#planningsms_client_label').val($(data).find('#planningsms_client option:selected').text());
// let $input = $(data).find(target)
// // On remplace notre <select> actuel
// $(target).replaceWith($input)
// })
});
</script>
I am now stuck because I cannot figure out how to get information back to my Controller, allowing me to modify a PreSelect variable with the value of the input and change the structure of the SQL query.
Create a route? Call a route in an Ajax POST?
Use this route in my Controller?
I think it's more or less that, but on the other hand I have no idea how to implement it.
EDIT :
It has moved forward a bit.
I manage to recover the data of the change of the input in my controller.
On the other hand I try to recall the function which will allow me to make a new SQL query with the selected filter, but that does not seem to work.
Ajax :
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data['isAttending'] = $field.val()
console.log(data)
$.ajax({
type: "POST",
url: "/campagnestel/ajax",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
</script>
And function in my controller :
/**
* #Route("/ajax", methods={"GET", "POST"})
*/
public function testAjax(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array(
'status' => 'Error',
'message' => 'Error'),
400);
}
if(isset($request->request)) {
$preSelect = $request->request->get('isAttending');
return $this->queryFollowingFilter($preSelect);
}
// return $this->queryFollowingFilter($preSelect);
return new JsonResponse(array(
'status' => 'OK'),
200);
}
Error :
The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned an array
As the error message states:
The controller must return a "Symfony\Component\HttpFoundation\Response" object
A JsonResponse meets that requirement and suits your needs. Try this:
if($request->request->has('isAttending')) {
$preSelect = $request->request->get('isAttending');
return new JsonResponse(
$this->queryFollowingFilter($preSelect),
200
);
}
This is the view, the success function should make changes in the <p id="mondiv"></p>tags.
<input type="button" value="Refuser" class="refuser" id="{{ demande.id }}">
<p id="mondiv"></p>
<script>
$(".refuser").click(function () {
$.ajax({
url: '{{ path('verifier_demandes') }}',
type: 'POST',
data: {'id_demande': this.id},
dataType: 'json',
success: function (data) {
$.each(data,function (i,e) {
$('#mondiv').append('<ul>'
+'<li>'+e.id+'</li>'
+'<li>'+e.etat+'</li>'
+'<li>'+e.user.nom+'</li>'
+'<li>'+e.user.prenom+'</li>'
+'<li>'+e.user.username+'</li>'
+'</ul>');
})
},
error: function(data) {
alert('error');
}
})
}
);
This is the controller, the entity gets deleted like intended but since then i can't change my view element ( the success function )
if($request->isXmlHttpRequest())
{
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
$gerant = new Gerant();
$gerant = $em->getRepository("GestionBoutiquesBundle:Gerant")->findOneBy(array('id' => $id_gerant));
$em->remove($gerant);
$em->flush();
$demandes = new Gerant();
$demandes=$em->getRepository('GestionBoutiquesBundle:Gerant')->findBy(array('etat'=>false));
$ser= new Serializer(array(new ObjectNormalizer()));
$data=$ser->normalize($demandes);
return new JsonResponse($data);
}
}
I have looked from both sides, the controller sending back the Json response, and from the view, but couldn't find any result.
EDIT: knowing that the $demandes i'm trying to send back with Json is an array of users, each user has an id, etat, nom, prenom, username..
You made a POST request so you should be able to access to the post data as follow:
$id_gerant = $request->request->get('id_demande');
if($id_gerant) {
....
instead of:
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
....
As described here in the doc Symfony Request Object
Hope this help
Implementing the auto save functionality for my page. so after certain interval calling action Autosave(). But my page having begin form including the Partial view. The code for after interval call is working fine.
<script type="text/javascript">
window.setInterval(function () {
var form = $("#addpost");
$.ajax({
url: '#Url.Action("AutoSavePostAction", "MyControllerName")',
data: form.serialize(),
type: 'POST',
success: function (data) {
$("#Id").val(data);
}
});
}, 30000);
View is :
#using (Html.BeginForm("SavePostAction", "MyControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id="addpost" }))
{
.................
#Html.Partial("_TextPostPartial", Model);
.................
}
SavePostAction is after calling submit. On this submission, getting the value from Partial view, which is not an issue.
But in ajax call somehow partial view does not included in serialization.
Here _TextPostPartial having CKEditor which is strongly bind with Model.
Like Partial view having :
<textarea id="Description" name="Description">#Html.Raw(Model.Description)</textarea>
Edited:
[HttpPost]
public ActionResult AutoSavePostAction(PostDTO postDTO, FormCollection postFormCollection)
{
}
[HttpPost]
[MemberFunction]
public ActionResult SavePostAction(PostDTO postDTO, FormCollection postFormCollection)
{
}
You need to assign the value of the CKEditor to the input before serializing the form data
window.setInterval(function () {
$("#Description").val(CKEDITOR.instances['Description'].getData()); // add this
var form = $("#addpost");
$.ajax({
url: '#Url.Action("AutoSavePostAction", "MyControllerName")',
data: form.serialize(),
type: 'POST',
success: function (data) {
$("#Id").val(data);
}
});
}, 30000);
I am trying to get the state code to be followed by a dash and the state name using an ajax autocomplete syntax. I'm using jQuery and jQueryUI and the jQueryUI autocomplete function to attempt this.
I am using this json result:
[{"code":"AK","name":"Alaska"},{"code":"AL","name":"Alabama"},
{"code":"AR","name":"Arkansas"},{"code":"AZ","name":"Arizona"},
{"code":"CA","name":"California"}, ... ]
And I'm using this jQuery ajax call with an embedded
$.ajax({
url: '/Cats/State/List',
type: 'POST',
dataType: 'json',
success: function (data) {
$('#Cat_stateCode').autocomplete(
{
source: data.code + '-' + data.name,
minLength: 2
});
}
});
The mvc controller JSON Result looks like this:
public JsonResult List()
{
return Json(db.States.ToList(), JsonRequestBehavior.AllowGet);
}
How do I get the auto complete to show:
CA - California
CO - Colarado
If I type out C? Or does Autocomplete only work with simple json like {"AK", "AL", "AR" ... }?
Figured it out:
$("#Cat_stateCode").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Cat/States/List",
dataType: "json",
data: {
style: "full",
maxRows: 12,
req_state_part: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.code + ' - ' + item.name,
value: item.code
}
}));
// alert("data.code:" + data);
},
error: function (e) {
alert("e.error:" + e.error);
}
});
},
minLength: 1,
select: function (event, ui) {
//alert("ui item:" + ui.item ? "Selected: " + ui.item.label : "Nothing selected, input was " + this.value); //todo: remove after dev
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
In my mvc CatStateController I have this:
public JsonResult List(String stateAbbreviation)
{
String StateNameORStateCodeContains = Request.Params["req_state_part"];
return Json(db.States.Where(state => state.name.Contains(StateNameORStateCodeContains) || state.code.Contains(StateNameORStateCodeContains)).ToList(), JsonRequestBehavior.AllowGet);
}
So it looks like it doesn't sent the term over, it only send over some params you make up in the data element. Since you can make up pretty much anything its up to the developers imagination. One thing I was trying to do was create a closure b/c I have a lot of different animals with different states. And I need to create this same autocomplete function for each of them. So I need to ask another question how do you remove the auto complete so I can call that same function from many different ids, or do I just separate them out with a comma like so:
$("#Cat_stateCode,#Dog_stateCode,#Penguin_stateCode...").autocomplete({ ... ???
And I believe the answer to the second part is in here. I think its insinuating just add some class or attribute to the applicable input tags and then just perform an each over them and them lastly apply the autocomplete to the $(this).autocomplete immediately after each each iteration occurs.
Found a better way with just set the input tag to have a class="cssClassName". Had to use the TextBoxFor:
#Html.TextBoxFor(model => model.Cat.stateCode, new { #class = "StateCodeAutoComplete" })
I have below ajax query which returns me json from controller
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=1",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
the controller action is as below
[System.Web.Http.ActionName("GetHomeTab")]
public HomeTabModel GetHomeTab(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new HomeTabModel
{
HomeDesc = outlet.BizHomeDesc,
HomeTabText = outlet.BizHomeTabText
};
}
Now my question is: curently i am sending hard coded value of bizId to web api. I want to send this value dynamically. How can i achieve this? I have that value in my route config file. The code is as below-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = 1 }
);
}
I am new to this. Please help! Thanks in advance!
no, actually after much research, i came up with this solution and this works fine for me....
In controller,
public ActionResult Index(int bizId)
{
ViewBag.BizId = bizId;
return View();
}
and in View,
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=#ViewBag.BizId",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
You can pass a data object as part of the GetJson call.
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab",{bizId : 1},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
Taking this one step further you could wrap this in a function.
function makeCall(id)
{
$.getJSON("api/OutletPOC/GetHomeTab",{bizId : id},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
}
Also look into using promises.
$.getJSON().then().done();