I made an HTML page which has an input. I get the value through javascript, create a JSON, and I want to send it via ajax. I also have a JSP application, which runs a method in java that recieves this JSON and reads it so it can be stored in a database. The problem is that I don't know how to receive this call from ajax in my jsp application and sent it to my method in java. Can someone help me with this?
Javascript:
alert("I am about to POST this:\n\n" + dat);
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'JSON',
data: dat,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
`
JSP:
'<%# page language="java" import="connection.JsonHandler" %>
<%
String json = request.getParameter("dat");;
JsonHandler gson = new JsonHandler();
gson.ReadJson(json);
%>
Java:
package connection;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.GsonBuilder;
import entidades.User;
import java.lang.reflect.Type;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonHandler {
public Gson CreateJson(String values) {
Gson gson = new GsonBuilder().create();
gson.toJson("Hello", System.out);
gson.toJson(123, System.out);
return gson;
}
public void ReadJson(String json){
Gson gson = new Gson();
Type type = User.class;
gson.fromJson(json,type);
}
}
You can write a servlet, which will accept your POST request. Please refer to I couldn't get the POST value in servlet page? or How to get the data from ajax request in servlet page?
Related
I was trying to figure out how I get the body of the JSON object, that I was sending with the listed AJAX POST request.
While debugging the UploadJSON method gets called but is having a jsoninput with null content.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IFormCollection jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
//javascript
function uploadJSON(plistArrayForJSON) {
var sendobj = JSON.stringify({ plistArrayForJSON });
$.ajax({
url: 'https://localhost:5001/home/uploadjson',
type: 'POST',
data: sendobj,
contentType: "application/json",
});
}
The JSON you send is not deserializable as IFormCollection.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IList<PlayList> jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
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");
}
}
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?
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.
I am using the following JQuery\JavaScript code to communicate with a WCF 4 REST service.
<script>
var serviceUrl = "http://services.xiine.com/Xiine/Live/AccountService/rest/json/Login";
var userInfo = {
"IsNotEncrypted":true,
"Password":null,
"UserName":null
};
var loginSuccess = function(data, textStatus, jqXHR){
console.log("yay");
};
var loginError = function(){
console.log("oh no");
};
$.post(serviceUrl , userInfo, loginSuccess);
$.post(serviceUrl , loginSuccess);
</script>
I am trying to establish why it is that the service will correctly return a false value when I do not pass the user data:
$.post(serviceUrl , loginSuccess);
As opposed to when I do pass user data, at which point it gives a POST 400 (Bad Request) error.
$.post(serviceUrl , userInfo, loginSuccess);
I am sure it has to do with how the JSON object, userInfo, is being built or interpreted, and I can post Fiddler 2 or WireShark dumps, if that will help. Just let me know...
I don't really have access to changing the WCF side of the service, so hopefully there is something I can do on my end to make this work.
Thanks!
Edit
I got a little more information... Apparently, the problem is that the server is responding with the following error:
The server encountered an error processing the request. The exception message is 'The incoming message >has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', >'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the >documentation of WebContentTypeMapper for more details.'. See server logs for more details. The >exception stack trace is:
at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
So I am thinking I need to figure out how to get the object to go across the wire as a JSON object via a JQuery.post() method.
More information --- Again...
ok... There is no app.config or web.config, as such.
Here is what I can get as far as the contracts and code and what-not.
[ServiceContract]
public interface IAccount
{
[OperationContract]
bool Login(UserInformation user);
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AccountService : IAccount
{
public bool Login(UserInformation user)
{
//stuff...
}
}
[DataContract]
public class UserInformation
{
[DataMember(IsRequired = true)]
public string UserName;
[DataMember(IsRequired = true)]
public string Password;
[DataMember(IsRequired = true)]
public bool IsNotEncrypted;
}
public interface IUserInformation
{
UserInformation UserInformation { get; set; }
}
So, I found the answer to my question.
Someone attempted to point me in the right direction with a mention of the JSON.stringify() method, but it took me a little effort to get it implemented correctly.
In the end, I used WireShark to sniff out the http request, see what was actually being sent and received, and observe that not only did I need to stingify the data, but I also needed to specify the content type.
Here is the final code.
// This is the URL that is used for the service.
var serviceUrl = "http://services.xiine.com/Xiine/Live/AccountService/rest/json/Login";
// This is the JSON object passed to the service
var userInfo = {
"UserName": null,
"Password": null,
"IsNotEncrypted": true
};
// $.ajax is the longhand ajax call in JQuery
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/json; charset=utf-8",
// Stringify the userInfo to send a string representation of the JSON Object
data: JSON.stringify(userInfo),
dataType: "json",
success: function(msg) {
console.log(msg);
}});
in the interface for your service, you need to have the OperationalContract attribute and in that attribute, you need to set the RequestFormat. Here is an example of what it might look like.
[OperationContract, WebInvoke(UriTemplate = "/runGenericMethodJSON", Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]