A. Where I am so far successfully:
I have 3 divs"
NewAction
NewController
NewArea
I have an $.Ajax post with the url currently as follows
'#Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" })'
I have several pages that require this particular Ajax post so I put the Ajax post in a partial, and each main page that uses it, has a parameter in the partial call, eg:
#Html.Partial("_PartialPage", new [] { "NewAction", "NewController", "NewArea" })
The divs in #1 above are successfully populated dynamically with the string values in #3
B. Where my difficulty lies:
Despite many efforts & attempts, I cannot change the #Url.Action values in #2 to the values in the divs in #1.
I even tried to declare C# private variables and populate them with the foreach that populated the divs above and pass those values to the #Url.Action link, but I get a run error.
Does anyone know a way I can pass the parameter values in my partial call (#3) to the Url.Action method in the Ajax post in #2 above.
Thanks in Advance.
You could have a method that will extract the values that are passed to this strongly typed partial and build the url:
#model string[]
#functions {
public string GetUrl() {
if (Model != null && Model.Length > 2)
{
var values = new RouteValueDictionary();
values["controller"] = Model[0];
values["action"] = Model[1];
values["area"] = Model[2];
return Url.RouteUrl(values);
}
return Url.Action("CurrentAction", "CurrentController", new { area = "CurrentArea" });
}
}
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(GetUrl()));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
will render like this:
<script type="text/javascript">
var url = "/NewArea/NewAction/NewController";
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
But if you don't need those route values separately another possibility is to directly pass the entire url to the partial view:
#Html.Partial("_About", Url.Action("NewAction", "NewController", new { area = "NewArea" }))
and then inside the partial simply use it:
#model string
<script type="text/javascript">
var url = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
success: function(result) {
// ...
}
});
</script>
Related
I am new to AJAX and cant even get the basics to function correctly.
I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.
The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.
Razor Page:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Page Model:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
Below is the code that is now working for me. Thanks for everyone's input.
Razor Page (script section):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
Page model:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}
I've a view that recives parameters from the frontend via AJAX.
I've passing AJAX parameters in a maner, but this time my way didn't work.
I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work:
Why?
My friend's AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/?d_name=" + val_d + "&p_name=" + val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
</script>
My AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
d_name: val_d,
p_name: val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
});
</script>
View
def get_district(request):
d_name = request.GET.get("d_name")
p_name = request.GET.get("p_name")
data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True)
# data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True)
return render(request, "accounts/district_dropdown.html", {
"districts": set(list(data))
})
You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect.
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
data: { // Pass parameters in separate object
d_name: val_d,
p_name: val_p
},
}).done(function (result) {
$("#id_shipping_district").html(result);
});
The data object is converted into a query string and appended to the URL.
In your friend's case, they are building up the query string manually when they create the URL - hence their version works.
I have this ajax inside my file.php (It hits the success callback):
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
console.log(data);
}
});
})
</script>
Now on my Controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));
}
What I want to do:
I have a LIST with professor and their disciplines. What I need to do is:
Whenever I change the value of that select box, I just remake the function with the new parameter.
I'm trying to use ajax to remake that list but nothing change, not even the URL with the professor.php?anoSemestre=xx.
Also, when I try to use the $_GET['anoSemestre'] the page doesnt show any change or any ECHO.
But If I go to Chrome spector>NEtwork and click the ajax I just made, it shows me the page with the data I sent.
Cant find out what I'm doing wrong.
UPDATE
I did what was suggested me, now I'm working with the data I get from the success callback:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(data){
var lista = $(data).find('#list-professores'); //Get only the new professor list and thier disciplines
$('#list-professores').remove(); //Remove old list
$('#professores').append(lista); //Append the new list where the old list was before.
}
});
})
</script>
The return of var lista = $(data).find('#list-professores'); is:
Accordion Effect
#list-professores li input[name='item']:checked ~ .prof-disciplinas {
height: auto;
display:block;
min-height:40px;
max-height:400px;
}
This list is an Accordion Menu (using a checkbox and changing it with js&css), so everytime I click on a professor < li>, it's suppose to open and show a sublist (disciplines of that professor I clicked). But it's not opening anymore and no errors on the console. No idea why.
The issue here is what you are returning in your controller and how you do it, you donĀ“t need to redirect or refresh the entire page. This could be achived using a single blade partial for the piece of code you may want/need to update over ajax. Assuming you have an exlusive view for that info, you could solve this with something like this:
in your view:
<div class="tableInfo">
<!--Here goes all data you may want to refresh/rebuild-->
</div>
In your javascript:
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: {anoSemestre: anoSemestre},
success: function(){
$('.tableInfo').html(data); //---------> look at here!
}
});
})
</script>
in your controller:
public function getProfessorList()
{
$professor = Professor::all();
$ano_semestre = isset($_GET['anoSemestre']) ? $_GET['anoSemestre'] : Horario::first()->distinct()->pluck('ano_semestre');
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
if (Request::ajax()) {
return response()->json(view('YourExclusiveDataPartialViewHere', ['with' => $SomeDataHereIfNeeded])->render()); //---------> This is the single partial which contains the updated info!
}else{
return View::make('professor', compact('professor', 'semestres', 'ano_semestre'));//---------> This view should include the partial for the initial state! (first load of the page);
}
}
$("##ViewBag.PageGroupID").append(data);
Now ViewBag.PageGroupID returns the id of the div at runtime.What if i want to append data in the div(the id which i will get runtime).How do i acheive this?
$('#btnPageElementClick').click(function () {
var flag = false;
var b;
$.ajax({ type: 'GET', url: '/ScriptedTestCase/pageElementPV/' + $('#PageElements').val(), data: null,
success: function (data)
{
$("##ViewBag.PageGroupID").append(data); //where divID is the id of the div you append the data.
}
});
return false;
});
Make sure that inside the controller action that rendered the view that contains the script you have shown, you have actually set this data:
ViewBag.PageGroupID = "someDivId";
Also note that in HTML ids cannot start with numbers.
I am trying to call a controller via ajax without to much luck.
I have create this in my view
<input type="submit" id="preview-email" value="Preview Email" />
<script type="text/javascript">
$("#preview-email").click(function () {
var p = { "email": "1223" };
$.ajax({
url: '/BusinessController/PreviewEmail',
type: "POST",
data: p,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
});
</script>
My controller
[HttpPost]
public ActionResult PreviewEmail(string email)
{
// string d = ViewData["editor"].ToString();
string e = System.Web.HttpUtility.HtmlDecode(email);
EmailModel model = new EmailModel() { EmailBody = e };
return PartialView("_PreviewEmail", model);
}
Turning on fiddler is telling me that its a 500 error. What have I done wrong? I've placed a breakpoint on my controller however it doesnt get that far
Your URL should be:
'/Business/PreviewEmail'
instead of:
'/BusinessController/PreviewEmail'
However, the recommended practice for building URLs is to use your routes:
Url.Action("PreviewEmail", "Business")
BTW, you have another problem in your code. By setting "application/json" as your contentType, MVC will expect a JSON string. However, when you assign a JavaScript object to the data property of $.ajax(), jQuery will serialize the value to this:
email=1223
So you'll want to assign a string to the data property instead by doing this:
var p = '{ "email": "1223" }';
#Url.Action doesn't work inside the JS file. What if my call to Controller/Action is inside JS file?
For now I'm, retrieving the location.href and then replacing the Action name.
(This may not be a wise thing to do)