I'm new to the world of ajax requests and asp.net. I'm trying to send an ajax request to aspx page. When I'm debugging the server side it seems to be ok, but the response printing the error message?
I tried to change the Response.ContentType but it didn't solve my problem. Any suggestions?
Here is my javascript code:
function onclick(){
$.ajax({
url: "SandaAJAXRequests.aspx",
type: "post",
data: JSON.stringify({ "first": "getevent","second":"data" }),
dataType: 'json',
success:
function (response)
{
roundNumber = 1;
numberofblackwins = 0;
numberofredwins = 0;
ifBattleIsOver = false;
$("#round").text(roundNumber);
var result = response.split(",");
name1 = result[1];
name2 = result[2];
var r = confirm("Is " + name1 + " the black competitor?");
if (r == true) {
$("#black_competitor_name").text(name1);
$("#red_competitor_name").text(name2);
}
else {
$("#black_competitor_name").text(name2);
$("#red_competitor_name").text(name1);
}
},
error: function (xhr) {
alert("Problem sending data to the server");
}
});
}
Here is my server side:
protected void Page_Load(object sender, EventArgs e)
{
string jsonString = String.Empty;
Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
string data = jsonString.Replace("\\", "");
char[] seperators = { ':', ',', '"' };
string[] a = data.Split(seperators);
string t = a[4];
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
object serJsonDetails = javaScriptSerializer.Deserialize(jsonString, typeof(object));
string requestType = serJsonDetails.ToString();
switch (t)
{
case "getevent":
SandaEvent current = (SandaEvent)Application["CurrentEvent"];
Response.ContentType = "text/plain";
String response = current.id + "," + current.name1 + "," + current.name2;
Response.Write(response);
Response.End();
break;
}}
You are missing contentType in $.ajax({});
Content-type: application/json; charset=utf-8
is necessary when you are a doing a post using $.ajax({})
Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding.
Related
I am creating json object to save data and then sending it to the servlet. But when I try to retrieve the object and display its contents in java servlet, I am not getting any response from server. Even though a simple System.out.println() message on browser.
angular.module('TestApp').controller('PostController',
function($scope, $rootScope, $http) {
$scope.retriveDataAndConvertToJson = function() {
var collectionJsonData = new Array();
for (var i = 0; i < rowID.length; i++) {
collectionJsonData.push({
"payment_term": document.getElementById("textfield1" + rowID[i])
.getAttribute("value"),
"payment": document.getElementById("textfield2" + rowID[i])
.getAttribute("value"),
"party": document.getElementById("textfield3" + rowID[i])
.getAttribute("value"),
"amount": document.getElementById("textfield4" + rowID[i])
.getAttribute("value")
});
console.log(collectionJsonData[i].payment_term);
console.log(collectionJsonData[i].payment);
console.log(collectionJsonData[i].party);
console.log(collectionJsonData[i].amount);
console.log("==========================");
} //End of For loop
var xhr = new XMLHttpRequest();
var url = "http://" + document.location.host + "/SivaTask/processInfo";
console.log("The url is " + url);
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
var data = JSON.stringify(collectionJsonData);
xhr.send(data);
}
});
Servlet
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String contextName = req.getRequestURI();
String url = contextName.substring(contextName.indexOf('/', 2) + 1);
System.out.println(url);
String jsonData = "";
resp.setContentType("text/plain");
System.out.println("hello world");
PrintWriter out = resp.getWriter();
out.write("The information is : ");
System.out.println("hello world2");
}
I am passing an array from servlet through ajax call. But when I am trying to get the same in servlet side, I am getting null pointer exception. I tried using one of the examples given in SO. Since I'm a newbie, any help would be appreciated!
$.ajax({
url : 'insertserv1',
type: 'POST',
dataType: 'json',
data: {tablearray:tablearray} ,
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
// to get data from inspection table
{ var tablearray = [];
$("#tab_logic tr.data").map(function (index, tr) {
$(this).find('td').each(function(){
var $data = $(this).html();
if($(this).find("select").length > 0) {
var $x = $(this).find("select").val();
}else{
var $x = $(this).find("input[type='text']").val();
}
tablearray.push($x);
});
});
}
String[] tablearray = request.getParameterValues("tablearray[]");
for (int i = 0; i < tablearray.length; i++) {
System.out.println(InspTableArray[i]);
}
If I have understood correctly, this is what you would be looking for:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
JSONObject jObj = null;
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
String str = null;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
try
{
jObj = new JSONObject(sb.toString()); //This is your JSON data.
}
catch (JSONException e)
{
e.printStackTrace();
}
}
I want to post JSON data from JSP to Spring MVC Controller. For this, I am using Javascript Ajax. Please help me on this. I searched on net but could not get the solution for my problem.
When I execute the code I get bellow error:
Parse Error: Incorrect syntax Error Unexpected End of Inputand some Ids get printed in a console as below:person#35fcfbc0, person#35fcfbc5`
But I want the value of data1, data2 and data3 to be printed in console;
My Json String as below
{“persons”:
[
{“data1”:”1000”, “data2”:”false”,”data3”:”Holiday”},
{“data1”:”1000”, “data2”:”false”,”data3”:”Holiday”}
]
}
I am using below Javascript and Ajax to post Data
<script type="text/javascript">
$(document).ready(function()
{
var sJson
var ssJson
function dataRow(value1,value2,value3)
{
this.data1 = value1;
this.data2 = value2;
this.data3 = value3;
}
$('#help_button2').click(function()
{
// create array to hold your data
var dataArray = new Array();
var Vars
// iterate through rows of table
// * Start from '2' to skip the header row *
$(".case").each(function(i)
{
if (this.checked)
{
var Vars=i+1
//alert("Checkbox at index " + Vars + " is checked.");
var Vars1= $("#myTable tr:nth-child(" + Vars + ") td").eq(18).find('select').val()
//alert(Vars1)
//alert(Vars)
if (Vars1!="nooption")
{
dataArray.push
(
new dataRow
(
$("#myTable tr:nth-child(" + Vars + ") td").eq(1).html(),
$("#myTable tr:nth-child(" + Vars + ") td").eq(18).find('select').val(),
$("#myTable tr:nth-child(" + Vars + ") td").eq(19).find('select').val()
)
);
} //else {alert("Please Select Option for Error_NoError ")
//return false;
//}
}
});
ssJson1 = JSON.stringify({"persons" : dataArray });
alert(ssJson)
alert(ssJson1)
$.ajax({
url:'<%=webUrl%>/data/data',
type: 'POST',
dataType: 'json',
data:ssJson1,
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.data1 + " " + data.data2 + " " + data.data3);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er+ssJson);
}
});
});
});
</script>
My Pojo Class
public class Person implements Serializable{
private int data1;
private String data2;
private String data3;
public int getData1() {
return data1;
}
public void setData1(int data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public String getData3() {
return data3;
}
public void setData3(String data3) {
this.data3 = data3;
}
My Controller code:
#RequestMapping(value="/data",method=RequestMethod.POST)
public #ResponseBody void data(#RequestBody PersonList persons) throws
ParseException, IOException
{
List<Person> data1s=persons.getPersons();
System.out.println(data1s);
}
I need to call a c# function in my code behind using a javascript where i set two variables that i need to call my function with these variables, following my codes:
C# code behind:
public string CallWebMethod(string url, Dictionary<string, string> dicParameters)
{
try
{
byte[] requestData = this.CreateHttpRequestData(dicParameters);
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.KeepAlive = false;
httpRequest.ContentType = "application/json; charset=utf-8";
httpRequest.ContentLength = requestData.Length;
httpRequest.Timeout = 30000;
HttpWebResponse httpResponse = null;
String response = String.Empty;
httpRequest.GetRequestStream().Write(requestData, 0, requestData.Length);
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream baseStream = httpResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(baseStream);
response = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private byte[] CreateHttpRequestData(Dictionary<string, string> dic)
{
StringBuilder sbParameters = new StringBuilder();
foreach (string param in dic.Keys)
{
sbParameters.Append(param);//key => parameter name
sbParameters.Append('=');
sbParameters.Append(dic[param]);//key value
sbParameters.Append('&');
}
sbParameters.Remove(sbParameters.Length - 1, 1);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(sbParameters.ToString());
}
and this is my javascript :
<script>
function SendNeedHelpLinkTrace() {
var keysToSend = ['pCatchLinkVirement', 'pCatchLinkCarteBancaire', 'pCatchLinkRechargePaiementFactureTelecom', 'pCatchLinkPaiementVignetteImpotTaxe', 'pCatchLinkPaiementFactureEauElectricite', 'pCatchLinkServiceFatourati', 'pCatchLinkCihExpress', 'pCatchLinkEdocuments']
var lChannelId = document.getElementById('<%= HiddenChannelId.ClientID%>').value;
var lServiceId = "900149";
var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;
//alert(lClientId);
var lData = keysToSend.reduce(function(p,c){
var _t = sessionStorage.getItem(c);
return isEmpty(_t) ? p : p + ' | ' + _t;
}, '')
function isEmpty(val){
return val === undefined || val === null;
}
var lCollect;
console.log(lClientId);
console.log(lData);
alert(lData);
// this is the dictionnary:
lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;
console.log(lDataCollected);
//this is the url:
var url="http://10.5.230.21:4156/CatchEvent.asmx/CollectData";
sessionStorage.clear();
}
How should i proceed ?
I am new to Json datatype. how to retrive it.. please look at the code below.
This is my Javascript code:
function fnDeleteSelected() {
var count_checked = $("[name = 'myChkBox[]']:checked").length;
var arrayOfID = [];
$(':[name = "myChkBox[]"]:checked').each(function () {
arrayOfID.push($(this).val());
});
var test = JSON.stringify(arrayOfID);
alert(test);
if (count_checked == 0) {
alert("Please Select a Student to delete");
return false;
}
else {
var confirmDel = confirm("Are you sure you want to delete this?");
if (confirmDel == true) {
jQuery.ajax({
url: baseUrl + "DeleteSelected/",
type: 'Post',
dataType: 'Json',
data: { Parameters: test },
success: function (msg) {
jQuery("input:checkbox:checked").parents("tr").remove();
}
});enter code here
}
}
}
here data send to controller is parameters where parameters = ["143","144","145"]
and my controller is: where Parameters is passed as "[\"143\",\"144\",\"145\"]"my question is how to parse the Parameters so that it can be embedded in sql statement
public JsonResult DeleteSelected(string [] Parameters)
{string strConn = "Data Source=localhost;Initial Catalog=Information;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(strConn);
string strSql = "DELETE FROM dbStudent where ID in";
SqlCommand myCommand = new SqlCommand(strSql, conn);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(Parameters, JsonRequestBehavior.AllowGet);
}
what should be there in strSql..??
You can change your ajax post to be like that: (the contentType is important)
jQuery.ajax({
url: baseUrl + "DeleteSelected/",
type: 'Post',
dataType: 'json',
data: JSON.stringify(arrayOfID),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
jQuery("input:checkbox:checked").parents("tr").remove();
}
});
and your action method to be like that
public JsonResult DeleteSelected(int[] Parameters)
{
string strConn = "Data Source=localhost;Initial Catalog=Information;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(strConn);
var strSql = "DELETE FROM dbStudent where ID IN (" + String.Join(",", Parameters) + ")";
SqlCommand myCommand = new SqlCommand(strSql, conn);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(Parameters, JsonRequestBehavior.AllowGet);
}
You can convert your array to int array
int[] myInts = Parameters.Select(int.Parse).ToArray();
Then
var query = "DELETE FROM dbStudent where ID IN (" +
String.Join(",", myInts ) + ")";