I am doing a search for a date in the database using ajax to call the function. The problem is that it gives me a 404 result when it should be showing it and the ajax enters in error mode.
controller code that works
[HttpPost]
public ActionResult SearchDate(DateTime date)
{
code...
return View(employees);
}
ajax code
function SearchByDate()
{
var x = document.getElementById("DateInputField");
if (x.value != "")
{
$.ajax({
url: '/Employees/SearchDate',
type: 'GET',
data: { "date": x.value },
error: function (data) {
alert('Error!');
},
succes: function (data)
{
alert('Succes!');
}
});
}
else
{
alert('Date not selected!')
}
}
I ran the program with breakpoints and it exits with the right result but it is showing none and in the developer console i get ERROR 404!Not found! and also the ajax returns alert error.Please help! Ty
Update after some issues where fixed i get this error:
The view 'SearchDate' or its master was not found or no view engine supports the searched locations!
There are multiple errors:
[HttpPost] at backend and you are sending a GET request.
404 means file is not found, so your path might be not correct.
succes callback should be success.
contentType is not set instead you can look into traditional:true,.
Use Query string in place of send data from data parameter.
changed type: 'GET',datatype: "html", then created a partial view rendered it inside and changed the function in controller to HTTPGET and returned partial view as result!
Related
Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.
I have searched and seen many solutions but yet I still am not getting any progress. I get no errors within the console and get nothing in return from the ajax request.
Here is action method code:
[HttpGet]
public ActionResult GetEmployees()
{
AWEmployeeModel aw = new AWEmployeeModel();
aw.ID = 0;
aw.Name = "Selena";
aw.Position = "Cashier";
aw.Department = "Finance";
return Json(aw,JsonRequestBehavior.AllowGet);
}
And here is my ajax call within my controller:
EmpApp.controller("AWEmpControl", function ($scope) {
loadEmployees();
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.employees = response["Name"];
}
});
}
});
I do also have the ng directives on the desired page:
<div class="container" ng-app="AWEmpApp" ng-controller="AWEmpControl">
{{employees}}
</div>
I tested to see if the scripts work fine by assigning $scope.employees = "Hello..."; and no problems, so I know it has nothing to do with script loading.... What could be the issue? I've made sure to describe the request as GET and to return a JSON object. Am I missing something?
Thanks in advance.
EDIT
I checked the firefox console and got back Parsing Error: No XML found at location.......
Which I found odd since the server returns a JSON object, so I replaced the ajax method with the following:
function loadEmployees() {
$http.get('/AWEmployee/Index/GetEmployees')
.then(function(response) {
$scope.employees =response;
});
};
Now response is html data of the page that called it (Index), instead of the JSON object ! I assume something is happening in between the communication as suggested in this post.
As you use JQuery to fetch data from server instead of $http service and moreover success function is executed asynchronous, AngularJS will not reflect any changes that was happened, to force it, just wrap assigning into $apply:
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.$apply(function(){
$scope.employees = response["Name"];
});
}
});
}
Found out the issue, it's a simple mistake on my part. I was calling http://localhost:53729/AWEmployees/Index/GetEmployees which was the wrong thing to do. I took out the Index page, so now the url looks like http://localhost:53729/AWEmployees/GetEmployees and it worked perfectly!
I'm quite new to MVC and I'm trying to call a method int one of my controllers.
<script>
function checkCardNumber() {
var content = $('#card-number').val();
var url = "AccountController/CheckRegisteredCard";
alert("content and URL are set");
$.post(url, { cardNumber: content }, function (data) {
alert(data);
});
alert("called outside of Post");
}
</script>
and here's the C# controller side:
[HttpPost]
public string CheckRegisteredCard(string cardNumber)
{
if (/*some condition*/)
{
return "";
}
else
{
return "some string";
}
}
both alerts("content and URL are set", "called outside of post") are being triggered, but the ajax part is not working at all. What am I doing wrong here?
If your controller class is called AccountController, the url should be /Account/CheckRegisteredCard.
Have you checked the network tab of your browser? I bet there's a 404 error.
If this snippet of javascript is in a .cshtml file, I would recommend using #Url.Action() to get the url string.
I would recommend using Fiddler and having that open when the ajax call is being made. This will tell you (1) if the call is being made at all or failing immediately, and (2) what kind of response you are receiving from the controller. Also agree with Jason P about how the url should be calling the controller.
I am using ckeditor in our project. passing that value in ajax post like
//$form is -> $('form') jquery object
$("#ajaxsubmitbutton").on('click', function () {
CKupdate();
$.ajax({
type: ($form.attr('method').toLowerCase() == 'post' ? 'POST' : 'GET'),
url: ($form.attr('action') == 'undefined' ? window.location : $form.attr('action')),
data: $form.serialize(),
success: function (data) {
// Use local eval, since it will work in this context
callbackFunction(data);
},
error: function () {
var data = "ajaxerror";
callbackFunction(data);
}
});
});
Ckeditor update code :
function CKupdate(){
for ( instance in CKEDITOR.instances )
CKEDITOR.instances[instance].updateElement();
}
$form.serialize having below value :
"Id=0&Title=dfg&ShortText=rer&CultureCode=en-US&StartDate=3%2F12%2F2014&EndDate=3%2F26%2F2014&Text=%3Cp%3Etest3%3C%2Fp%3E%0D%0A"
controller code :
public JsonResult Save(int id, string title, string shortText, string text, DateTime? startDate, DateTime? endDate, string cultureCode)
{
//process some operation
}
it throws some ajax error like " 500 -internal server not found". i don't know what is the real cause for this issue
may be the problem in serializing the form. any help on this.
I suspect that the tags are the issue here-
Assuming Asp.net MVC here you have two options-
Decorate your model property with the [AllowHtml] method (not sure how much of a pain it would be to convert your properties to a model here)
Put the [ValidateInput(false)] tag on your controller method
You may need to add the following tag to system.web in your config as well
<httpRuntime requestValidationMode="2.0"/>
You may also run into issues if your submit isn't a post in which case you'll want to add allowget to your return value.
Not sure if this is your issue without the full error but that is where I'd start. You may want to check the response in fiddler or firebug to see if you can get more information on that exception.
Hope that helps.
Earlier today I posted another post where #Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);
isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);
and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
if (!ModelState.IsValid)
{
throw new HttpException(400, "Client-side validation failed.");
}
if (string.IsNullOrWhiteSpace(website.URL))
{
throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
}
using (_session.BeginTransaction())
{
_session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
_session.Transaction.Commit();
}
return PartialView(ListPartialView, MapUserToViewModel);
}
// MyJs.js
$("#testform").live('submit', function () {
var test = { URL: $("#URL").val() };
$.ajax({
url: "/Dashboard/AddWebsite",
type: "POST",
data: JSON.stringify(test),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("TRIG");
$("#content").html(data);
},
error: function () {
alert("Error");
}
});
return false;
});
Thanks in advance!
In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).
Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.