Display JSON Result Upon Button Click ASP.NET MVC - javascript

Hi I have this code in my controller:
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
return Json(new {CalculatedBMI = CalculateModel.BMICalc.ToString(), CalculatedBMIMeaning = CalculateModel.BMIMeaning.ToString() }, JsonRequestBehavior.AllowGet);
}
I would like to display CalculatedModel.BMICalc and CalculatedModel.BMIMeaning on the page using this JavaScript:
$('#good').click(function () {
var request = new BMICalculation();
$.ajax({
url: "CalculateAndSaveToDB",
dataType: 'json',
contentType: "application/json",
type: "POST",
data: JSON.stringify(request),
success: function (response) {
var div = $('#ajaxDiv');
div.html("<br/> " + "<b>" + "Your BMI Calculations: " + "</b>");
printBMI(div, response);
},
});
});
function printBMI(div, data) {
div.append("<br/>" + "You are " + response.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + response.CalculatedBMIMeaning + ".");
};
Nothing happens however when I do the button click. The correct data from form goes correctly into DB. My Chrome debugger says however that CalculateAndSaveToDB isn't found 404 error. Please help.

Try to return false at the end of your click function.
$('#good').click(function () {
//Your code
return false;
});
Also I can see an error in your printBMI function. There is not reference to the variable "response". It should be "data"
function printBMI(div, data) {
div.append("<br/>" + "You are " + data.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + data.CalculatedBMIMeaning + ".");
};

There might be several problems:
Your routing is not correct and the post-action cannot be invoked. I dont see any information about routing, so this might be a problem.
You do not return false, as suggested by PraveeReddy. If you dont do so, the browser follows the link of your button.
Just a hint: In such simple scenarios it can be easier to use $.load: http://api.jquery.com/load/

Related

Ajax error function not working 2

Basically what I'm trying to do is have a search bar. The user should input the state and city. Once I get the state and city, update the html with the result. The problem is once i enter an invalid state or city, it gives me an error in the console. What i want is an alert telling the user that they have made a mistake in entering the city or state. I tried using a try and catch/ ajax error function but it doesn't seem to work. Need some help thanks !
$(document).ready(function() {
setTimeout(function(){
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search= $('#search');
var searchsubmit= $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
try {
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}catch(err){
alert(err.message);
}
});
});
I think that adding the error callback should work, here is a jsbin:
https://jsbin.com/ciwosoqeye/edit?html,js,output
var searchresult = '';
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/" +
searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
},
error: function(jqxhr, errorString, ex) {
alert(ex);
}
});
as defined in the doc
Without knowing what error message you are getting or what parsed_json looks like with a bad request, this is only a guess but parsed_json probably doesn't have a location property and/or a city property when bad data is passed in. I'm guessing that is causing the error. If this is the case, you can check for the existence of parsed_json.location and parsed_json.location.city before trying to access them and display the error if they don't exist.
$(document).ready(function() {
setTimeout(function() {
$('body').addClass('loaded');
$('h1').css('color','#222222');
}, 3000);
var search = $('#search');
var searchsubmit = $('#searchsubmit');
searchsubmit.on('click', function(e){
console.log(search.val());
var searchresult= search.val();
$.ajax({
url:"http://api.wunderground.com/api/69e8e728a8f8536f/geolookup/conditions/q/"+ searchresult +"/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
if (parsed_json.location && parsed_json.location.city) {
var location = parsed_json.location.city;
var temp_f = parsed_json.current_observation.temp_f;
alert("Current temperature in " + location + " is: " + temp_f);
} else {
alert(err.message);
}
}
});
});
});
Setting a break-point at the beginning of the success callback and inspecting parsed_data would help in debugging this sort of thing.

How to update SharePoint 2010 Column with SharePoint Username via OnClick?

Good morning, I come to you guys looking for some assistance getting two functions to work. I think I'm almost there but I'm missing something. I cannot get the field in SharePoint to update but I can get my document to open no problem. Is something missing in the code below?
<script type="text/javascript">
function fnUpdateRecord(userId, id) {
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List(" + id + ")?$select=ViewBy", function (data) {
var viewby = data.d.ViewBy;
var username = userId;
var doc = new Object();
doc.ViewBy = username;
$.ajax({
method: "POST",
url: "PROGRAM/_vti_bin/listdata.svc/List(" + id + ")",
contentType: "application/json; charset=utf-8",
processData: false,
beforeSend: beforeSendFunction,
data: JSON.stringify(doc),
dataType: "json",
error: function (xhr) {
alert(xhr.status + ": " + xhr.statusText);
},
success: function () {
}
});
});
}
function fnRecordAccess(id, path) {
$.ajax({
url: "GetCurrentUser.aspx",
context: document.body
}).success(function(result) {
var userId = $(result).find('.wtf').text()
fnUpdateRecord(userId, id);
window.open(path, "othrWn");
}).error(function(error) {
console.log(error);
});
}
</script>
I think call those functions via an OnClick:
onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a>
I can get the item/infopath form to load in another window but it doesn't seem to run the function to add the username in the ViewBy column. Any ideas? Thank you for assisting!
Edit: Added fnCountrySearch; this calls the other functions.
function fnCountrySearch(choice) {
fnWaitDialog("show");
var searchId = choice;
$("#tableBody tr").remove();
$.getJSON("PROGRAM/_vti_bin/ListData.svc/List?$filter=Country eq '" + searchId + "'&$orderby=Name", function (data) {
var d = data.d;
if (d.results.length == 0) {
$("#noResultsAlert").show();
$("#notingQueried").hide();
}
else {
$.each(d.results, function (n, i) {
var path = i.Path + "/" + i.Name;
$("#tableBody").append("<tr><td>" + "<a class='btn btn-sm btn-default' class='pull-left' href='#' onclick='fnRecordAccess(" + i.Id + ", "" + path + "")'><i class='fa fa-lg fa-pencil'></i> View</a></td></tr>");
});
$("#noResultsAlert").hide();
$("#notingQueried").hide();
}
})
.always(function () {
fnWaitDialog("hide");
});
}
The beforeSendFunction:
function beforeSendFunction(xhr) {
// Manipulate headers for update
xhr.setRequestHeader("If-Match", "*");
// Using MERGE so that the entire entity doesn't need to be sent over the wire.
xhr.setRequestHeader("X-HTTP-Method", 'MERGE');
}
REST
To compare your code with published examples, you can refer to Microsoft's documentation of SharePoint 2010's REST interface here:
Data Access for Client Applications: Using the REST Interface
Reference Implementation: Client: Using the REST Interface from JavaScript
JSOM
SharePoint 2010 does have a JavaScript client object model that you can use as an alternative to the REST API. This can be an especially attractive option if you find yourself invoking the REST API via JavaScript, since the client object model does not require additional libraries.
If you were to rewrite your fnUpdateRecord method to use the JavaScript client object model it would look like this:
fnUpdateRecord(userId, id){
var listName = "List", fieldName = "ViewBy", newValue = userId + " # " + new Date() + ";\n";
var clientContext = new SP.ClientContext();
var list = clientContext.get_web().get_lists().getByTitle(listName);
var item = list.getItemById(id);
clientContext.load(item);
clientContext.executeQueryAsync(Function.createDelegate(this,function(){
// get current field value...
var currentValue = item.get_item(fieldName);
item.set_item(fieldName, newValue + currentValue);
item.update();
// update the field with the new value
clientContext.executeQueryAsync();
}),Function.createDelegate(this,function(sender,args){alert(args.get_message());}));
}
Note that when using the JavaScript Client Object Model, you need to wait for the SP.JS library to load first. This can be accomplished using the built-in ExecuteOrDelayUntilScriptLoaded method like so:
ExecuteOrDelayUntilScriptLoaded(yourFunctionName,"SP.JS");
or
ExecuteOrDelayUntilScriptLoaded(function(){
// your code here
},"SP.JS");

Ajax call successful, but error block is executing

I'm trying to save a post to my database which it does, however the ajax error block is executing. It states ok in its response though so I looked around on some of the other questions and it seemed like I wasn't returning a Json object so I tried a few things:
Creating a NameValule variable and adding ("Success","true") and converting it to Json by Json.Encode(NameValue);
Returning a string in the format of Json:"{ \"Result\":[{\"Success\":\"true\"}]}";
Changing the dataType to "text json" "text/json"
The error block still executes for some reason, any ideas?
//Save it all in an object to be passed in ajax
var Post = {
Id: postID,
Title: postTitle.val(),
Author: postAuthor,
Date: postDate,
Content: postContent.val(),
metaDescription: metaDescription.val(),
metaKeywords: metaKeywords.val(),
metaID: metaId.text(),
Page: $(document).attr('title')
};
//save to database
$.ajax({
url: url,
type: 'POST',
dataType: "text json",
data: { data: JSON.stringify(Post) },
success: function (result) {
console.log("result: " + result);
if (result == "Success") {
// postContent.append("<br/><p>Edit Successful!</p>");
alert('Edit successfull');
//window.location.replace(window.location.href);
}
else {
postContent.replaceWith("<div>" + result + "</div>");
}
},
error: function (xhr, status) {
console.log('ajax error = ' + xhr.statusText);
}
});
Here is the response page:
#using WebMatrix.Data;
#functions{
public string EditPost()
{
var db = Database.Open("StarterSite");
var post = Request.Unvalidated["data"];
var result = Json.Decode(post);
var error = new System.Collections.Specialized.NameValueCollection();
/* Id: postID,
Title: postTitle,
Author: postAuthor,
Date: postDate,
Content: afterEdit,
Page: $(document).attr('title')
*/
if(string.IsNullOrEmpty(result["Id"]))
{
error.Add("Error", "Id empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Author"]))
{
error.Add("Error", "Author empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Content"]))
{
error.Add("Error", "Content empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["Date"]))
{
error.Add("Error", "Date empty");
return Json.Encode(error);
}
//Page and Title only ones that can be empty
var cmd = "UPDATE Posts SET ID='" + result["Id"]
+ "',Author='" + result["Author"]
+ "',Content='" + result["Content"]
+ "',Date='" + result["Date"]
+ "',Title='" + result["Title"]
+ "',Page='" + result["Page"]
+ "' WHERE ID='" + result["Id"] + "';";
try { db.Execute(cmd); }
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaDescription"]))
{
error.Add("Error", "metaDescription empty");
return Json.Encode(error);
}
if (string.IsNullOrEmpty(result["metaKeywords"]))
{
error.Add("Error", "metaKeywords empty");
return Json.Encode(error);
}
//Post was edited successfully add/update meta info
int parseResult = 0;
Int32.TryParse(result["metaID"], out parseResult);
if (parseResult > 0)//metaID is supplied
{
cmd = "UPDATE MetaInfo SET Description='" + result["metaDescription"]
+ "',Keywords='" + result["metaKeywords"]
+ "',postID='" + result["Id"]
+ "' WHERE ID='" + result["metaID"] + "';";
}
else //metaID is not supplied
{
cmd = "INSERT INTO MetaInfo (Description,Keywords,postID) VALUES('"
+ result["metaDescription"] + "','"
+ result["metaKeywords"] + "','"
+ result["Id"] + "');";
}
try
{
db.Execute(cmd);
}
catch (Exception e)
{
error.Add("Error",e.Message);
return Json.Encode(error);
}
//End Update meta info
error.Add("Success", "true");
return Json.Encode(error); //"{ \"Result\":[{\"Success\":\"true\"}]}";
}
}
#{
var result = EditPost();
}
#result
For anyone else that may have this same problem here was how I finally solved it: Just use Html.Raw(result) to send back only the json instead of extra stuff that gets added for some reason.
Can't be sure without knowing the requirements for the url. My guess would be that the data property is the reason you're off. I'm guess Post is an object defined elsewhere. When you send your request, the server will likely interpret the data field as an object not a string. Try to change {data: JSON.stringify(Post)} to just JSON.stringify(Post)
try with adding async: true, line after type: 'POST',
Problem is with your JSON response.
"{ \"Result\":[{\"Success\":\"true\"}]}";
There added slashes before double quotes(").
You can see the actual error thrown by jQuery using below updated error block:
error: function (xhr, status, errorThrown ) {
console.log(errorThrown )
Solution:
Remove slashes from your response try response like below:
'{ "Result":[{"Success":"true"}]}'
Hope this will help you.
Regards,

How can i validate recaptcha with ajax?

my function in js have this code:
$.ajax({
url: "ajax.php",
type: 'POST',
data: 'act=newAccount&email=' + email + '&password=' + password + '&first-name=' + firstName + '&last-name=' + lastName + '&company-name=' + companyName,
success: function(data)
{
json = JSON.parse(data);
if (json === true)
{
console.log("data");
$("#new-account-form")[0].reset();
window.location.replace('login.php');
}
else
{
$(".error-message span").html('Your regestry failed. Please, insert valid data.');
$('.error-message').fadeIn('slow', function () {
$('.error-message').delay(5000).fadeOut('slow');
});
}
}
});
now, i want validate recaptha in my ajax.php but i dont know how i do...
thanks you all
You'll need a Captcha images' displayer and some code to validate it. I recommend Securimage, it worked fine for me, and it is so easy to implement. Have a look at it at http://www.phpcaptcha.org/documentation/quickstart-guide/

How to access result array returned in ajax?

Arg!! I had this working flawlessly and now I am back to banging head against the keyboard.
I want access defined columns inside the array, but I am getting undefined but if I display the results using an alert as detailed in snipped of code below I see the following:
[{"firstname":" Mr","0":" Mr","lastname":" Two","1":" Two","user_public_info_id":"3","2":"3","st_usage_id":null,"3":null},{"firstname":" Mr","0":" Mr","lastname":" Three","1":" Three","user_public_info_id":"5","2":"5","st_usage_id":null,"3":null}]
***
g
***
e
***
undefined
Here is the Ajax code:
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: "handler=getStActivitySharingList&stu_id="+stu_id,
datatype: "json",
success: function(result){
var count = 0;
if (result !== null)
{
//display results
alert(result + " <br />*** <br />" + result[0] +" <br />*** <br />" + result[1] + " <br />*** <br />" + result[0]["firstname"]);
//clears choice list
clearOptions();
//result = $.parseJSON(result); //if this is used cannot display result again
alert (result);
$.each(result, function (i, elem) {
alert("elem"+elem.st_usage_id ); //displays as undefined and won't break
if (elem.st_usage_id === null)
{
count++;
alert(elem.firstname + " "+ elem.lastname + " " + elem.user_public_info_id);
appendOption(elem);
}
});
}
alert(count);
if (count === 0){
noResultsAvailableOption();
}else{
resultsAvailableOption();
}
ShowDialog(false);
e.preventDefault();
},
error: function(){
alert("ajax failure: could not retrieve a list of contacts");
}
});
i not know how you return it from PHP, but in jquery try:
sucess: function (result)
{
console.log(JSON.parse(result)); // parse string to json
}
See json.org
To better answer this question is to implement better debugging procedures.
Here is the code that I used for debugging this issue. The breaking down of the xmlHttpRequest clearly displayed to me that issue was with the data and that I was encountering an illegal character exception when trying to encode the data to json.
A great way to solve any issue is to first implement the correct debugging procedures, and everything else will work itself out.
error: function(xmlHttpRequest, status, error){
alert("ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xmlHttpRequestStr= "";
for(x in xmlHttpRequest)
xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
alert(xmlHttpRequest);
}

Categories

Resources