JQuery ajax method giving syntax error - c#

<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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" runat="server">
<title>Login Page</title>
<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="wholeContent">
<div id="login">
<table border="2">
<tr>
<td>
User Id
</td>
<td>
<input type="text" id="txtId" name="txtId" />
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="text" id="txtPwd" name="idPwd" />
</td>
</tr>
<tr>
<td>
<input type="button" id="btnSubmit" value="Login" />
</td>
</tr>
</table>
</div>
<div id="success">
</div>
<div id="error">
</div>
</div>
<script type="text/javascript">
$(document).ready(function()
{
$("#btnSubmit").click(function()
{
var uid = $("#txtId").val();
var pwd = $("#txtPwd").val();
var data=JSON.stringify({uid:uid,pwd:pwd});
$.ajax({
type: "POST",
url: "Default.aspx/ValidationWebMethod",
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
// data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
success: function (data)
{
alert(" Successful Login "+data.d);
// location.reload();
},
error: function(resp,textStatus,errorThrown)
{
alert("error : " + errorThrown + " || Check your Id and Password || "+ resp.d);
}
});
});
});
</script>
</form>
</body>
</html>
This is my code-behind (part of the code)
[System.Web.Services.WebMethod]
public static void ValidationWebMethod(string uid, string pwd)
{
string text = uid + " : " + pwd;
System.IO.File.WriteAllText(#"D:\TrackLog.txt", text);
string[] flags = new string[1];
// bool valid = true;
if (uid.Equals("arijit") && pwd.Equals("admin"))
{
flags[0] = "true";
// return flags;
}
else
{
flags[0]="false";
// return flags;
}
}
Now when I am clicking the button (btnSubmit) its giving syntax error:Invalid Character (the errorThrown variable here in the alert box)..Please can you tell me why is it happening?

The problem is here
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
As you changed the data in json format with JSON.stringify
var strdata=JSON.stringify({uid:uid,pwd:pwd});
So you no need to pass data to ajax method like you do above.
Try this
data: strdata // renamed variable
instead of
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",

Your ValidationWebMethod does not return anything. Make it return, for example, string.

Related

C# JSON AJAX returning page HTML instead of method value

NOTE: I did search the forums but didn't find anything that matched my issue or worked.
Hi all,
I'm trying to make a simple call from an asp.net web form using json & ajax to a method in the code-behind page but it's returning that page html instead of the value from the method.
Here is the method in the code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
namespace Tags
{
public partial class AJAX3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string CalculateSum(Int32 Num1, Int32 Num2)
{
Int32 Result = Num1 + Num2;
return Result.ToString();
}
}
}
Here is my web form:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="AJAX3.aspx.cs" Inherits="Tags.AJAX3" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call asp.net server side page methods using jQuery AJAX & json</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCalculate").click(function () {
//Get values from textboxes that will be passed to function
var num1 = $('#txtFirstNumber').val();
var num2 = $('#txtSecondNumber').val();
$.ajax({
type: "POST",
dataType: "text",
contentType: "application/json; charset=utf-8",
//Url is the path of our web method (Page name/function name)
url: "AJAX3/CalculateSum",
//Pass values to parameters. If function have no parameters, then we need to use data: "{ }",
data: "{'Num1':'" + num1 + "', 'Num2':'" + num2 + "'}",
//called on ajax call success
success: function (result) {
$('#dvMsg').text("Sum of " + num1 + " and " + num2 + " = " + result);
},
//called on ajax call failure
error: function (xhr, textStatus, error) {
$('#dvMsg').text("Error:" + error + ", xhr: " + xhr + ", textStatus: " + textStatus);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Enter First Number:</td>
<td>
<asp:TextBox ID="txtFirstNumber" runat="server" Text="22" /></td>
</tr>
<tr>
<td>Enter Second Number:</td>
<td>
<asp:TextBox ID="txtSecondNumber" runat="server" Text="33" /></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnCalculate" Text="Calculate" runat="server" OnClientClick="return false;" />
<div id="dvMsg"></div>
</td>
</tr>
</table>
</div>
</form>
</body>
My goal is to return a string and not a JSON object.
What am I doing wrong?
Thanks!

Adding an entry to the table and page using ajax

I study javascript. Got to ajax requests. Everything works fine in mvc. I decided to try on web forms. Trying to post a new entry on the page, please tell me what I'm doing wrong. Here is my code. The page code acts as the main view:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Tables.aspx.cs" Inherits="WebApplication1.Tables" %>
<!DOCTYPE html>
<script src="../../Scripts/jquery-1.8.0.min.js"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<div>
<table id="tab" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Author</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1408</td>
<td>Stiven King</td>
<td>500</td>
</tr>
</tbody>
</table>
</div>
<form id="form1" runat="server">
<asp:TextBox ID="txbName" runat="server"></asp:TextBox>
<asp:TextBox ID="txbAuthor" runat="server"></asp:TextBox>
<asp:TextBox ID="txbPrice" runat="server"></asp:TextBox>
<input id="btnAdd" type="submit" value="Добавить" />
</form>
</body>
</html>
<script>
$('#btnAdd').on('click', function () {
$.ajax({
type: "POST",
url: "Tables.aspx/AddBook",
data: JSON.stringify({
"Name": $('#txbName').val(),
"Author": $('#txbAuthor').val(),
"Price": $('#txbPrice').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (MyDT) {
$('#tab tbody').append(MyDT);
},
error: function (xhr) {
alert(xhr.statusCode)
}
});
});
</script>
Web method code, controller:
[WebMethod]
public static string AddBook(string Name, string Author, int Price)
{
db = new Context();
string html = "";
Book book = new Book() { Name = Name, Author = Author, Price = Price };
db.Books.Add(book);
db.SaveChanges();
html = GetHTMLRow(book);
return html;
}
And another method of obtaining html code for further adding an entry to the page, something like a partial view on which the entry is going to:
public static string GetHTMLRow(Book book)
{
string htmlRow = $"<tr><td>{book.Name}</td><td>{book.Author}</td><td>{book.Price}</td></tr>";
return htmlRow;
}
My code is completely working, but for some reason the page is restarted. But shouldn't ajax request work asynchronously without touching the page? In MVC everything works fine. And then why not? What can be wrong?
when you click the button it submits the form(because the type is set to "submit"). change it to "button"
<input id="btnAdd" type="button" value="Добавить" />

Load Additional Data While scrolling down a page using jQuery Ajax and ASP.NET

I am trying to apply the captioned feature in my project and decided to try it out to see how it works. But while testing it, it shows an Client script error with a message Undefined when I scroll to the bottom of the page. I do not know what I did wrong in my code and I don't know how to get it to work. I am hoping someone helps me out of this. Below is the code:
Repeater
<div id="dvCampaigns">
<asp:Repeater ID="rptUsers" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
border: dashed 2px #04AFEF; background-color: #B0E2F5">
<tr>
<td>
<b><u><span class="campaignname">
<%# Eval("CampaignName") %></span></u></b>
</td>
</tr>
<tr>
<td>
<b>Description: </b><span class="description">
<%# Eval("Description") %></span><br />
<b>ID: </b><span class="campaign-id">
<%# Eval("CampaignID") %></span><br />
<b>Date Created: </b><span class="datecreated">
<%# Eval("CreatedOn")%></span><br />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
<div>
<img id="loader" alt="" src="../Images/loading.gif" style="display: none" />
</div>
Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
rptCampaigns.DataSource = GetUserData(1);
rptCampaigns.DataBind();
}
}
public static TList<POLLice.Entities.Campaigns> GetCampaignData(int pageIndex)
{
int totalData;
var items = new CampaignsService().GetAll(pageIndex, 10, out totalData);
return items;
}
[WebMethod]
public static string GetCampaigns(int pageIndex)
{
var dataset = GetUserData(pageIndex).ToDataSet(true);
return dataset.GetXml();
}
jQuery Script
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "UserProfile/Default.aspx/GetCampaigns",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
},
error: function(response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var campaigns = xml.find("Campaigns");
campaigns.each(function() {
var campaign = $(this);
var table = $("#dvCampaigns table").eq(0).clone(true);
$(".campaignname", table).html(campaign.find("CampaignName").text());
$(".description", table).html(campaign.find("Description").text());
$(".campaign-id", table).html(campaign.find("CampaignID").text());
$(".datecreated", table).html(campaign.find("CreatedOn").text());
$("#dvCampaigns").append(table).append("<br />");
});
$("#loader").hide();
}
</script>
Many Thanks.
In your ajax you have this line:
url: "UserProfile/Default.aspx/GetCampaigns",
Did you remove the full path including http for this post or is that the way it is in your code? That needs a relative or absolute path to the web method. Also when calling web methods with ajax you need to use:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] //or whatever your return format is
[WebMethod]

where's the code from 'build' folder on asp.net c# (mvc)

I have to fix a bug on a website that is using asp.net and i don't know much about it (asp.net c# mvc)...
the problem is in a plugin named uploadify, and it calls for the script to upload files:
'script': '<%= ResolveUrl("~/Build/UploadImages")%>/<%= ViewData["build_id"] %>',
in the browser show like this:
'script': '/prod/cms/Build/UploadImages/680ad442-8e9c-459c-b253-e9c389c1622b',
the problem is that the folder 'Build' doens't exist, i think it's created by asp.net....
I can't find the code that uploads the file... I searched everywhere with the words 'SaveAs', 'SaveFileAs', 'Upload', 'Uploadify' in all files, and i still haven't found it yet...
the problem that uploadify gives is 'HTTP Error' after it show 100% of upload, I searched on google but no luck... i think if i found the script that uploads the file, maybe i can fix it
here's the all script of my file:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Framework.Models.Image>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Photo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Photo</h2>
<p>
<label>
Tipo:</label>
<%= Html.DropDownList("type", (SelectList)ViewData["types"], new { onchange = "changeScript(this.value)" })%>
</p>
<div id="dvUpload">
<input id="upload" name="upload" type="file" />
Fazer Upload | Limpar Uploads
</div>
<%-- <% using (Html.BeginForm("UploadImages", "build", new { id = ViewData["build_id"], type = "c1956908-64f5-4195-ba73-4d7710d560d7" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input id="File1" name="upload" type="file" />
<input type="submit" value="Enviar" />
<%} %>--%>
<br />
<br />
<table>
<tr>
<th>
</th>
<th>
Type
</th>
<th>
Imagem
</th>
<th>
Legenda
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%= Html.ActionLink("Apagar", "deleteimage", new { id = item.Properties.id, build_id = item.Properties.build_id }, new { onclick = "return confirm('Confirma esta ação?')" })%>
</td>
<td>
<%= Html.Encode(item.Type)%>
</td>
<td>
<img src="<%= Cms.Helpers.Settings.CMS_ADDRESS + item.Properties.url_address %>" width="150" height="100" />
</td>
<td>
<%= Html.TextBox(item.Properties.id.ToString(), item.Properties.description) %>
<input type="button" value="Ok" onclick="saveLegend('<%= item.Properties.id.ToString() %>')" />
</td>
</tr>
<% } %>
</table>
<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeaderContent" runat="server">
<script type="text/javascript" src="<%= ResolveUrl("~/Content/JS/swfobject.js") %>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Content/JS/jQuery/jquery.uploadify.v2.1.0.js") %>"></script>
<script type="text/javascript">
var html = "";
jQuery(document).ready(function() {
html = jQuery("#dvUpload").html();
jQuery("#upload").uploadify({
'uploader': '<%= ResolveUrl("~/Content/Flash/uploadfy.swf") %>',
'script': '<%= ResolveUrl("~/Build/UploadImages")%>/<%= ViewData["build_id"] %>',
'cancelImg': '<%= ResolveUrl("~/Content/Images/cancel.png") %>',
'folder': '<%= ResolveUrl("~/Content/Images") %>',
'multi': true,
'simUploadLimit': 10,
'fileDesc': 'Apenas Imagens são permitidas',
'fileExt': '*.gif;*.jpg;*.png',
'onError' : function(errorType) {
//alert('The error was ' + errorType.toSource());
alert(JSON.stringify(errorType, null, 4));
},
'onComplete': function() {
alert("foi tudo");
}
});
AddNullValueSelectObject('type');
});
function Upload(build_id) {
jQuery('#upload').uploadifyUpload();
}
function changeScript(val)
{
jQuery("#dvUpload").empty();
jQuery("#dvUpload").html(html);
var culture = jQuery('#culture').val();
jQuery("#upload").uploadify({
'uploader': '<%= ResolveUrl("~/Content/Flash/uploadfy.swf") %>',
'script': '<%= ResolveUrl("~/Build/UploadImages")%>/<%= ViewData["build_id"] %>?type=' + val,
'cancelImg': '<%= ResolveUrl("~/Content/Images/cancel.png") %>',
'folder': '<%= ResolveUrl("~/Content/Images") %>',
'multi': true,
'simUploadLimit': 10,
'fileDesc': 'Apenas Imagens são permitidas',
'fileExt': '*.gif;*.jpg;*.png',
'onError' : function(errorType) {
//alert('The error was: ' + errorType.toSource());
alert(JSON.stringify(errorType, null, 4));
},
'onComplete': function() {
alert("foi tudo");
}
});
}
function saveLegend(id)
{
var text = jQuery('#' + id).val();
jQuery.ajax({
type: 'GET',
url: '<%= ResolveUrl("~/build/UpdatePhotoLegend")%>/' + id,
data: 'legend=' + text,
success: function(data) {
alert('Alterado com sucesso!');
}
});
}
function AddNullValueSelectObject(object_id) {
jQuery('#' + object_id).append("<option value='00000000-0000-0000-0000-000000000000'>--- SELECIONE ---</option>");
jQuery("#" + object_id + " option[value='00000000-0000-0000-0000-000000000000']").attr('selected', 'selected');
}
</script>
</asp:Content>
thanks in advance...
Normally I wouldn't answer unless I was fairly sure of my answer, however, since noone else is responding...
I have no experience with uploadify but it looks like you are using an old version of uploadify and the api has changed quite a bit so it's hard for me to say for sure. I think the 'script' parameter is actually referring to the server side "script" that would normally handle the saving of the uploaded file (the 'uploader' parameter in the current version http://www.uploadify.com/documentation/uploadify/uploader/).
Do you have a BuildController class with an UploadImages action (method)? If so, that is probably one of the causes of your error (something erroring while saving to disk). If you do have a BuildController, I wonder if that call to resolve url is correct? The resolved path looks off to me (normally you would not resolve a route based url in mvc as resolve url isn't route aware).
If you don't have a BuildController and I'm totally off let me know and I'll remove this answer. It's somewhat a shot in the dark. But it is plausible.
EDIT: Just in case you have no experience in MVC at all, the code from the "Build folder" should be located in your mvc web app under a folder called Controllers inside a class called BuildController inside a Method called UploadImages.
Promoted my comment to an answer
It's possible that the script is embedded as a resource. Try using ILSpy to confirm this. In that case you will need to access the source code. Also, it maybe that the script was minified/obfuscated and that's why you can't find anything.

Can't pass variable from JQuery AJAX to C# code behind

Not sure what I'm doing wrong but I can't get my JQuery AJAX call to pass the variable properly. It recieves it just fine. I'm probably overlooking something minor. Thanks.
(Also, is there any way to pass data this way without using a [WebMethod] or via the URL?)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$('#button').click(function(){
var json_obj = "{'" + $('#t1').val() + "' : '" + $('#p1').val() + "', '" + $('#t2').val() + "' : '" + $('#p2').val() + "'}";
$.ajax({
type: "POST",
url: 'Default.aspx/test',
contentType: 'application/json; charset=utf-8',
data: "thisisatest",//json_obj,
dataType: 'json',
success: function(msg) {
//$('#result').html(msg.d);
alert(msg.d)
},
error: function(msg) {
//$('#result').html(msg.d);
alert(msg.d + " err")
}
});
});
});
</script>
</head>
<body>
<div>
Type: 1: <input type="text" id="t1" />
Property 1: <input type="text" id="p1" />
<br /><br />
Type 2: <input type="text" id="t2" />
Property 2: <input type="text" id="p2" />
<input type="button" value="Add object!" id="button" />
<br /><br />
<div id="result"></div>
</div>
</body>
</html>
Code Behind
[WebMethod]
public string test(string json)
{
return json;
}
Here's a full example I wrote for you to illustrate the concept:
<%# Page Language="C#" %>
<%# Import Namespace="System.Web.Services" %>
<script type="text/C#" runat="server">
public class MyModel
{
public string T1 { get; set; }
public string P1 { get; set; }
public string T2 { get; set; }
public string P2 { get; set; }
}
[WebMethod]
public static string Test(MyModel obj)
{
return "Hello from test";
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Type: 1: <input type="text" id="t1" />
Property 1: <input type="text" id="p1" />
<br /><br />
Type 2: <input type="text" id="t2" />
Property 2: <input type="text" id="p2" />
<input type="button" value="Add object!" id="button" />
<br /><br />
<div id="result"></div>
<script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$('#button').click(function () {
var data = JSON.stringify({
obj: {
t1: $('#t1').val(),
p1: $('#p1').val(),
t2: $('#t2').val(),
p2: $('#p2').val()
}
});
$.ajax({
url: 'default.aspx/test',
type: 'POST',
contentType: 'application/json',
data: data,
success: function(result) {
$('#result').html(result.d);
}
});
return false;
});
</script>
</body>
</html>
I have mixed here the code behind and the markup in the same Default.aspx file but obviously you could have them separate if you prefer.
WebMethods must be static!
http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
[WebMethod]
public static string test(string json)
{
return json;
}
and your JSON input should be :
var jsonInput = { 'json': 'XXXXXXX'};
where 'json' is equal to the name of the webmethod parameter
and in the Ajax function
data:JSON.stringify(jsonInput)
You can change the method to GET and append the value to the URL like so...
$.ajax({
type: "GET",
url: 'Default.aspx/test?json=' + 'thisisatest',
contentType: 'application/json; charset=utf-8',
success: function(msg) {
//$('#result').html(msg.d);
alert(msg.d)
},
error: function(msg) {
//$('#result').html(msg.d);
alert(msg.d + " err")
}
});
Then in your code behind....
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json; charset=utf-8";
Response.Write(Request["json"]);
}
If You're going to go this route though, I'd recommend not using Code Behinds as they have to process the entire ASP.NET Web Forms Page Life Cycle. You're better of using ASP.NET Handlers (ashx).
Good luck!

Categories

Resources