Salaamun Alekum
My AJAX Call Is Not Calling The Controller Action In ASP.NET MVC Web Applicaiton Project
Bellow Is My AJAX Call In Javascript And Next Is Controller's Action
AJAX Call
var requestUrl = '/Home/GetCurrentUser';
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
The Controller Action
[SharePointContextFilter]
public JsonResult GetCurrentUser()
{
CurrentUserModel um = new CurrentUserModel();
try
{
Microsoft.SharePoint.Client.User spUser = null;
var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title, user => user.Email, user => user.LoginName);
clientContext.ExecuteQuery();
um.Name = spUser.Title;
um.Email = spUser.Email;
um.LoginName = spUser.LoginName;
}
}
SharePointBoxOnline.Common.User u = UserManager.Instance.GetUserByEmail(um.Email);
if (u != null)
{
um.ClientId = u.FK_Client_ID;
um.UserId = u.User_ID;
}
}
catch (Exception e)
{
SharePointBoxOnlineAppWeb.Classes.LogsManager.LogException(e.Message, e.StackTrace, System.Web.HttpContext.Current.Request.Url.ToString(), "Added logging functionality to store the exception information in the Database", DateTime.Now);
}
return Json(um, JsonRequestBehavior.AllowGet);
}
Errors Results In AJAX Are
error.description
Invalid character
status
parsererror
xhr.responseText
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
<link href="/Content/css?v=MDbdFKJHBa_ctS5x4He1bMV0_RjRq8jpcIAvPpKiN6U1" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h2>An unexpected error has occurred.</h2>
<p>Please try again by launching the app installed on your site.</p>
</div>
</div>
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Internet Explorer","requestId":"673b269bf2c74e39a9496d69f3e0b62e"}
</script>
<script type="text/javascript" src="http://localhost:14069/4b2e31c8e2cf413facce9558ed0cb3ff/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>
</html>
Thank You Stackoverflow And Members Of Stackoverflow Please Let Me Know If You Require Further Details
Thank You
$.ajax({
url: requestUrl,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data)
{
debugger;
alert(data);
},
error: function (xhr, status, error)
{
debugger;
alert(error);
}
});
Related
I have a autocomplete in a grid-view in a ascx file but the autocomplete is not working in the ascx file. I have made several similar autocomplete in other page that work. Why is it that the autocomplete does not work in my ascx file. I have a hypotheses why it does not work but I am unsure how to fix it here it is
I think that the problem is with the following url in the javascript
url: "contratoGerencia.aspx/getSupplierAndComponente"
However I dont know how I should change it don get it to work with the ascx file.Also I found a solution here https://www.codeproject.com/Questions/757769/How-to-Call-Ascx-page-form-JavaScript-Funnction-Of that is almost what I want the only problem is that I also have a textbox in my situation.
Any help would be very appreciated. I hope the following information will help you.
Here is my ascx (ComponentesControler.ascx) code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="../css/autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../scripts/autocomplete.js" ></script>
<asp:TextBox CssClass="gridContractAndComponente" ID="txtContractComponenteFooter" Text="" runat="server" TextMode="MultiLine" Rows="1" />
Here is my ascx.cs (ComponentesControler.ascx.cs) code
[WebMethod]
public static List<string> getSupplierAndComponente(string prefixText)
{
string lv_numero_contrato;
List<string> numeros_contrato = new List<string>();
connectionStringBuilder builder = new connectionStringBuilder();
String connString;
connString = builder.builder.ConnectionString;
string selectStatement = " SELECT numero_contrato FROM erp_contratos ";
using (MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = selectStatement;
cmd.Parameters.AddWithValue("#searchText", prefixText);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
lv_numero_contrato = reader.GetString(reader.GetOrdinal("numero_contrato"));
numeros_contrato.Add(lv_numero_contrato);
}
}
conn.Close();
}
}
return numeros_contrato;
}
Here is the aspx page (contratoGerencia.aspx) were I use the ascx file
<div id="ComponentesSection" class="menusection">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Always" >
<ContentTemplate>
<TWebControl5:WebControl5 ID="Header8" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Here is my javascript file (autocomplete.js)
$(document).ready(function () {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
The problem is in the name of your parameter entered in AJAX, your method expects to receive a parameter named prefixText and not containedText.
Change
data: {'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
with
data: {'prefixText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
The issue can be triggered by the UpdatePanel like explained here:
jQuery $(document).ready and UpdatePanels?
So modify your autocomplete.js like this:
$(document).ready(function() {
SearchSupplierAndComponente();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
See if the console error goes away.
Error
jquery-1.7.js:8157 OPTIONS http://localhost:8080/DigitalWallet/subscriber/add/ 403
send # jquery-1.7.js:8157
ajax # jquery-1.7.js:7635
(anonymous) # CallTest.js:9
dispatch # jquery-1.7.js:3319
eventHandle # jquery-1.7.js:2925
index.html:1 Failed to load http://localhost:8080/DigitalWallet/subscriber/add/: Response for preflight does not have HTTP ok status.
My Client code is follow
$(document).ready(function() {
$('#butCallAjax').click(function() {
jQuery.support.cors = true;
alert("awa");
var data0 = {
number: '0719402280',
agent_number: '0719402243',
agent_pin: '1234'
};
var json = JSON.stringify(data0);
$.ajax({
type: "POST",
dataType: "text",
data: json,
contentType: "application/json; charset=utf-8",
url: "http://localhost:8080/DigitalWallet/subscriber/add/",
success: function(data) {
alert(data);
},
error: function(msg, url, line) {
alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
});
});
And this is my User HTML part
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="http://code.jquery.com/jquery-1.7.js" type="text/javascript"></script>
<script src="js/custom/CallTest.js" type="text/javascript"></script>
</head>
<body>
<button id="butCallAjax">Get data</button>
<select id="cboFastBikes" name="cboFastBikes"></select>
</body>
</html>
This is my service
#RequestMapping(value = "/agent/add/", method = RequestMethod.POST)
public String addAgent(#RequestBody Agent agent) throws Exception {
Log4JUtil.logger.info("Agent,agent_save_request,Request=" + agent.toString()+"|"+agent.getName()+"|"+agent.getNumber());
String Text = "";
try {
agentValidation.fieldValidation(agent);
String number = agent.getNumber();
try {
Agent dbagent = agentService.findByNumber(number);
if (dbagent != null) {
throw new AgentAlreadyExistsException();
} else {
agentService.saveOrUpdate(agent);
agentService.createWallet(number);
Text = "0|Created|Active|Agnt";
}
} catch (Exception exp) {
throw exp;
}
} catch (Exception ex) {
Log4JUtil.logger.info("Agent,agent_save_request,Request=" + agent.toString() + "," + ex.toString());
throw ex;
}
return Text;
}
This service is working fine. I used postman to check the service. Please help me to figure out this problem
Can we call a C# method in a class from a html page??
I have a class names Crud.cs
public class Crud
{
public String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
I want to call this method from a html page.I'm using a html page not a asp page.Is there any possibility to call without using ajax or if ajax also how could I call.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-3.2.1.js" type="text/javascript"></script>
</head>
<body>
<div style="align-content:center;">
<input type="text" id="HtmlName" />
<button id="btn_gen_html" onclick="createHtml()">Generate</button>
</div>
<div id="Msg"></div>
<div id="feedbackMsg"></div>
<script>
function createHtml() {
var name = document.getElementById("HtmlName").value;
$.ajax({
type: "POST",
url: "Crud.cs/generateFiles",
data: { name } ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else(val==1)
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
}
</script>
</body>
</html>
This is my code. Here I am not able to call generateFiles() method in crud class. Can I call so.And if I can How?
You can't call normal method. The method must be static and web method.
Try this:
public class Crud
{
[WebMethod]
public static String generateFiles(String name)
{
return(generateHtml(name));
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
You are missing a controler in your project.
You try to retrieve data from a cs file without a controler (or a [WebMethod])? this is impossible.
Try looking for some MVC guides, Here is one from microsoft web site
You dont have to use all that ASP component that showen there, but you can see there how to retrieve data from the server to the client.
Basic syntax
<script type="text/javascript"> //Default.aspx
function myfunction() {
$.ajax({
type: "POST",
url: 'Default.aspx/myfunction',
data: "mystring",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
Default.aspx.cs
[WebMethod]
public static String myfunction(string name)
{
return "Your String"
}
If you want to use page call without ajax: Ref
//cs file (code behind)
[ScriptMethod, WebMethod]
public static string GetLabelText(string param1)
{
return "Hello";
}
//aspx page
<script type="text/javascript">
function InsertLabelData() {
PageMethods.GetLabelText(param1,onSuccess, onFailure);
}
function onSuccess(result) {
var lbl = document.getElementById(‘lbl’);
lbl.innerHTML = result;
}
function onFailure(error) {
alert(error);
}
InsertLabelData();
</script>
If you're using ASP.NET Web Forms, there is a WebMethodAttribute you can use instead of calling .cs file directly which unsupported by AJAX due to no URL routing enabled for normal classes. The web method must be declared as static:
// if you're using ASMX web service, change to this class declaration:
// public class Crud : System.Web.Services.WebService
public class Crud : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static String generateFiles(String name)
{
return generateHtml(name);
}
private String generateHtml(String name)
{
var filename = "C:\temp\"" + name + ".html";
try
{
FileStream fs = new FileStream(filename, FileMode.Create);
return "True";
}
catch(Exception e)
{
return e.ToString();
}
}
}
Then your AJAX call URL should be changed to this (note that the web method should be exist in code-behind file, e.g. Crud.aspx.cs or Crud.asmx.cs):
$.ajax({
type: "POST",
url: "Crud.aspx/generateFiles", // web service uses .asmx instead of .aspx
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
If ASP.NET MVC is used, use JsonResult to return JSON string as success result:
public class CrudController : Controller
{
[HttpPost]
public JsonResult generateFiles(String name)
{
return Json(generateHtml(name));
}
}
The AJAX call for the action method looks similar but the URL part is slightly different:
$.ajax({
type: "POST",
url: "Crud/generateFiles",
data: { name: name }, // use JSON.stringify if you're not sure
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (val) {
alert(val);
if (val == 0) {
$("#feedbackMsg").html("Success");
}
else
{
$("#feedbackMsg").html("Sorry cannot perform such operation");
}
},
error: function (e) {
$("#feedbackMsg").html("Something Wrong.");
}
});
//Perfect solution
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
//PLEASE menntion [WebMethod] attribute on your method.
I was playing around with the WordPress Rest API, and I was downloading this plugin called WP OAuth Server (by Justin Greer), and I have built my own OAuth connection.
I have one problem: I get Error 400, and it says: The grant type was not specified in the request.
Here is my code so far:
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css" type="text/css">
</head>
<body>
<div id="result"></div>
<!--<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script>-->
<script type="text/javascript" src="assets/js/app.js"></script>
</body>
</html>
JavaScript:
/**
* OAUTH 2 LOGIN
*/
+function () {
var $CLIENT_CODE = 'fc8uhbwlo4niqhngrjsdl3tbp3cndpidfs61w77g';
var $CLIENT_ID = 'llsfdwZzO7qVHBzM4nhfcq1jFW2L8O';
var $CLIENT_SECRET = 'auaCKn8JWXQmSyYrl3PDi23klIhotp';
var $AUTHORIZATION_ENDPOINT = 'http://domain.dev/oauth/authorize';
var $TOKEN_ENDPOINT = 'http://domain.dev/oauth/token';
$.ajax({
url: $AUTHORIZATION_ENDPOINT + '?client_id=' + $CLIENT_ID + '&client_secret=' + $CLIENT_SECRET + '&response_type=code',
}).done(function (url) {
$('#result').html(url);
fetchSomething();
}).fail(function (errorThrown) {
console.log("Error" > errorThrown.responseText);
})
function fetchSomething() {
$.ajax({
type: 'POST',
url: $TOKEN_ENDPOINT + '?grant_type=authorization_code&code=' + $CLIENT_CODE,
}).done(function (success) {
console.log(success);
}).fail(function (error) {
console.log(error);
});
}
}();
CodePen
This was my solution
$.ajax({
url: 'http://' + domain + '?oauth=token',
type: 'POST',
data: {
grant_type: grantType,
code: code,
client_id: clientID,
client_secret: clientSecret,
redirect_uri: redirect
}
}).done(function (token) {
console.log(token);
}).fail(function (fail) {
console.log(fail.responseJSON.error);
});
It's me again (previous question) I am still having problems with json and xml being returned from an ajax call.
I have written a webservice in MonoDevelop version 2.2 to return my json.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getLocationJ(){}
Which returns:-
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(bigPM);
return json;
If I test my webservice I get:-
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"placeName":"XXXX","address":"Some Address","lat":12121,"lng":12121}]</string>
Which is exactly what I am pulling in when I make my ajax calls. My json is still wrapped in XML and therefore cannot be read.
This is my ajax call:-
$.ajax({
type: "GET",
url: theURL,
async: true,
data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
cache: false,
dataType: "jsonp",
contentType: "application/xml; charset=utf-8",
success: function (data) {
alert('in here');
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
alert(xhr.statusText);
}
});
If I do just json I get 500 Internal server error, if I do a POST I get 403 forbidden error.
This morning I tried doing:-
$.getJSON(theURL, {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat}, function(data) {
);
});
Only I get the exact same problems.
If I could just remove the xml from my json then I could move forward but right now I am dead in the water and I think I am drowning in ajax!
Please help
Cheryl
Instead of returning a string in your WebMethod, return void and use:
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(YOUR_STRING_TO_OUTPUT));
A quick and dirty fix is to extract your json from the xml in the success function.
$.ajax({
type: "GET",
url: theURL,
async: true,
data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
cache: false,
dataType: "jsonp",
contentType: "application/xml; charset=utf-8",
success: function (data) {
data = extractJsonFromXml(data);
//you have to write extractJsonFromXml function in js, you could use substring, or a regex replace.
}
change
contentType: "application/xml; charset=utf-8",
to
contentType: "application/json; charset=utf-8",
Complete example:
/* in this case I am using */
<script src="Js/json2.js" type="text/javascript"></script>
// available at: http://www.json.org/js.html
function jsonObject()
{
};
var phoneListObject = new jsonObject();
function SaveJsonObject()
{
phoneListObject.Control = new jsonObject();
phoneListObject.Control.CustomerId = $("#CustomerId").val();
phoneListObject.Control.CustomerName = $("#CustomerName").val();
phoneListObject.ListBody.PhonesBlock = new jsonObject();
phoneListObject.ListBody.PhonesBlock.Phone = new Array();
$('#PhonesBlock .Phone').each(function(myindex)
{
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneNumber = $(".PhoneNumber input", this).val();
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneName = $(".PhoneName input", this).val();
});
};
$(function()
{
function SaveCurrentList()
{
SaveJsonObject();
var currentSet = phoneListObject;
var formData = { FormData: currentSet };
phoneListJSON = JSON.stringify(formData);
var FormData = "{ FormData:" + JSON.stringify(phoneListJSON) + "}";
SavePhoneListData(FormData);
};
function SavePhoneListData(phonesData)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: phonesData,
dataFilter: function(data)
{
var msg;
if ((typeof (JSON) !== 'undefined') &&
(typeof (JSON.parse) === 'function'))
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "../../WebServices/ManagePhones.asmx/SaveJson",
success: function(msg)
{
SaveSuccess(msg);/* the JSON is in the msg, create this function to do what you want with it. */
},
complete: function(xhr, textresponse)
{
var err = eval("(" + xhr.responseText + ")");
},
error: function(msg)
{
},
failure: function(msg)
{
}
});
};
$('#btnSave').click(function()
{
SaveCurrentList();
});
});
/* json data snip */
{"FormData":{"Control":{"CustomerId":"12345y6","CustomerName":"Joe Customer"},"PhonesBlock":{"Phone":[{"PhoneNumber":"234-233-2322","PhoneName":"son harry"},{"PhoneNumber":"234-233-2323","PhoneName":"son frank"},{"PhoneNumber":"234-233-2320","PhoneName":"momk"}]}}}
/*XML of the form data:*/
<FormData>
<Control>
<CustomerId>12345y6</CustomerId>
<CustomerName>Joe Customer</CustomerName>
</Control>
<PhonesBlock>
<Phone>
<PhoneNumber>234-233-2322</PhoneNumber>
<PhoneName>son harry</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2323</PhoneNumber>
<PhoneName>son frank</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2321</PhoneNumber>
<PhoneName>momk</PhoneName>
</Phone>
</PhonesBlock>
</FormData>
/* form layout snip */
<div class="control">
<div class="customer">
<input typeof="text" id="CutomerId" />
<input typeof="text" id="CutomerName" />
</div>
<div class="phoneslist" id="PhonesBlock">
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
</div>
</div>
<input id="buttonSave" class="myButton" type="button" value="Save" />
signature of the web service method:
[WebMethod(EnableSession = true)]
public string SaveJson(string FormData)
{
}
Make sure your service class has [ScriptService] attribute. This attribute is not added by default.