HI i have the bleow json code to validate a form when data is enetred wrong, if the data is enetered wrong more than once when create button is clicked it appends all the data again and still has the first set of errors, is there a way to remove the current errors and replace them with updated ones when the button is clicked?
function CreateChild() {
$("#formErrors").remove();
$.ajax({
type: "POST",
contentType: "application/json",
url: rootURL,
dataType: "json",
data: formToJSONCreate(),
success: function (data, textStatus, jqXHR) {
alert('Child Added Succesfully');
clearCreateForm();
displayList();
},
error: function (jqXHR, textStatus, errorThrown) {
var errors = JSON.parse(jqXHR.responseText).ModelState
var errorText = Object.keys(errors).map((key) => errors[key])
console.log(Object.keys(errorText))
$('#formErrors').append(errorText.join(' <br>'))
}
});
}
To achieve that, simply use .html() instead of .append()
$('#formErrors').html(errorText.join(' <br>'));
See http://api.jquery.com/html/ for details of this method.
Related
In my Asp.net Project and in Controller with name 'AjaxController' I have this Action Method:
[HttpPost]
public ActionResult GetList(int year)
{
var res="";
// some codes
return Json(res);
}
And in Js file :
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: 2000,
async: false,
success: function (response) {
// some codes
},
error: function (xhr, status, error) {
alert(error);
},
});
I expect that this method ONLY called with 'POST' but when I check My logs I will see some errors like:
AbsoluteUri :https://example.com/Ajax/GetList/
* Message :A public action method 'GetList' was not found on controller 'Controllers.AjaxController'.
That shows Called as 'GET', NOT 'POST'.
What and where is problem?
Thancks In Advanced
Couple of suggestions from my end -
Remove contentType and async attributes unless really required
Pass JSON object to 'data'
Also, use debugger and breakpoints generously to figure out yourself where your code is going astray
$.ajax({
url: '/Ajax/GetList/',
type: "POST",
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {year: 2000},
//async: false,
success: function (response) {
debugger;
// some codes
},
error: function (xhr, status, error) {
debugger;
alert(error);
},
});
I am trying to send data from my javascript to an aspx webmethod with ajax. the Success option of ajax post is fired but my web method never getting called.
the javascript code is:
$.ajax({
type: "POST",
url: '../About.aspx/GetWFData',
data: "{sendData: '" + 5 + "'}",
async: true,
success: function (result) {
alert("Bravo");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
and the webmethod in the code behind is:
[WebMethod]
public static string GetWFData(string sendData)
{
return String.Format("Hello");
}
Try to use below code to see if it works.
var params = '{sendData:' + values + '}';
$.ajax({
type: "POST",
url: '../About.aspx/GetWFData',
data: JSON.stringify(params),
async: true,
success: function (result) {
alert("Bravo");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
});
And refer to http://elegantcode.com/2009/02/21/javascript-arrays-via-jquery-ajax-to-an-aspnet-webmethod/ for more info. Try to disable request validation on a page.http://www.asp.net/whitepapers/request-validation
I am calling a handler through a AJAX call .
code
var PostData = {"MyName": myName };
$_.ajax(
{
type: "POST",
async: true,
url: 'SomeGenericHandler.ashx',
data: JSON.stringify(PostData),
success: function (msg)
{
var ObjJson = eval(msg);
},
error: function (msg)
{
}
});
Inside ProcessRequest ,these values i am getting :
context.Request.Form.Count = 1
context.Request.Form[0] = "{'MyName':'dave'}"
context.Request.Form["MyName"] = null
How can get the posted data as :
context.Request.Form["MyName"] = "dave"
Thanks in advance :)
You need to send the data in the format of the post as:
$_.ajax(
{
type: "POST",
async: true,
url: 'SomeGenericHandler.ashx',
data: 'MyName=dave&MoreData=SecondName',
success: function (msg)
{
var ObjJson = eval(msg);
},
error: function (msg)
{
}
});
Also take a look at the encodeURIComponent, you may need to encode the parameters :
Combining two Javascript and jQuery scripts
I've googled many similar situations, but none of them could solve my problem. Please take a look at my code:
JavaScript:
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: {request:'BasicGpaInfo'},
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});
ASP.NET:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["request"] == "BasicGpaInfo")
{
Response.Write(BasicGpaInfo());
}
else
{
Response.Write("Nothing");
}
}
This always returns "Nothing" and break point tells that Request.Form is null. And I have tried with GET and Request.QueryString which gives the same situation.
I guess there's something wrong with data in ajax function and I've tried with the following things that won't help:
data: $.param({request:'BasicGpaInfo'})
data: "{request:'BasicGpaInfo'}"
data: {request:'BasicGpaInfo'}
It won't work on all Web Browsers.
Please give some advice. Thanks!
I tested your code and it runs fine. However it always returns "Error in loading alarm information!" because you are not returning Json from the server.
Javascript is fine, once you return json, it will go into success.
You are returning the whole page, and your ajax method is getting the whole html instead of Json from BasicGpaInfo()
try putting a breakpoint in alert, and you will see all the data come inside data
error: function (data) {
alert("Error in loading alarm information!");
}
alternatively try
error: function (data) {
alert(data);
}
Here is the full code
$.ajax({
type: 'POST',
url: 'Default.aspx/BasicGpaInfoWebMethod',
data: { request: 'BasicGpaInfo' },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("Error in loading alarm information!");
//alert(data); // uncomment to see the whole response
}
});
and your webmethod will be :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string BasicGpaInfoWebMethod(string request)
{
return request;
}
Try this JSON.stringify before post. For using JSON.stringify in IE<=7 include json2.js file from json.org
$.ajax({
type: 'POST',
url: 'alarmInfo.aspx',
data: JSON.stringify({ request: 'BasicGpaInfo'}),
dataType: "json",
success: function (data) {
alert(data);
},
error: function () {
alert("Error in loading alarm information!");
}
});
I have the following Javascript function that makes a call to an Asp.Net WebMethod that returns true if a username already exists and false if it does not.
The following will give me the correct answer in an alert box but if I change the
alert(result.d) to return result.d
the result of the function is always undefined.
How can I get the function that the Ajax call is contained in to return a value based on the response from the WebMethod?
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: function (result) {
alert(result.d);
},
error: function (err) {
alert(err);
}
});
}
The thing to note is that the ajax function is non blocking. You specify two callback functions, one for success and one for error, one of these functions will get executed when the underlying request is finished.
Your doesEnteredUserExist does not wait for the ajax call to complete, and thus, the return value of the function is undefined.
The proper way to continue execution based on the result of your call is to break your functionality out into a separate function, and call that from your success function.
Ajax is asynchronous so once the function "doesEnteredUserExist" returns, the ajax call is not yet finished. Then later in the success callback you have the value. From there you should continue with your code and display the info to the user.
Store the value of result.d in a variable, then use it for whatever you would like.
Change this:
success: function (result) {
alert(result.d);
},
to this:
success: function (result) {
var resultString = result.d;
},
Now whenever you need result.d, just use the variable resultString. Basically, the ajax call is the only thing that can call the function that you wanted to return the value for, so you need to store that value when the function is called.
Maybe give this a bash
function onSucess (data) {
alert(data.d);
}
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: onSucess,
error: function (err) {
alert(err);
}
});
}
I am guessing that you are trying to set result.d which is out of scope from the call which is why the alert (result.d) works as its in scope.
I may be getting the wrong end of the stick, you could use a global variable (not recommended), set that in the ajax return which you could then read from your function.
May need a bit more info or clarity on what your trying to achieve, as I read the question a couple of ways.
I normally do this (havent tested this):
function ajaxLoad(callback)
$.ajax({
type: 'POST',
async: true,
url: 'url.aspx',
data: d,
cache: false,
contentType: 'application/json',
dataType: 'json',
error: function (xmlHttpRequest, textStatus, errorThrown) {
//error stuff
},
success: function (data) {
if (typeof callback == 'function') { [callback(data)]; }
}
});
}
function callback(data)
{
alert(data);
}
call the function using
ajaxLoad('callback');
something like that!
Inside your success callback function if you return some value it doesn't set the return value for it's parent function. In this case the parent function is $.ajax and it always returns a jqXHR deferred object.
If you are using jQuery 1.5 or later the you can use deferreds. The idea is to save the jqXHR object returned from the AJAX request and wait for it to complete before returning it's value:
var jqXHR = $.ajax({...});
$.when(jqXHR).then(function (result) {
return result.d
});
Docs for $.when(): http://api.jquery.com/deferred.when
An example of doing this would be to return the jqXHR object from your function and then wait for the AJAX request to resolve outside the function:
function doesEnteredUserExist() {
return $.ajax({...});
}
$.when(doesEnteredUserExist).then(function (result) {
//you can access result.d here
});
As #timing has mentioned, by the time the value is returned from thefunction, the ajax call is not complete so everytime you get the undefined.
This is not a solution to the problem, but an alternative method you can try for displaying it would be instead of returning the value, just update the innerHTML of some element like div with the returned text.Below is what I mean:
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: function (result) {
//alert(result.d);
if(result.d==true){ //Just a check for the value whether true or 1 etc..
$("#notifications").html('Username Already Exists'); // Have a div where you can display the message (named it notifications here) , update the notifications div text to notify the user
}else{
$("#notifications").html('Username is Available');
}
},
error: function (err) {
alert(err);
}
});
}
This seems a good example of $.Deferred object usage
the idea is quite simple (really, I promise, :) see steps on the code)
Create a new deferred object
Make your ajax call. If result is false you will reject the deferred otherwise you will resolve it (you could reject it also on error ajax callback)
return the promise
Use .when() helper to check the status of the promise.
I create a fiddle which return randomically true or false in the response
function checkUserExist() {
var dfd = $.Deferred(); /* step 1 */
$.ajax({
url: "/echo/json/",
data: {
"json": JSON.stringify({d: (Math.random() < 0.5) })
},
type: "POST",
success: function (data) {
console.log("result (inside ajax callback) ", data.d);
if (!data.d) { dfd.reject() } else { dfd.resolve(); } /* step 2 */
},
error : ...
});
/* step 3 */
return dfd.promise();
}
$.when(checkUserExist()) /* step 4 */
.fail(function() { console.log("user don't exist (inside fail)"); })
.done(function() { console.log("user already exist (inside done)"); })
fiddle url : http://jsfiddle.net/Gh9cN/
(note: I've changed some internal details so to make it work on jsfiddle)