jquery autocomplete to fill a javascript array? - javascript

I wanted to add autocomplete to a text box I had on my form. I found an excellent SO thread that entailed this right here: https://stackoverflow.com/a/5973017/168703 This was exactly what I needed because it also only showed the autocomplete when someone typed an # symbol.
It was something to the effect of this:
$("#ucAddActionItemIssueActions_txtActionItem")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: 0,
source: function(request, response) {
var term = request.term,
results = [];
if (term.indexOf("#") >= 0) {
term = extractLast(request.term);
if (term.length > 0) {
results = $.ui.autocomplete.filter(
availableTags, term);
} else {
results = ['Start typing...'];
}
}
response(results);
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
var email = GetEmail(ui.item.value);
email = email + ";";
emails.push(email);
$("#ucAddActionItemIssueActions_hdnEmails").val(emails.join(""));
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
return false;
}
});
Pay close attention to the source portion as it forced me to declare something like this:
var availableTags = [
"jdoe",
"tsmith",
"mrighty",
"tstevens",
"ktripp",
"tram",
];
That is my autocomplete suggestions would be inside of the js file...but this is the only part I did not want. I have to load the data from a database. Unfortunately I am dealing with an ancient .net framework prolly pre 2.0 app. Its vb.net and there is no linq or lists or all the good stuff. Fine I thought..I could probably create a .asmx file that added strings to an array list, converted it back to a string array and returned it in the .asmx file. Something to this effect (this was just a test no pulling data just yet from a database):
Imports System.Web.Services
Imports System.Collections
<System.Web.Services.WebService(Namespace := "http://tempuri.org/myapp.com/GetLogins")> _
Public Class GetLogins
Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
Public Sub New()
MyBase.New()
'This call is required by the Web Services Designer.
InitializeComponent()
'Add your own initialization code after the InitializeComponent() call
End Sub
'Required by the Web Services Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Web Services Designer
'It can be modified using the Web Services Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
components = New System.ComponentModel.Container()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
'CODEGEN: This procedure is required by the Web Services Designer
'Do not modify it using the code editor.
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
#End Region
' WEB SERVICE EXAMPLE
' The HelloWorld() example service returns the string Hello World.
' To build, uncomment the following lines then save and build the project.
' To test this web service, ensure that the .asmx file is the start page
' and press F5.
'
'Public Function HelloWorld() As String
' Return "Hello World"
'End Function
<WebMethod()> _
Public Function GetLogins() As String()
Dim myList As ArrayList
myList.Add("jstevens")
myList.Add("jdoe")
Dim arr() As String = CType(myList.ToArray(Type.GetType("System.String")), String())
Return arr
End Function
End Class
As mentioned this was just a test so I'm just adding two items in a string array and returning it. Now I am pretty unsure how to change my jquery code to incorporate this....
I thought I would add something like this:
$.ajax({
url: "GetLogins.asmx/GetLogins",
data: "{ 'resName': '" + request.term + "' }",
datatype: "json",
type= "POST",
contentType: "application/json; charset=utf-8"
})
But I am not sure how to incorporate that in the original jquery as my jquery skills are zilch...
Can anyone help me understand this and put this together so it may actually work. Once I get the test working I can then modify it to pull data from the database. Am I on the right path?
EDIT
Here's what I have
$("#ucAddActionItemIssueActions_txtActionItem")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: 0,
source: function (request, response) {
//get client value
var c = $("#ucAddActionItemIssueActions_ddlClientAssignTo").val();
var params= '{"ClientID":"' + c + '"}';
$.ajax({
url: "GetLogins.asmx/GetLogins",
data: params,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
var email = GetEmail(ui.item.value);
email = email + ";";
emails.push(email);
$("#ucAddActionItemIssueActions_hdnEmails").val(emails.join(""));
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join("");
return false;
}
});
But my app is throwing an internal server error 500. With the following exception:
System.InvalidOperationException: Request format is invalid:
application/json; charset=UTF-8. at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at
System.Web.Services.Protocols.WebServiceHandler.Invoke() at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
Here is my webservice:
Imports System.Web.Services
Imports System.Collections
<System.Web.Services.WebService(Namespace := "http://tempuri.org/quikfix.jakah.com/GetLogins")> _
Public Class GetLogins
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetLogins(ByVal ClientID As Integer) As String()
Dim myList As New ArrayList
myList.Add("jstevens")
myList.Add("jdoe")
myList.Add("smartin")
Dim arr() As String = CType(myList.ToArray(Type.GetType("System.String")), String())
Return arr
End Function
End Class
Again this is an old 1.1 .net application, do I need something in the web config file to represent this .asmx file? The parameters in the web method match the parameters of the ajax call so what could be causing this?

I think the problem here is that web services expect XML or text. JSON won't work.
You can try changing your content-Type (in your ajax call) to text and returning a string instead of a string array from your GetLogins method. That way you can serialize your string array to a JSON string using a JSON converter and return that.

Related

ASP .NET MVC - Ajax POST action fail

I'm trying to do a simple action with some JavaScript code. I've got some items on a scheduler (DevExpress scheduler component). When I'm double clicking on an appointment (an item then), it should raise an JS function which is the case. My function should get the selected appointment id and pass it to Controller Action. Here is my JS code :
function DoubleClick() {
debugger;
var apt = GetSelectedAppointment(scheduler);
var aptid = apt.appointmentId;
$.ajax({
type: "POST",
url: "/Home/GetAppId",
data: { id: aptid },
dataType: 'json',
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
}
And here is my C# code :
[HttpPost]
public JsonResult GetAppId(int id)
{
context = new SchedulingDataClassesDataContext();
DBAppointment app = (from a in context.DBAppointment where a.UniqueID == id select a).FirstOrDefault();
return Json(new {rep = app});
}
As you can see in my JS code, I'm not doing anything special in case of success. However, I never reach the success part. Plus, when I'm looking at the Chrome dev tool (F12), I'm getting that red error message.
POST http://localhost:25206/Home/GetAppId 500 (Internal Server Error)
Anything that I'm doing wrong?
Man, you need to force things as follows
return Json(new {rep = app},"text/json",JsonRequestBehavior.AllowGet);
In addition, mind your navigation properties (if any) in order to avoid circular reference
According to your error your problem somewhere in select your data from DB or creating anonymous object when you try to serialize it to Json. I rewrite your select to simplify it and not creating any anonymous objects when return it from Controller like this:
[HttpPost]
public JsonResult GetAppId(int id)
{
context = new SchedulingDataClassesDataContext();
DBAppointment app = context.DBAppointment.FirstOrDefault(x => x.UniqueID == id);
return Json(app);
}
Does it work like this?
Please remove the name of the property in ajax data and edit that property as below.
function DoubleClick() {
debugger;
var apt = GetSelectedAppointment(scheduler);
var aptid = apt.appointmentId;
$.ajax({
type: "POST",
url: "/Home/GetAppId",
data: aptid,
dataType: 'json',
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
}
and edit your controller as follows
[HttpPost]
public JsonResult GetAppId([FromBody]int id)
{
//...
}
Please read this blog post which is a good read and allowed me to understand what's going on.
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
The original question that I asked
Simple post to Web Api
Try changing the last line of the method to:
return Json(new { rep = app }, JsonRequestBehavior.AllowGet);
You need to tell C# to allow the json to be returned to the client.

Asp.Net MVC 4 Automatically bind model from array of objects in form post

I have built an array of objects in JavaScript and want to post them back to the server via Ajax (Im using jQuery)
The JavaScript object array looks like this:
var columns = [
{ name: 'col 1', source: 'whatever', hidden: false, width: 50 },
...
];
Im posting it back like this:
$.post('/MyController/MyAction', { 'columns': columns });
On the controller action Im currently getting this:
I have a c# object called JqColumn that I want to bind the post into, it looks like this:
public class JqGridColumn
{
public string name;
public string source;
public int width;
public bool hidden;
}
So I thought that adding a parameter in the controller action of type JqGridColumn[] columns would automatically bind the posted data, but it doesn't (it generates a array, with the correct number of elements, but each item in the array has blank values)
Can anyone tell me what Im doing wrong? Thanks!
UPDATE
At present, I am manually binding the items in my controller action as follows:
public void ColumnChooser(JqGridColumn[] columns)
{
for (int i = 0; i < columns.Length; i++)
{
columns[i].hidden = bool.Parse(Request.Form["columns[" + i + "][hidden]"]);
columns[i].width = int.Parse(Request.Form["columns[" + i + "][width]"]);
columns[i].name = Request.Form["columns[" + i + "][name]"];
columns[i].source = Request.Form["columns[" + i + "][source]"];
}
return;
}
...which works fine, but I'd really like to know the .Net MVC (correct) way to do it!
Since you didn't register a specific ModelBinder for the JqGridColumn type, the DefaultModelBinder will be used. But:
It won't bind Fields, only public Properties.
The expected format for Array binding is columns[0].name while you're actually posting columns[0][name].
The problem could be solved easily if you'll simply send your columns in JSON format instead of Name-Value-Pairs:
$.ajax({
url: '/MyController/MyAction',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ columns: columns })
});
Yet, if you don't like to change your class, you could register a ModelBinder specific for JqGridColumn and have it working even with Fields and current jQuery serialization:
public class JqGridColumnBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
string name = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[name]").AttemptedValue;
string source = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[source]").AttemptedValue;
int width = (int)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[width]").ConvertTo(typeof(int));
bool hidden = (bool)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[hidden]").ConvertTo(typeof(bool));
return new JqGridColumn
{
name = name,
source = source,
width = width,
hidden = hidden
};
}
}
Then register it in App_Start/ModelBindingConfig.cs:
binders.Add(typeof(JqGridColumn), new JqGridColumnBinder());
It's because your JqGridColumn object needs properties, not fields. see this question for reference:
ASP.net MVC - Model binding excludes class fields?
try post back with the traditional : true setting
and dataType: json
$.ajax({
url: '/MyController/MyAction',
method: 'POST',
traditional: true,
dataType: json
data: columns ,
sucess: function () { alert('Success'); }
});

Using a value from a dropdown list in a handler

I could really use some help if anyone can spare some time. I am trying to access the value of a dropdownlist (dropdownlist1) on the master page from my content page and then use the variable in a hanlder in a .ashx code page. To test it I was trying to display the varialble in a message box. Any ideas would be appreciated.
Content Page (dropdownlist is on master page)
$(document).ready(function $("#DropDownList1").change(function () {
location.reload;
alert($(this).val());
strTrail = $(this).val();
alert(strTrail);
});
Handler
Case "SearchByLocation"
Dim firstTime As Integer = 0
Dim latitude As String = "42.9901009" 'context.Request("Latitude")
Dim longitude As String = "-81.146698" 'context.Request("Longitude")
'Dim fromdate As String = context.Request("#DropDownList1").val
Dim strTrail As String = context.Request("#DropDownList1")
MsgBox("now")
MsgBox(strTrail)
'strTrail = context.Request("strTrail")
If firstTime < 1 Then
strTrail = "Lookout"
End If
Dim objCBL As New JParkinsonLookUP.JPLookUp
Dim objDS As System.Data.DataSet = objCBL.SearchByTrail(strTrail, latitude, longitude, 10)
'result = "{""Locations"":[{""ID"":""1"",""Latitude"":""28.537"",""Longitude"":""-81.380""}]}"
result = "{""Locations"":["
For Each dr As System.Data.DataRow In objDS.Tables(0).Rows
result += "{""ID"":""" & dr("ID").ToString() & """,""Latitude"":""" & dr("Latitude").ToString() & """,""Longitude"":""" & dr("Longitude").ToString() & """},"
Next
result = result.Substring(0, result.LastIndexOf(","))
result += "]}"
firstTime = 1
Case "SearchByDescription"
End Select
'second command
'third command
context.Response.Write(result)
End Sub
firt of all avoid msgbox coz it will throw in exception (not valid in an aspnet page contest)
Second one when you will go through document.ready you will have to make a ajax request as per your code you will return json object then you need to parse within javascript the object ad read value from it.
$.ajax(
{
type: "GET", url: url, data: qry,
success: function (msg) {
lat = msg.Locations[0].Latitude;
lng = msg.Locations[0].Longitude;
alert(lat +' ' + lat);
},
error: function (msg) {
$("#coor").html("errore durante l'elaborazione");
}
});
Another important stuff use this directive to set your response:
context.Response.ContentType = "application/json";
Take care to check via Chrome or Firefox your response and call via network call so you will able to have more info.
this is code is not test i use some working code at my end and make some changes to let you an idea.

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 .

Jquery ajax functions stopped working

Ive been working on some jquery within a a page.
Now all of a sudden the post functions seem to have stopped working?
function deleteRow(OrderNo, LineNo) {
alert(OrderNo + ";" + LineNo);
$.ajax({
type: "POST",
url: "Ajax.aspx/DeleteRow",
data: '{' + 'OrderNo:"' + OrderNo + '",' + 'LineNo:"' + LineNo + '"' +
'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//$("#item").val(msg);
var data = jQuery.parseJSON(msg);
if (!data.error) {
$('#' + LineNo).remove();
}
else {
alert("Error" + " " + data.error);
}
},
error: function (msg) {
alert('Failure: ' + msg);
}
});
}
This is a jquery function which gives an error back 'Failure [object Object]'
the function DeleteRow does exist in Ajax.aspx and does work. Cant understand why all of a sudden the post functions would stop working??
[WebMethod]
public static string DeleteRow(string OrderNo, string LineNo)
{
SqlConnection myConnection = new SqlConnection(connStr);
myConnection.Open();
//Check if param exisits
string SQLst = "Delete from Saved_Order_Import where [Order No] = '"+OrderNo+"' And [Line No] = '"+LineNo+"'";
try
{
SqlCommand myComman = new SqlCommand(SQLst, myConnection);
myComman.ExecuteNonQuery();
}
catch (Exception ex)
{
myConnection.Close();
return "{\"error\":\"Error Line Not Deleted" + ex.ToString() + "\"}";
}
myConnection.Close();
return "{\"Success\":\"Line Deleted\"}";
}
console log
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
isRejected: function () {
isResolved: function () {
overrideMimeType: function ( type ) {
pipe: function ( fnDone, fnFail ) {
promise: function ( obj ) {
readyState: 4
responseText:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title>
</title></head>
<body>
<form name="form1" method="post" action="Ajax.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZAZAz479BJ9BS5KpwM0PauBgztmI" />
</div>
<div>
</div>
</form>
</body>
</html>
"
setRequestHeader: function ( name, value ) {
status: 200
statusCode: function ( map ) {
statusText: "parsererror"
success: function () {
then: function ( doneCallbacks, failCallbacks ) {
__proto__: Object
You problem is on this line:
'{' + 'OrderNo:"' + OrderNo + '",' + 'LineNo:"' + LineNo + '"' +
'}',
It should be like this:
'{' + '"OrderNo":"' + OrderNo + '",' + '"LineNo":"' + LineNo + '"' +
'}',
Notice the missing opening " before OrderNo:" and before LineNo:". The fix will produce a valid JSON string:
'{"OrderNo": "OrderNo Value", "LineNo": "LineNo Value"}'
It's suprisingly uncommon the knowledge that those double quotes are required for valid JSON.
Based on the response you posted, the server output was a HTTP Status 200 with a HTML Form as the response. Was this the desired format of the response?
You're telling the AJAX function to parse the response as JSON but no JSON came back from the request. Look at your console log. The exception is a parser error.
There are lots of improvements that could be brought to your code. I will try to cover at least some of them that are bugging me when hovering over your code at first sight.
The first thing that worries me is that your page method returns a string, in which you are manually writing some JSON. That's something you should never do. You should never manually serialize/deserialize anything. In any language. Never. You can read the following article to understand why. Page methods can return strongly typed objects and the ASP.NET infrastructure will take care of properly serializing them into JSON so that you don't have to worry about it. So let's start by introducing a model that your page method could return:
public class Result
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
As you can see in this model we have a boolean variable indicating the success or failure of the page method and a string variable containing the error message in the event of failure.
The next thing, and probably, the worst with your code, is the SQL injection vulnerability present in your ADO.NET snippet. Let's fix that by introducing parametrized queries and returning the model we have just defined:
[WebMethod]
public static Result DeleteRow(string OrderNo, string LineNo)
{
try
{
using (var myConnection = new SqlConnection(connStr))
using (var myCommand = myConnection.CreateCommand())
{
myConnection.Open();
myCommand.CommandText = "DELETE FROM Saved_Order_Import WHERE [Order No] = #OrderNo AND [Line No] = #LineNo";
myCommand.Parameters.AddWithValue("#OrderNo", OrderNo);
myCommand.Parameters.AddWithValue("#LineNo", LineNo);
myCommand.ExecuteNonQuery();
}
}
catch (Exception ex)
{
return new Result
{
Success = false,
ErrorMessage = "Error Line Not Deleted" + ex.ToString()
};
}
return new Result
{
Success = true
};
}
The last step is to clean the client side code. Here you I would recommend you to use the JSON.stringify method to properly JSON serialize the javascript literal instead of using some string concatenations to manually build your JSON (read the article I have linked previously in my answer to understand why you should never manually serialize/deserialize anything => you should always use a proper qserializer for the given format).
$.ajax({
type: 'POST',
url: 'Ajax.aspx/DeleteRow',
data: JSON.stringify({ OrderNo: OrderNo, LineNo: LineNo }),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
// Notice how we use msg.d here. The ASP.NET Page Methods
// infrastructure will JSON serialize the response using this property:
// {"d":{"Success":"true"}}
var data = msg.d;
if (data.Success) {
$('#' + LineNo).remove();
}
else {
alert('Error ' + data.ErrorMessage);
}
},
error: function (msg) {
alert('Failure: ' + msg);
}
});
Also make sure that you have enabled page methods in the script manager of your page:
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
Remark: the JSON.stringify method is natively built-in modern browsers but if you need to support legacy browsers you could include the json2.js script to your page.
PHP devs (like me) who deal with jQuery, Ajax and other frontend technologies: "Suddenly not working" could mean that you added some debugging, some "echos" (PHP wrong way of debugging) and you forgot to check the entire stack in order of removing it. That debugging code you let there will cost long painful days of reviews and tests. Have you ever considered that? Follow these steps:
0 - (Please: Developers start counting from zero) - Directly call backend using URL only, whenever possible, instead of using ajax. You can grab a testing tool like these ones QA guys use - and we should get used on them too - there are many. Grow up. Go find one. Talk to QA guys. Do something. Now! :-)! Look at what you received: is it a valid JSON? Is it a valid XML? Is it a valid JSON/XML plus something that should not be there? Is it a valid JSON/XML but not the one you expected to receive? Probably this step is enough.
1 - Get used to the following useful ajax snippet (http://craigsworks.com/projects/forums/showthread.php?tid=3829) :
$.ajax({
url: 'http://localhost/formengine/index.php?r=site/ajax',
success: function(response) {
console.log(response);
}
});
2 - Test any other jQuery behavior instead of the one you are building. This step is just to make you feel better and recover that everyday rationality that pays your salary. jQuery, Ajax, PHP, .net stack, Java stack: they are friendly, nice and do want to be working for you. Sometimes it's just matter of handling head stuff: either an offline CDN, a URL that is wrong, source location may be wrong, these ordinary, everyday stuff. Place the CDN URL to the navigation bar: you shall be able to read the entire lib in your browser screen. Click on this: https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
3 - In the deepest moment of your desperation, have you placed any alert somewhere where it's not legal? Do not say "no"! Go testing it: google chrome, F12, a developers perspective frame opens and at the top right you can see the smallest red flag ever - yes: the smallest. Hear the voices in your head: click on it. A meaningful message will appear. If it's the case, fix the issue.
4 - Drive all the necessary efforts towards having a well defined deploying process. Copying and pasting are not professional approaches - and, believe me, you are the most interested ones on doing things right. There are many "best practices" references regarding deploying, considering, of course, the technology stack you guys use: follow them.
Good Luck to you all! Hope it helps!

Categories

Resources