Ajax POST never gets triggered, neither success nor error - javascript

What I am trying to do by using AJAX is when I click "Select" Button, all the related information coming from SQL DB will be assigned to the related labels.
The problem is that the AJAX code below($.ajax) never gets triggered (neither success nor error). alert(res[0]) is showing the true result on screen (so the clientid parameter is true).
This is from a WebApplication Project in Asp.Net
function BindClientSummaryForm() {
var skillsSelect = document.getElementById('<%= ddlSFoundClients.ClientID %>');
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
var res = selectedText.split('-');
document.getElementById('<%= hiddenClientID.ClientID %>').value = res[0];
alert(res[0]);
$.ajax({
type: "POST",
url: "Default.aspx/GetClientSummaryData",
contentType: "application/json;charset=utf-8",
data: "{ 'clientid': " + res[0] + "}",
dataType: "json",
success: function (data) {
alert("deneme");
document.getElementById('<%= lblClientNameSurnameD.ClientID %>').innerHTML = data.d.Firstname + " " + data.d.Lastname;
document.getElementById('<%= lblDateOpenedD.ClientID %>').innerHTML = data.d.DateFileOpened;
document.getElementById('<%= lblCityD.ClientID %>').innerHTML = data.d.City;
...
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error occured while filling ClientSummary part.");
}
});
return false;
}
<asp:Button runat="server" CssClass="btnSelect fieldButton" ID="btnSSelect" Text="Select" OnClientClick="return BindClientSummaryForm()"></asp:Button>
CodeBehind
[WebMethod]
public static MyClient GetClientSummaryData(String clientid) //GetData function
{
...
return client;
}
the debugger never drops to the GetClientSummaryData(clientid) method in c# as well.
I appreciate for your helps.

Try to change the value of content-type to text/plain on both, the client and the server, and use eval ('('+data+')') in the success function.
I know that this is not correct because the server response is json, but happened to me the same thing and I discovered (i don't know the reason) when you return the content as content-type: application/json on the server, jQuery does not call the success function.

What for do you specify POST as a request type? It seems like it will be more natural if you use GET (even method name tells us about that).
Also I'm not sure about this syntax data: "{ 'clientid': " + res[0] + "}" because I prefer to write scripts in separate files. Anyway, you can try to write data: { clientid: res[0] } instead

Related

AJAX indicates that WEBMETHOD was successful, but it never actually triggers the webmethod on code behind

I've been through countless posts and cant figure out what I am doing wrong. I have a asp.net website with C# code behind. In it, I need for a javascript function on the .aspx page to trigger a method on the aspx.cs page. I wrote the following code:
.aspx page (my ScriptManager):
</head>
<body id="bodycontainer">
<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePartialRendering="false" EnablePageMethods="true"/>
The Javascript function using ajax on the .aspx page:
function ValidateForm() {
$.ajax({
type: "POST",
url: "default.aspx/Save",
data: {},
contentType: "application/json; charset=utf=8",
// dataType: "json", // NOT NEEDED IF NO RETURN VALUE
async: true, // OPTIONAL
success: function (msg) {
alert("success");
},
error: function (msg) {
alert("failed");
}
});
}
The aspx.cs page (Code Behind page):
[WebMethod]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default();
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
public void btnSave_Click()
{
// METHODS CODE HERE
}
The ValidateForm function responds with "success", however, it doesn't seem like it is even triggering the WebMethod on the Code Behind page. If I use the I.E. Console Network tab, I can see the POST request. However, on the code behind method, it never triggers the breakpoints in debug (Not sure if it should according to some posts). At one point I inserted line to throw a DivideByZero exception and it never raised the exception.
So, to summarize, I get confirmation that he Javascript call to the WEBMETHOD worked by virtue of the success message and the POST message in the F12 Console Network tab. However, it doesn't seem that the WEBMETHOD ever fires. Any help would be appreciated !
You could try this to test an error instead of throwing an exception
Response.Clear();
Response.StatusCode = 500;
Response.End;
Not sure what I did, but I think adding "UseHttpGet = false" allowed it to finally execute the webmethod.
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static void Save()
{
// throw new DivideByZeroException(); // USED THIS TO VERIFY IF WEBMETHOD IS HIT.
_default obj = new _default(); // SINCE THIS METHOD IS STATIC, WE HAVE TO INSTANTIATE AND INSTANCE OF THE DEFAULT PAGE CLASS TO ACCESS METHODS ON THIS PAGE
obj.Show("Save Method Works"); // THIS IS A POPUP MESSAGE BOX
obj.btnSave_Click(); // THIS IS THE SAVE METHOD ON THIS PAGE THAT WE WANT TO RUN
}
function ValidateForm() {
var text = "This is a Test";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf=8",
data: "{}",
url: "default.aspx/Save",
dataType: "json",
success: function (msg) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("status: " + textStatus);
alert("Error: " + XMLHttpRequest.responseText);
}
});
}

populate drop down list with json

I am trying some stuff and populating drop down list with a json and javascript for some reason I am getting a console error when trying to populate
I am using Scripts/jquery-2.0.2.js
this is the error:
Failed to load resource: the server responded with a status of 404 (Not Found)
POST //localhost:9819/Home/Home/Test 404 (Not Found)
jquery-2.0.2.js:7858 send jquery-2.0.2.js:7858 jQuery.extend.ajax
jquery-2.0.2.js:7314 RetrieveData Index:45 (anonymous function)
Index:64 jQuery.event.dispatch jquery-2.0.2.js:4692 elemData.handle
This is the View Code:
<script>
$(document).ready(function () {
var Load = false;
function RetrieveData() {
if (Load == false) {
Load = true;
$.ajax({
url: <%= Url.Action("Test", "Home") %>
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
$("#selectMe").html(data);
Load = false;
},
error: function (data, status, jqXHR) {
alert("Error: " + data);
Load = false;
}
});
}
}
$(document).on("click", "#test", function () {
RetrieveData();
});
});
</script>
<input type="submit" id="test" />
<select id="selectMe"></select>
Controller:
public string GenerateHTMLforDropDownList(Dictionary<string, string> myData)
{
string HTMLString = "";
foreach (KeyValuePair<string, string> k in myData)
{
HTMLString += "<option value=\"" + k.Key + "\">" + k.Value + "</option>";
}
return HTMLString;
}
[HttpPost]
public JsonResult Test()
{
Dictionary<string, string> myData = new Dictionary<string, string>();
myData.Add("0", "Mike");
myData.Add("1", "Mark");
myData.Add("2", "Karl");
myData.Add("3", "Rhona");
return Json(GenerateHTMLforDropDownList(myData), JsonRequestBehavior.AllowGet);
}
any help of how I can fix this thanks
As the error states, the resource is not found. Look at the URL in the error:
http://localhost:9819/Home/Home/Test
Assuming you're not doing anything more custom, if you have a Test action on a Home controller then the URL should be:
http://localhost:9819/Home/Test
Notice also how you're specifying the URL in your code:
url: "Home/Test"
If you're currently at http://localhost:9819/Home/Anything then that relative URL says to look for a resource called Test in a "subdirectory" (using the word loosely) of the current resource. So there's your problem.
Instead of specifying the URL manually like that, use the Url.Action method in MVC. Something like this:
url: '#Url.Action("Test", "Home")'
This will generate a fully-qualified URL from server-side code regardless of where your current context is, so you don't have to adjust it based on the current URL or anything like that.
I have not done this in MVC but I've done this countless times in Web Forms and it looks like your URL might be the problem...
//localhost:9819/Home/Home/Test
In your ajax call you should probably adjust this line...
url: "Home/Test"
and make it look something like ...
url: <%= Page.ResolveUrl("~/Home/Test.asmx") %>
Sorry if this is way off base for MVC.
You need to change your button type to 'button' not submit as this is ajax call

Making Ajax call from javascript

I have the following jquery ajax call and it works fine in a purely jquery file.
var request = $.ajax({
url: "kscript.jsp",
type: "POST",
data: {st:start, sp:stop},
dataType: "html"
});
request.done(function(msg) {
$("#output").html( msg );
alert("Success!!!"+msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Thereafter I rewrote my code as a javascript, but I am now putting the ajax call directly inside a javascript function. This hasn't worked and I am getting 500 Internal Server Error.
function myAjax(){
var request = $.ajax({
url: "kscript.jsp",
type: "POST",
data: {st:start, sp:stop},
dataType: "html"
});
request.done(function(msg) {
$("#output").html( msg );
alert("Success!!!"+msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
I have also tried this:
function ajaxFunction() {
xmlhttp.open("POST","kscript.jsp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("st=start&sp=stop");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("output").innerHTML=xmlhttp.responseText;
}
}
}
but the same error: 500 Internal Server Error. In all these instances, the error is pointing to kscript.jsp .I have ensured that the URL and spelling is correct but hasn't worked. I would appreciate your suggestion to fix this problem.
here is kscript.jsp
<%
String astart = request.getParameter("start");
String sptimes=request.getParameter("stop");
out.print("<h1> Start is: "+start+" -- Stop is"+stop +"</h1>");
%>
it's looks like a folders structure problem, you shoudl ensure that the relative path is fine, I mean, if you are calling from a js you should point to /jsp/yourJsp.jsp , checkit... by the way, are you using the F12 tools to validate the response from the server ?
i think you are making some mistake to call java script method.so check or have you describe ajaxcall inside javascript tag.
You are trying to access the wrong parameters in jsp.
The error occurs here:
String astart = request.getParameter("start");
the parameters are st and sp, not start and stop.
you need:
String astart = request.getParameter("st");
String sptimes=request.getParameter("sp");
Or, you can change the js to pass the correct parameters:
data: {start:start, stop:stop},

ASP.Net call codebehind on $.ajax success

I have a page (default.aspx) with codebehind. The a$.ajax url is getting a response from one place, and on its success I want to call the codebehind function.
(In case I made a mistake while obfuscating the code, the $.ajax works perfectly and I get the desired response).
How is this possible?
Code I'm using:
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
$.ajax({
type: "POST",
url: URL,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var resultCount = response.d
alert("*** RESULT ****" + resultFields);;
var string = StringReturn(); // the codebehind
alert(string);
},
error: function (e) {
alert("Unavailable");
}
});
Codebehind:
[WebMethod]
protected static string StringReturn()
{
return "StringReturn() success";
}
However, I'm getting error messages saying that StringReturn isn't a valid function.
Any help would be appreciated?
I've added the following lines of code to the page as advised:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
I've also changed the code to call a javascript function on the Success event, the function being:
function HelloWorlds() {
alert("HelloWorld() method");
message = PageMethods.StringReturn();
message.toString();
alert(message);
}
however that doesn't appear to work. What am I missing?
You need to have a scripmanager on your page and then you can call it like this PageMethods.StringReturn()

getJSON is not calling the controller action

I don't know why this is happening since there are other functions in this page that use also getJSON and they do work. I have the following JavaScript Code
function openSOPNotesDialog() {
var url = '<%: Url.Action("GetSOPNote", "SalesOrder") %>';
var id = <%: Model.SodID %>;
$.getJSON(url, { sodId : id }, function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
});
}
and then I have this method on the SalesOrderController class
public JsonResult GetSOPNote(int sodId)
{
var service = new SodSrv();
var note = service.GetSOPNotes(sodId);
return Json(note, JsonRequestBehavior.AllowGet);
}
However, the method is never called in the debugger and data is returned as null (which is what I'd expect). As I said before there are other calls in this page and they are also doing GET requests so I don't know what may be the cause.
Sounds like the browser is pulling the data from the cache since it is a get request. Make sure to set no cache headers on the server if it is not meant to be cached.
Try adding an error handler to try to track down what the issue is:
$.ajax({
dataType: 'json',
url: url,
data: { sodId : id },
success: function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("oops: " + textStatus + ": " + jqXHR.responseText);
}
});
I suspect that the reason is that getJSON uses get method and controllers normally allowed to accept only post methods. It's ease to check using any browser firebug for example.

Categories

Resources