Post Ajax call says Get not allowed - javascript

I'm trying to use ajax with post method but it keep poping me this error
An attempt was made to call the method \u0027SendEmail\u0027 using a GET request, which is not allowed
Here is the js
var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "ContactUs.aspx/SendEmail",
contentType: "application/json; charset=UTF-8",
data: json,
dataType:"json",
success: function (data) {
var a = 3;
},
error:function(a,b){
var a = 43;
}
})
and here is the server side on c#
[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}
Thanks in advance!

You should follow this way:
Your backend method which you already decorated with [WebMethod] and added a reference of using System.Web.Services;, I've changed the method to return something so it can be verified whether it works or not.
[WebMethod]
public static String sendEmail(string param)
{
return "Your String";
}
within your .aspx page, add scriptManager for enabling client side calling to your code behind methods
<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Finally within your JQuery script, call the method like this:
$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
alert(response);
}});
Hope it helps!

Try to use [HttpPost] instead of [WebMethod] and remove static.
Is it a REST API or MVC?

Related

ajax post request with multiple paramaters

My controller:
[HttpPost]
public IActionResult UserRoleChanged(string roleName,string userName)
{
var a = roleName;
var b = userName;
return RedirectToAction("UserManager");
}
Script in view:
if (window.confirm('Are you sure that you want to change role?')) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("UserRoleChanged", "DashBoard")",
dataType: 'json',
data: { 'roleName': this.text, 'userName': 'SomeName'},
cache: false,
success: function (data){
window.location.href = data;
},
failure: function (data) {
}
})};
When I run script above UserRoleChanged action does not invoke. If I try to remove userName variable from data in ajax then UserRoleChanged action method invokes without any problem. How can i pass multiple data to my controller? What is wrong with my code?
Remove the dataType: 'json' from the ajax, and try again. As you are trying to get the values on server side as normal variable, so dataType: 'json' is not required here.
You can create a model with same properties and pass it as a parameter. Its a good practice.
Looks like this.
public class User
{
public string RoleName { get; set; }
public string UserName { get; set; }
}
And the json looks like this example
{
"RoleName" : "somename",
"UserName" : "somename"
}

How to call a cs function in another library with ajax

Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}

How to solve Invalid JSON Primitive error on Ajax?

I am trying to perform ajax using webmethod on Asp.net,
And I am using JQuery-3.1.1
I want to pass the value to server and get back the value. I don't know what I did wrong.
Asp.net Code
<div class="row">
<asp:Button ID="btnSave" runat="server" CssClass="btn btn-info" Text="save" />
</div>
Jquery Code
$(document).ready(function () {
$('#btnSave').click(function () {
var name= 'xxx';
$.ajax({
type: "POST",
url: "AjaxWebMethod.aspx/getFileExistOrNot",
data: '{fileName:'+name+'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("failed ="+response.d);
},
error: function (response) {
alert("error ="+response.d); //This alert is executing
}
});
function OnSuccess(response) {
alert("Result ="+response.d.mydata);
}
return false;
});
});
C# code
public partial class AjaxWebMethod : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string mydata="ajaxworking";
return mydata;
}
}
I don't know really where I did my mistake
Error message on console
{Message: "Invalid JSON primitive: xxx.",…}
ExceptionType:"System.ArgumentException"
Message:"Invalid JSON primitive: xxx."
Can you give the solution with proper reason. that will good for me to understand more, thanks
Your postData is invalid JSON, a string needs quotes around it:
'{fileName:'+name+'}'
It should be:
'{fileName:"'+name+'"}'
The jQuery call that you are making is set up to expect JSON format in the response. It would appear that your server side code is simply returning a string which is not encoded as JSON. You either need to change the output from the server or change what is expected from the ajax invocation.

How to make Rest Spring work with JS

Folks
I have a problem with consuming a rest using javascript.
This Rest is already being used in other applications, where PHP and Aspx conserve the same described below.
#Controller
#RequestMapping("/userlogin")
public class UserRest {
#Autowired
private UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<RetornUser> login(#RequestBody User user) {
RetornUser retornUser = new RetornUser();
try {
user = userService.autenticarUsuario(user);
retornUser.setUsuario(usuario);
retornUser.setCodigoRetorno(1);
} catch (Exception e) {
retornUser.setCodigoRetorno(-1);
retornUser.setMensagem(e.getMessage());
}
return new ResponseEntity<>(retornUser, HttpStatus.OK);
}
}
The code above works perfectly with PHP, Aspx and Java calls.
When I call the routine, the JS is falling into the error function before receiving the return.
The worst thing is that the JS error is not bringing the reason. Below the code in pure HTML.
function logar() {
try {
var json = JSON.stringify(usuario);
json = "{\"nome\": \"garra\",\"senha\": \"1234\"}";
$.ajax({
type: "POST",
url: "http://localhost:8080/garrasystem/webservice/userlogin/login",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 300000, // sets timeout to 3 seconds
success: function (retorno) {
alert(retorno);
},
error: function (data, textStatus, xhr) {
alert(data.responseText);
}
});
} catch (e) {
console.log(e);
}
}
The way it is there, when I send debug, it calls the normal login method, but it falls into the error function, nor does it expect the login method to perform the return.
I put the method return String only and nothing too.
My Spring is 4.
I'm waiting for some help
Vinicius Castro
Looks like you are passing string instead of json object. Could you try passing the following:
var data = {
nome: "garra",
senha: "1234"
};
Folks
Being focused on a single problem, I forgot to analyze the button type. It was like type submit, so it was not working. It is like experiencing these kind of mistakes.
Thank you to all who supported me

Unknown WebMethod error while calling it from Jquery using Ajax

I have a web method that i am trying to call from jquery ajax but it is not getting invoked.
In firebug When i saw the response i get,
<title>Unknown web method MyMethod.<br>Parameter name: methodName</title>
error.I am not able to get the reason why this error is coming when that method is available at the server side..
Here is my client side code..
$("#excel").on("click", function (e) {
e.preventDefault();
var img = "image";
$.ajax({
type: "POST",
url: "Default.aspx/MyMethod",
data: JSON.stringify({ imageData: img }),
contentType: "application/json; charset=utf-8"
}).done(function (o) {
console.log(["Response:", o]);
});
});
And here is my server side code..
[WebMethod()]
public static void MyMethod(string imageData)
{
string fileNameWitPath = "D:/Kabir/custom_name.png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);//convert from base64
bw.Write(data);
bw.Close();
}
}
}
Please help me to solve this issue as i am completely struck into this.
Thanks in advance..
Using this worked for me System.Web.Services.WebMethod
Try this
[System.Web.Services.WebMethod]
public static void MyMethod(string imageData)
{
}
System.Web.Services.WebMethod()
Initializes a new instance of the System.Web.Services.WebMethodAttribute class
System.Web.Services.WebMethod
Adding this attribute to a method within an XML Web service created using ASP.NET makes the method callable from remote Web clients
If the above doesn't works, make sure that the url you are passing is correct. And still if it doesn't works Check this out
This did worked on my system
Default.aspx
<form id="form1" runat="server">
<div id="excel">
Here</div>
</form>
<script type="text/javascript">
$("#excel").on("click", function (e) {
e.preventDefault();
var img = "image";
$.ajax({
type: "POST",
url: "Default.aspx/MyMethod",
data: JSON.stringify({ imageData: "Hello" }),
contentType: "application/json; charset=utf-8"
}).done(function (o) {
console.log(["Response:", o]);
});
});
</script>
Default.aspx.cs
[System.Web.Services.WebMethod]
public static string MyMethod(string imageData)
{
return imageData;
}
If you're looking for an answer about VB.net, you need to make your function Public Shared. I just ran into this issue myself.

Categories