500 internal server error ajax/javascript - javascript

I know there is some posts on this but they did not help me.
My program run's and when I click on a button to fire a javascript nothing happens, or no response. In chrome debugger under network tab I see in red
http://wms-wsdl.company.net/mobile.asmx/ContactGet?searchField=test&office=97&person=119&user=531&organization=14
when I click on that link it shows a red circle with 500 internal server error.
If I click on the response I see:
{"Message":"Invalid JSON primitive: test.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext context, JavaScriptSerializer serializer, WebServiceMethodData methodData)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
Now I have no Idea what that means.
When I double click in that lick It shows me all my data that is supposed to be inserted into a list view (data is xml) e.g. <string xmlns="http://company.net/">
[ { "Name": "Myar", "Surname": "Tester", "Mobile": "080000000", "Email": "" ......}, etc
My javascript function is as follows:
function initContactView()
{
alert("ContactView start test")
var txtSearch = $("#searchTextField").val();
$.ajax({
type: "GET",
dataType:"json",
contentType: "application/json; charset=utf-8",
crossDomain: true,
url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
success:successContact,
failure: function (msg) {
console.log(msg);
alert(msg)
}
});
alert("ContactView End Test");
}
function successContact(data) {
alert("Success Start Test");
window.location = "#contactsview";
$("#lstView_contacts").kendoMobileListView({
dataSource: JSON.parse(data.d),
template: $("#lstView_contact_Template").html(),
endlessScroll: true,
scrollThreshold: 8
});
alert("Success Start Test");
}
searchTextField comes from my HTML textbox.
What I seem to find odd is that it gets the data it should, I have verified that in the xml but still gives an error.
My webservice that I am using is a json webservice.
It alerts both alerts but I think it goes into failure.
The response i get in debugger is:
<string xmlns="http://company.net/">[
{
"Name": "Myar",
"Surname": "Tester",
"Mobile": "080000000",
"Email": "test#test.com"
}]</string
How my webservice looks:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function ContactGet(ByVal searchField As String, ByVal office As String, ByVal person As String, ByVal user As String, ByVal organization As String) As String
Dim objSearch As New ArrayList
Dim objSearching As New Search
Dim intResult As Integer
Try
'Test String
intResult = objSearching.SearchByKeyword(searchField, person, office, organization, user, company.ETMyProperty.Search.enmSearchType.enmContact, objSearch)
Dim objContact As New Person
Dim dt As New DataTable("Contacts")
Dim col_Name As New DataColumn("Name", GetType(String))
dt.Columns.Add(col_Name)
Dim col_Mobile As New DataColumn("Surname", GetType(String))
dt.Columns.Add(col_Mobile)
Dim col_Office As New DataColumn("Mobile", GetType(String))
dt.Columns.Add(col_Office)
Dim col_Category As New DataColumn("Email", GetType(String))
dt.Columns.Add(col_Category)
Dim dr As DataRow
For i = 0 To objSearch.Count - 1
dr = dt.NewRow()
dr("Name") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return2
dr("Surname") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return3
dr("Mobile") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return6
dr("Email") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return7
dt.Rows.Add(dr)
Next
Dim serializer As New JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object) = Nothing
'serialize dt row to json output
For Each drow As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
Dim str_json = JsonConvert.SerializeObject(dt, Formatting.Indented)
Return str_json
Catch ex As Exception
Return Nothing
End Try
End Function
I have been on this for a few days now and I cant seem to get any solution.
Any help?

Refering to jQuery doc, you should use error: function() {...}, and not failure.
The value for the key success should be a function, and not a variable. Something like success: successContact(),
For debugging in some usefull way, you NEED to know, if your ajaxcallback calls success or error. If it does not call success, it is probably because the answer has no application/json content-type header, or your json is wrong.

Cause you are seding a GET request, you have to remove or define the contentType as:
application/x-www-form-urlencoded; charset=UTF-8
function initContactView()
{
alert("ContactView start test")
var txtSearch = $("#searchTextField").val();
$.ajax({
type: "GET",
dataType:"json",
crossDomain: true,
url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
success:function (data) {successContact(data);},
failure: function (msg) {
console.log(msg);
alert(msg)
}
});
alert("ContactView End Test");
}
Check too if the error is when the Request Begin on the ASMX or the error is on the ASMX Response.
Check this for Details Get Request:
Do I need a content type for http get requests?
Also configure your webservice to return JSON. The response isn't json.
So, the dataType now is not correct. To retrun ONLY json change your WebMethod.
[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write("Hello World");
//return "Hello World";
}
Important: if you are using webmethods you don't need to parse the datatable to json, webservice will do it for you.
So change this to:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function ContactGet(ByVal Parameters....) As DataTable
After all, this is an example that works with the .net serialization
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Collections;
using System.Linq;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<Dictionary<string, object>> HelloWorld()
{
DataTable TestTable = new DataTable();
TestTable.Columns.Add("Name");
TestTable.Columns.Add("Id");
DataRow Row = TestTable.NewRow();
Row["Name"] = "James";
Row["Id"] = 0;
TestTable.Rows.Add(Row);
return RowsToDictionary(TestTable);
}
private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)
{
List<Dictionary<string, object>> objs =
new List<Dictionary<string, object>>();
foreach (DataRow dr in table.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
for (int i = 0; i < table.Columns.Count; i++)
{
drow.Add(table.Columns[i].ColumnName, dr[i]);
}
objs.Add(drow);
}
return objs;
}
}
Please, check another serializers like http://james.newtonking.com/json. Perhaps you can use better a ASHX handler than a ASMX for returning JSON.

Related

Pass Multiple Parameters from Jquery to ASPX web method not working

I have one array which contain value in following format
var checkedvalue = [];
var x = "230";//Just now constant value pass
var y = "450";
checkedvalue.push({
xCordi : x,
yCordi : y,
bPart:txtName.value
});
in my code i have two button, 1 for push the TEXTBOX data in my array.
Now on second button click i want to pass this value to my web method and perform operation.
$AddtoDB.on('click', function () {
if ( $("#<%= divdynamicData.ClientID %>").is(':empty')){
alert("No Data Found");
}
else{
var ImageName="test.jpeg";
var ImagePath ="c:\drive";
IndertIntoDB(ImageName,ImagePath,checkedvalue);
}
});
the function is called when there is data.
function IndertIntoDB(ImageName,ImagePath,checkedvalue){
//alert(ImageName);
//alert(ImagePath);
//$.each( checkedvalue, function( key, value ) { alert( value.xCordi + ": " + value.yCordi +":"+ value.bPart );});
$.ajax({
type: "POST",
url: "ImageHotSpot.aspx/GetSaveData",
data: JSON.stringify({ iName: ImageName,iPath:ImagePath,iData:checkedvalue }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("DataInserted");
}
});
Now i want to iterate the checkarray in web method but i got error.
//}
[System.Web.Services.WebMethod]
public static void GetSaveData(string iName, string iPath, string[] iData)
{
}
This answer is at first glance since i was not able to extract more info.
I hope this helps.
This is what your checkedvalue variable looks like in js code.
var checkedvalue = [];
var x = "230";//Just now constant value pass
var y = "450";
checkedvalue.push({
xCordi : x,
yCordi : y,
bPart:txtName.value
});
And this is your ajax request data.
data: JSON.stringify({ iName: ImageName,iPath:ImagePath,iData:checkedvalue })
Here is the method that is called with ajax.
public static void GetSaveData(string iName, string iPath, string[] iData)
Now i am not very familiar with ajax calling aspx. Usually there is a controller with MVC.
Since you don't mention the error in the original post.
My guess is you get a Null reference exception with checkedvalue->iData.
C# cannot deserialize a complex object from javascript without having the specifics. Meaning a c# object, it passes null.
An array of strings would work like this.
var checkedvalue = [];
checkedvalue.push("Hello"); //etc push other strings
You need a c# class like this one. Assuming they are of type string all three. From context i believe xCordi, yCordi are of type int feel free to change them. Also remove the "" from your js code.
public class SomeClass{
public string xCordi {get;set;} //change string to int
public string yCordi {get;set;} //change string to int
public string bPart {get;set;}
}
public static void GetSaveData(string iName, string iPath, string[] iData) -> public static void GetSaveData(string iName, string iPath, List<SomeClass> iData)
or public static void GetSaveData(string iName, string iPath, SomeClass[] iData)
Then your ajax method should work and c# should be able to deserialize the object.

ASP.NET ajax call using Jquery adds to list

I have a simple UI where I am trying to populate the select dropdown using data from database. I am doing this by a AJAX call to fetch the data.
The C# web method looks like
private static List<List<string>> componentTypeDropDown = new List<List<String>>();
private void loadDropDownList()
{
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}
[WebMethod]
public static ArrayList getComponentType()
{
ArrayList compType = new ArrayList();
for (int i=0;i<componentTypeDropDown.Count();i++)
{
compType.Add(new { label = componentTypeDropDown[i][0], value = componentTypeDropDown[i][1] });
}
return compType;
}
The AJAX call looks like
$.ajax({
type: "POST",
url: "salesQuote.aspx/getComponentType",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("karan");
},
error: function () {
alert("Failed to load names");
}
});
Every time I refresh or even restart the server the value of msg in success callback has previous values as well. For example lets say my database has value 1,2. First time I call ajax msg is 1,2 if i refresh the value is 1,2,1,2 and so on. Even if I close the server and start again the value would be 1,2,1,2,1,2
Your ComponentTypeDropdown is a static, so every time you call 'LoadDropdownList' this list will add new items, whitout removing the old ones.
I would suggest that you add following line in the loadDropDownList method:
private void loadDropDownList()
{
componentTypeDropdown.RemoveAll();
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}

getting a 403 forbidden error when calling a .NET function from jQuery AJAX

I have this jQuery code that runs from a form submission and loops to insert a certain number of records into an SQL table. The ajax portion of the code calls a VB function in a webmatrix page called Helpers.vbhtml
function InsertSheeter()
{
var textDate = $('#textDate').val()
var Workorder = $('#textWorkorder').val()
var Material = $('#dropdownMaterial').val()
var Shift = $('#dropdownShift').val()
var Sheeter = $('#dropdownSheeter').val()
var FoilNum1 = $('#textFoilNum1').val()
var FoilNum2 = $('#textFoilNum2').val()
var FoilNum3 = $('#textFoilNum3').val()
var Printline = $('#dropdownPrintline').val()
var Section = $('#dropdownSection').val()
var Comments = $('#textComments').val()
var Employee = $('#dropdownEmployees').val()
var a = 0
while (a < Section)
{
switch (a)
{
case 0:
blockSection = "1"
break;
case 1:
blockSection = "2"
break;
case 2:
blockSection = "3"
break;
}
var str = {pDate: textDate, pSheeter: Sheeter, pShift: Shift,
pEmployee: Employee, pWorkorder: Workorder, pBlockSection: blockSection,
pComments: Comments, pFoilNum1: FoilNum1, pFoilNum2: FoilNum2,
pFoilNum3: FoilNum3, pPrintline: Printline, pMaterial: Material}
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Helpers.vbhtml/InsertSheeter",
data: JSON.stringify(str),
dataType: "json",
success: function(data)
{
OpenReports(Workorder, data.d)
},
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert(errorMessage);
}
});
a++;
}
}
This is the VB.NET function that gets called:
I created according to how I understand the documentation, a webservice using a vbhtml page in the App_Code directory. Here is a snippet of my vb code InsertSheeter as previously referenced in this post.
#Imports Microsoft.VisualBasic
#Imports System
#Imports System.Web
#Imports System.Web.Services
#Imports System.Xml.Serialization
#Functions
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<WebMethod>
Public Shared Function InsertSheeter(ByVal pDate As DateTime, ByVal pSheeter As String, ByVal pShift As String,
ByVal pEmployee As String, ByVal pWorkorder As String,
ByVal pBlockSection As String, ByVal pComments As String, ByVal pFoilNum1 As String,
ByVal pFoilNum2 As String, ByVal pFoilNum3 As String, ByVal pPrintline As String,
ByVal pMaterial As String) As String
Dim db As Database
db = Database.Open("Nomex")
Dim strQuery As String
Dim pBlockNumber As String
pBlockNumber = GetBlockNumber(pBlockSection, pWorkorder, pSheeter, pMaterial)
strQuery = "INSERT INTO dbo.NomexSheeter (SheeterDate, Sheeter, Shift, Employee, WorkOrder, BlockNumber, BlockSection, " _
& "Comments, FoilNum_1, FoilNum_2, FoilNum_3, PrintLine, Material) " _
& "VALUES (#0, #1, #2, #3, #4, " _
& "#5, #6, #7, #8, #9, #10, #11, #12)"
db.Execute(strQuery, pDate, pSheeter, pShift, pEmployee, pWorkorder, pBlockNumber, pBlockSection,
pComments, pFoilNum1, pFoilNum2, pFoilNum3, pPrintline, pMaterial)
db.Close
Return pBlockNumber
End Function
End Functions
after calling the jQuery function InsertSheeter() i still get the 404 Forbidden error. I don't understand what I am doing wrong. Webmatrix documentation and posts online seem to support this idea.
Perhaps your AJAX request is going over HTTP and you have "Require SSL" set for your application?
Maybe I'm wrong but I think Helpers is not intended to be called by client side.
Helpers In ASP.NET Web Pages are components that are stored as .cshtml files, and are meant to promote reusability by allowing other ASP.NET Web Pages to access them using the familiar object.method([argsā€¦]) syntax in views.
Usefull link about helpers.
What you seems to want is a web service in asmx format that allow http Post request and send and receive JSON.
Link to create web services.
Link to enable http Post.
Link to enable JSON .

How to download file from System.Web.HttpContext.Current.Response.BinaryWrite(byteArray); from javascript instead of C#

I have a C# method that works if you call it from another C# method, but not from javascript. How do I make it work from my ajax call?
I need to get a file based on an ID that is passed in, so I have an ajax post with the statusID. That ID is pulling the proper file in my C# method, it is just not giving the file save dialog.
However, if I call this from my C# page load method with a static statusID for testing purposes, it works just fine.
Here is the C# method:
public void Get_Attachment_By_StatusID(int statusID)
{
SqlDataReader _reader = null;
string _connString = "Data Source=133.31.32.33;Initial Catalog=Reports;Integrated Security=True";
string sql = "SELECT a.StatusID ,a.DocumentName ,a.MIMETypeID ,a.Binary ,a.CreatedDate ,a.CreatedBy " +
",b.MIMEType FROM Attachments a Inner join MIME_Types b on a.MIMETypeID = b.ID " +
"WHERE [StatusID] = {0} ";
sql = string.Format(sql, statusID);
try
{
_connection = new SqlConnection(_connString);
_connection.Open();
using (SqlCommand cmd = new SqlCommand(sql, _connection))
{
cmd.CommandType = System.Data.CommandType.Text;
_reader = cmd.ExecuteReader();
if (_reader.HasRows)
{
while (_reader.Read())
{
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.ContentType = _reader["MIMEType"].ToString();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + _reader["DocumentName"].ToString() + ";");
byte[] b = (byte[])_reader["Binary"];
System.Web.HttpContext.Current.Response.BinaryWrite(b);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
}
_reader.Close();
_connection.Close();
}
}
catch (Exception ex)
{
//Log exception to error Logging app
string err = ex.ToString();
}
finally
{
if (_connection != null)
_connection.Close();
if (_reader != null)
_reader.Close();
}
}
Here is how I am calling it from my page, in javascript:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID';
$.ajax({
url: url,
type: 'post',
cache: false,
data: JSON.stringify({ "statusID": statusID }),
contentType: 'application/json',
success: function (data) {
}
});
}
Nothing happens. In Chrome, I don't see anything in the javascript console, and in IE, my console spits this out: "XML5619: Incorrect document syntax."
Again, if I go into the controller, and call the method in my page load method, it presents the save file dialog and saves the file just fine. So I must be doing something wrong with my javascript/jquery/ajax...
I am new to MVC4 and know I'm missing something here. What am I missing?
Use window.open('CONTROLLER_URL/STATUS_ID'); instead of an AJAX request.
<a target="_blank" href="javascript:window.open('/Home/Get_Attachment_By_StatusID/12345');">Test</a>
Here's one suggestion, largely based on answer from LastCoder:
Decorate your action with the [HttpGet] attribute and change the parameter name to id:
[HttpGet]
public void Get_Attachment_By_StatusID(int id) ...
Now in your client-side code, simply do this:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID/'+statusID;
window.location=url;
}

Javascript Deserialize is returning the class name instead of actual object

So I'm running GetServerUpdateProgress() in the controller from a $.ajax call on my page. While debugging I can confirm that the variable: myobj is being properly created and filled with the correct data.
But when on the $.ajax success, I'm not getting the data in json format, instead I'm getting
a string of "TrackerMVC.ClassLib.UpdateAJAXProgress" - the objects type.
I've done this in the past with a .svc webservice and didn't have any problems getting the object values using this exact same method.
Any ideas? Thanks!
method:
public UpdateAJAXProgress GetServerUpdateProgress()
{
string BASE_URL = "http://localhost:55094";
string url = BASE_URL + "/Home/UpdateProgress";
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultNetworkCredentials; // uses current windows user
var myojb = new UpdateAJAXProgress();
var response = (HttpWebResponse)wr.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (UpdateAJAXProgress)js.Deserialize(objText, typeof(UpdateAJAXProgress));
return myojb; // during debugging this object has the correct values in the correct format
}
class:
public class UpdateAJAXProgress
{
public int Completed { get; set; }
public int Total { get; set; }
}
javascript:
$.ajax({
type: "POST",
async: false,
url: '#(Url.Action("GetServerUpdateProgress","Charts"))',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data); // data being returned is: "TrackerMVC.ClassLib.UpdateAJAXProgress"
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
You're misusing MVC.
You should declare your function as returning ActionResult, then return Json(myobj).
If you return a non-ActionResult from an MVC action, MVC will convert it to a string by calling ToString().

Categories

Resources