Ajax Post 500 Internal Server Error with asp.net - c#

I have a problem with ajax
This is the code:
$(document).ready(function () {
show_page(1);
});
function show_page(page) {
debugger;
$.ajax({
type: 'post',
url: 'OrdiniServer.aspx',
data: {
page: page
},
success: function (response) {
$("#table_ordini").html(response);
}
});
return false;
}
This function is included inside RistoratoreAccount.aspx which itself, is located inside a masterpage.
So when I start this function, it should call the page "OrdiniServer.aspx", but the browser console gives me this error:
jquery-1.3.2.min.js:8 POST http://localhost:10343/OrdiniServer.aspx 500 (Internal Server Error)
send # jquery-1.3.2.min.js:8
ajax # jquery-1.3.2.min.js:8
show_page # RistoratoreAccount.aspx:440
(anonymous function) # RistoratoreAccount.aspx:433
j # jquery-1.3.2.min.js:3
fireWith # jquery-1.3.2.min.js:3
ready # jquery-1.3.2.min.js:3
J # jquery-1.3.2.min.js:3
I tried to set the OrdiniServer.aspx with ContentPlaceHolder and without it but it still doesn't work.
I tried to use breakpoint on the codebehind but it doesn't start, so the error is not in the code...
So this is the OrdiniServer.aspx page:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterBack.Master" CodeBehind="OrdiniServer.aspx.cs" Inherits="FoodDelivery.OrdiniServer" %>
<asp:Content ID="cp2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
</asp:Content>
p.s. I tried this code with another project that doesn't have masterpage and it works...

use get method instead of post try below code
$(document).ready(function () {
show_page(1);
});
function show_page(page) {
debugger;
$.get("/OrdiniServer.aspx", { page: page }, function (data) {
$("#table_ordini").html(data.toString());
})
}
try this .

Related

call Ajax JQuery on asp:Button OnClientClick and disable page reload if pointer goes to IF condition of Ajax JQuery

I have a asp:Button (named as "Save") in a Web Page. It has separate code for
CommandName and CommandArgument defined in a class(.cs) file, to save records.
It also has a OnClientClick event code.
HTML:
<asp:Button ID="btnSave" runat="server" Text="Save" CommandName="Update"
OnClientClick="saveButtonClick();" CommandArgument="Save" />
Now, When I try to use OnClick event of this button, the OnClick code does
not work. I think its due to CommandName and CommandArgument or OnClientClick
code, already defined on this button but im not sure why its not working.
Since, the onClick event is not working, so I thought to write the logic of
onClick through Ajax JQuery and then I want to call this Ajax JQuery
inside pre-defined function of Javascript called onClientClick of this button.
i.e., inside saveButtonClick(); function of Javascript code
JavaScript:
<script tyep="text/javscript">
function saveButtonClick() {
//code
}
</script>
Current Ajax JQuery Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
function saveButtonClick() {
var chk = {};
chk.requestID = $("[id*=TempGUID]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBarcodeNumber]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "IPRForm_EditCheck.aspx/CheckDuplicate",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var val = data.d;
alert(val);
if (val == true) {
alert("Barcode Number already exist in system database.");
}
else {
alert("Barcode Number does not exist");
}
},
error: function (data) {
alert(data.responseText);
},
});
return false;
}
</script>
Requirement is When I click on asp:Button, it triggers the onClientClick event and go to saveButtonClick() function of Javscript, inside this function it calls the Ajax JQuery. Now, in Ajax JQuery, if pointer goes to IF condition then an alert should come and page should not reload, but if it does not goto IF condition, page should reload (as previous default behavior).
I hope I made my requirement clear to you all.
Please note that I am new in asp.net and Ajax JQuery.
Thanks in advance
function saveButtonClick() {
var chk = {};
chk.requestID = $("[id*=TempGUID]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBarcodeNumber]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "IPRForm_EditCheck.aspx/CheckDuplicate",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async:false,//here I am not allowing event to go further until it checks the barcode existance
success: function (data) {
var val = data.d;
alert(val);
if (val == true) {
alert("Barcode Number already exist in system database.");
return false;
}
else {
return true;
}
},
error: function (data) {
alert(data.responseText);
},
});
}
and update as following:
<asp:Button ID="yourid" UseSubmitBehavior="false"
OnClientClick="return saveButtonClick()"
runat="server" />
Explanation: See, you don't want to trigger the server side code unless bar-code not exists in the database. I have used method Preventing default behavior of button to prevent triggering server-side code. if bar-code doesn't exists than it will trigger the default behavior of the button.
Let me know if it doesn't works.
change your button code like this
<asp:Button ID="yourid" UseSubmitBehavior="false"
OnClientClick="return saveButtonClick()"
runat="server" />
JS code:
function saveButtonClick()
{
if(condition fails)
return false
else
return true
}
EDIT:3
updated JS code,At last I found that async calls cannot return a value, beacuse your code will not stop execution whether you have response from your service or not..please use this solution ,only if you like it..please keep in mind that this is a SYNCHRONOUS call ....
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
function saveButtonClick() {
var result = true;
var output = $.ajax({
type: 'POST',
url: "Default.aspx/SaveUser",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false
}).responseText;
var obj = jQuery.parseJSON(output);
if(obj.d) {
alert("Barcode Number already exist in system database.");
result = false;
}
else {
alert("entering database");
}
alert(result);
return result;
}
</script>

Using Response.Redirect in the View mvc4

I am going following steps:
in the controller action no.1 redirect to view no1;
in view no.1 I want to display cshtml page and next I want to redirect to the new action no.2 by using
#{Response.Redirect(Url.Action("CreatePdf", "Home");}
directive;
Action no.2 is reached and I've got my result (pdf file) but I can;t see the view no.1 from which I've called this action.
How can I load this view and display html page?
Just a little tweak to #DavidG's answer:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
location.href = "#Url.Action("CreatePdf", "Home")";
}
</script>
Just tested and working. It will download the file after 1sec
A redirect causes the entire session to be directed to the new page ans loses anything you have sent out. I would use jQuery instead:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(DownloadPdf, 1000);
});
function DownloadPdf() {
window.location = "#Url.Action("CreatePdf", "Home")";
}
</script>
I would suggest :
public ActionResult ControllerAction1()
{
return View();
}
For the View(), for document.ready function :
$(document).ready(function () {
$.ajax({
url: '#Url.Action("Action2", "Controller")',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'html',
data: JSON.stringify(model)
})
.success(function(result) {
// return true or false
// html of json result
})
.error(function(xhr, status) {
});
});

Can't Use PageMethod (ajax in C# .net)

I try to use PageMethod in asp.net.
First I add script Manager to my aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
I wrote onClick method on JS:
function TryAJAX() {
PageMethods.TryA( onSucess, onError);
function onSucess(result) {
alert('good.');
}
function onError(result) {
alert('Something wrong.');
}
}
and in the code behind:
[WebMethod]
public static String TryA()
{
return "JSON CHECK";
}
and I always get the message 'something wrong' . althouth that in debugger I see it's enter to the methood 'TryA'.
What is the problem?
thanks!!
i know this is not the exact path you were looking to take for a solution, but I think it is a WAY better option, so here's my 2 cents...
your button in html
<input type="button" id="myStupidButton" value="Click Me Yo" />
you javascript- I am going to use jQuery too , if that is really a problem I can give you a pure js option:
<script>
$(function(){
$(document).on('click', '#myStupidButton', function(){
$.ajax({
type: "POST",
url: "Mypage.aspx/TryA",
success: function(data){
// parse asp.net's response
data = $.parseJson(data);
//asp.net wraps all json into json like this "d" : "yourresponse"
alert(data.d);
}
});
});

how to use document.ready function on child pages

i need to use JavaScript on my website. When i create new web page,which is properly work with JavaScript. When i create a new web page, which is child page, derived from master page. this page does not support my JavaScript. I use this code for auto-complete property for multiple words.
My code is here:
JavaScript code in content place holder in header
<%# Page Language="C#" MasterPageFile="~/Master_Front.master" AutoEventWireup="true"
CodeFile="Mailbox.aspx.cs" Inherits="Mailbox" Title="Mail System" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<link href="Style/ui-lightness/jquery-ui-1.8.21.custom.css"rel="stylesheet" type="text/css" />
<script src="script/jquery.min.js" type="text/javascript"></script>
<script src="script/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtto").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Mailbox.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
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);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txtto").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
</asp:Content>
C# code:
[WebMethod]
public static List<string> GetAutoCompleteData(string user_name)
{
List<string> result = new List<string>();
SqlDataReader dr=General.ReturnDR("select DISTINCT mailid from UserDetails where mailid LIKE '%"+user_name+"%'");
while (dr.Read())
{
result.Add(dr["mailid"].ToString());
}
return result;
}
You can put all script in document.ready so that the elements are ready when script acces them.
$(document).ready(function(){
//put all your script of child page here.
});

Problem with jQuery selector and MasterPage

I have a problem with a master page containing a asp:textbox that I'm trying to access using jQuery. I have read lot sof thread regarding this and tried all the different approaches I have seen, but regardless, the end result end up as Undefined.
This is the relevant part of the MasterPage code:
<p><asp:Label ID="Label1" AssociatedControlID="osxinputfrom" runat="server">Navn</asp:Label><asp:TextBox CssClass="osxinputform" ID="osxinputfrom" runat="server"></asp:TextBox></p>
When I click the button, the following code from a jQuery .js file is run:
show: function(d) {
$('#osx-modal-content .osxsubmitbutton').click(function (e) {
e.preventDefault();
if (OSX.validate()){
$('#osx-modal-data').fadeOut(200);
d.container.animate(
{height:80},
500,
function () {
$('#osx-modal-data').html("<h2>Sender...</h2>").fadeIn(250, function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'from':'" + $("#osxinputfrom").val() + "','mailaddress':'" + $("#osxinputmail").val() + "','header':'Test3','message':'Test4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Meldingen er sendt!</h2>');
$('#osx-modal-data').fadeIn(200);
});
},
error: function(msg){
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Feil oppstod ved sending av melding!</h2>');
$('#osx-modal-data').fadeIn(200);
});
}
});
});
}
);
}
else{
$('#osxinputstatus').fadeOut(250, function () {
$('#osxinputstatus').html('<p id="osxinputstatus">' + OSX.message + '</a>');
$('#osxinputstatus').fadeIn(250);
});
}
});
},
So the problem here is that $("#osxinputfrom").val() evaluated to Undefined. I understand that the masterpage will add some prefix to the ID, so I tried using the ID from the page when it's run that ends up as ct100_osxinputfrom, and I also tried some other hinds that I found while searching like $("#<%=osxinputfrom.ClientID%>"), but it ends up as Undefined in the method that is called from the jQuery ajax method anyway. The third and fourth parameters to the ajay function that is hardcoded as Test3 and Test4 comes fine in the C# backend method.
So my question is simply: How can I rewrite the jQuery selector to fetch the correct value from the textbox? (before I used master pages it worked fine by the way)
Best regards
Daemon
It will be abit slower but why dont you try adding cssclass="bla" to your label and then get it with $('.bla').val(); ?
You should use the attribute ends with selector
Link
it would be $("id$='osxinputfrom'")

Categories

Resources