Hi I'm trying to do just a simple ajax call to a method in my code behind. At this point I'm just testing, so I'm keeping it as simple as possible, but it's always erroring. I'm sure it's just a simple mistake, but I have no idea what to do. It seems really straight forward, and it should work, but when I click the button, it just pops up an alert saying "[object Object]". Here is my code, any help is greatly appreciated:
aspx file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="Program.TestPage" %>
<!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 runat="server">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" id="btnSubmit" value="Submit" />
</div>
</form>
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TestPage.aspx/InsertData",
dataType: "json",
data: "{}",
success: function (data) {
alert(data.d);
},
error: function (result) {
alert(result);
}
});
});
});
</script>
</body>
</html>
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.Text;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Web.Services;
namespace Program
{
public partial class TestPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string InsertData()
{
string retMessage = "ddd";
return retMessage;
}
}
}
UPDATE
Sorry everyone, turns out the issue was in my global.asax. It was intercepting the ajax request, and messing everything up. Once I made sure the HTTP was a GET in the asax file, it stopped killing my ajax request, and started working.
In your javascript, you're calling InsertData as a POST
Try
[WebMethod]
[HttpPost]
public static JsonResult InsertData()
{
return Json(new { Message = "ddd" }, JsonRequestBehavior.AllowGet);
}
And in your javascript,
success: function (data) {
alert(data.Message);
},
You can try this:
var dataToPost = "{ country:'" + 2 + "', amount:" + 4.02 + "}";
$.ajax({
url: #Url.Action("PostAmount", "Deal")',
type: "POST",
dataType: 'json',
data: dataToPost,
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
alert("hi"+ data);
}
});
Related
I have a autocomplete in a grid-view in a ascx file but the autocomplete is not working in the ascx file. I have made several similar autocomplete in other page that work. Why is it that the autocomplete does not work in my ascx file. I have a hypotheses why it does not work but I am unsure how to fix it here it is
I think that the problem is with the following url in the javascript
url: "contratoGerencia.aspx/getSupplierAndComponente"
However I dont know how I should change it don get it to work with the ascx file.Also I found a solution here https://www.codeproject.com/Questions/757769/How-to-Call-Ascx-page-form-JavaScript-Funnction-Of that is almost what I want the only problem is that I also have a textbox in my situation.
Any help would be very appreciated. I hope the following information will help you.
Here is my ascx (ComponentesControler.ascx) code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="../css/autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../scripts/autocomplete.js" ></script>
<asp:TextBox CssClass="gridContractAndComponente" ID="txtContractComponenteFooter" Text="" runat="server" TextMode="MultiLine" Rows="1" />
Here is my ascx.cs (ComponentesControler.ascx.cs) code
[WebMethod]
public static List<string> getSupplierAndComponente(string prefixText)
{
string lv_numero_contrato;
List<string> numeros_contrato = new List<string>();
connectionStringBuilder builder = new connectionStringBuilder();
String connString;
connString = builder.builder.ConnectionString;
string selectStatement = " SELECT numero_contrato FROM erp_contratos ";
using (MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = selectStatement;
cmd.Parameters.AddWithValue("#searchText", prefixText);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
lv_numero_contrato = reader.GetString(reader.GetOrdinal("numero_contrato"));
numeros_contrato.Add(lv_numero_contrato);
}
}
conn.Close();
}
}
return numeros_contrato;
}
Here is the aspx page (contratoGerencia.aspx) were I use the ascx file
<div id="ComponentesSection" class="menusection">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Always" >
<ContentTemplate>
<TWebControl5:WebControl5 ID="Header8" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Here is my javascript file (autocomplete.js)
$(document).ready(function () {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
The problem is in the name of your parameter entered in AJAX, your method expects to receive a parameter named prefixText and not containedText.
Change
data: {'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
with
data: {'prefixText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
The issue can be triggered by the UpdatePanel like explained here:
jQuery $(document).ready and UpdatePanels?
So modify your autocomplete.js like this:
$(document).ready(function() {
SearchSupplierAndComponente();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
See if the console error goes away.
I have a front end code which sends a POST request to the server and returns nothing as the server needs the information.However in Chrome's log i see a 404
Thanks,
Failed to load resource: the server responded with a status of 404
(Not Found)
The following code sends the server a request:
var data = "hi"
var theIds = JSON.stringify(data);
var UrlFixer = '/Process/Complete';
// Make the ajax call
$.ajax({
type: "POST",
url: UrlFixer,
contentType: "application/json; charset=utf-8",
data: { ids: theIds },
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
Backend(C#):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Quiz3
{
public class Process
{
[HttpPost]
public static void Complete(string[] ids)
{
String[] a = ids;
}
}
}
You can get help from the code below to send data.
You do not have to submit a string item in the form { ids: theIds } You must change the form to JSON.stringify(data) .
var data = "Your Name";
$.ajax({
url: '/home/Complete',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
And your class should not be simple. You must have a controller class
Backend:
public class HomeController : Controller
{
[HttpPost]
public void Complete(string Name)
{
//Code ...
}
}
Maybe send your Ids as a list of id and don't stringify your list
public static void Complete(List<T> Ids)
I managed to get this to work with MVC Empty template by the following method:
Firstly a controller is made(inside the controller folder) and its named 'SubmitController'.Now at first i thought that naming it controller at the end is not important but it turns out it is and the URL would be '/Submit' and not '/SubmitController'.
Inside the C# file a function is made and i called it 'Process' with an POST attribute(HttpPost).The URL now would be '/Submit/Process'.In my case i needed to pass an array from the client to server and that is the extra piece of code used in C# to process it and display on the Output page of Visual studio.
SubmitController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class SubmitController : System.Web.Mvc.Controller
{
[HttpPost]
public PartialViewResult Process(string myArray)
{
String[] Items = myArray.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
//print
Items.ToList().ForEach(i => System.Diagnostics.Debug.WriteLine(i.ToString()));
return null;
}
}
}
SendEvent.js
// Make the ajax call
var myArray = data;
$.ajax({
type: "POST",
url: '/Submit/Process',
data: { 'myArray': myArray.join(',') },
});
I can't seem to get this simple function working.
The AJAX call returns success but the function is never being called since the Debug.WriteLine is not showing up. The "Function has been called" alert does pop up. There are no errors in the Chrome console.
I am using ASP.NET Web Forms
The Contact.aspx.cs file:
public partial class Contact : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Debug.WriteLine("Contact Page loaded");
}
[System.Web.Services.WebMethod]
public static string Test(string test)
{
Debug.WriteLine("Input param"+test);
return test;
}
}
In the Contact.aspx file
<button type="button" class="btn btn-info" onclick="ShowTest()">Test</button>
<script type = "text/javascript">
function ShowTest() {
//Tried this also (prefered)
//var res = PageMethods.Test("testMessage");
var testMsg = 'This is the test message';
$.ajax({
type: "POST",
url: "Contact.aspx/Test",
data: JSON.stringify({
test: testMsg
}),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
alert('It worked! ' + result.d);
},
error: function (result) {
alert('Nope');
}
});
alert("Function has been called");
}
</script>
I have found the solution!
Authentication failed in call webmethod from jquery AJAX
Blockquote
I found the answer
Just comment below line in RouteConfig file
//settings.AutoRedirectMode = RedirectMode.Permanent;
I have a asp.net form that uses ajax for form submit and when I click the button that uploads the files, the alert message in the error in jQuery is being displayed, but when I check the files on the server, the files are being uploaded with no problem.
Note: If I submit many files with large files, not all files will be submitted.
client page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NewForm_Frontend_test.aspx.cs" Inherits="eformsmanagementtool.NewForm_Frontend_test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="JavaScript/jquery-1.12.3.js"></script>
</head>
<body>
<form id="form1" runat="server">
<input id="name" type="text" placeholder="name" />
<button id="btnUpload">Click</button>
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="True" />
</form>
<script type="text/javascript">
$("#btnUpload").click(function (event) {
alert("Script Started")
var files = $("#FileUpload1")[0].files;
if (files.length > 0) {
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
alert("Number of files: " + files.length)
formData.append("Name", "John");
alert("Before ajax")
$.ajax({
url: 'NewForm_Backend_test.aspx',
timeout: 30000,
data: formData,
method: 'post',
contentType: false,
processData: false,
success: function (msg) {
alert("Good")
},
error: function (err) {
alert("Bad")
}
});
}
});
</script>
</body>
</html>
Server side page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Globalization;
namespace eformsmanagementtool
{
public partial class NewForm_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(20000);
string data = Request.Form["Name"];
Response.Write("You've submitted: " + data);
HttpFileCollection files = HttpContext.Current.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fileName = Server.MapPath("~/Documents/" + Path.GetFileName(file.FileName));
if (File.Exists(fileName))
{
File.Delete(fileName);
file.SaveAs(fileName);
Response.StatusCode = 200;
}
else
{
file.SaveAs(fileName);
Response.StatusCode = 200;
}
}
Response.Headers.Add("Content-type", "text/json");
Response.Headers.Add("Content-type", "application/json");
}
}
}
add this in your form attributes : enctype="multipart/form-data">
[PROBLEM RESOLVED]
I had to add async: false to ajax
$.ajax({
url: 'NewForm_Backend_test.aspx',
async: false,
timeout: 30000,
data: formData,
method: 'post',
contentType: false,
processData: false,
success: function (msg) {
alert("Good")
},
error: function (err) {
alert("Bad")
}
});
I want to postback on every keypress/textchanged event in textbox but my javascript is not running. Am i missing something...????
My Html textbox is this:
<asp:TextBox ID="Txt_Search" runat="server" AutoCompleteType="Disabled"
onkeypress="Postback();" OnTextChanged="Txt_Search_TextChanged" AutoPostBack="true">
</asp:TextBox>
My Javascript code is this:
function Postback() {
__doPostBack('<%= Txt_Search.ClientID %>', '');
};
My on textchanged event is this:
protected void Txt_Search_TextChanged(object sender, EventArgs e)
{
FolderStructure.Nodes.Clear();
Searchtxt();
}
I create sample projects ASP.NET WebForms and AJAX.
I Suggest you can use AJAX process .NET Generic Handler File. Please you research about Generic Handler file.
Before create Generic Handler file "Search.ashx" and Paste above the code.
public void ProcessRequest(HttpContext context)
{
var search = HttpContext.Current.Request.Form["term"];
//Dummy Data
List<string> searchList = new List<string> { "Red", "Orange", "Ping", "Blue", "White", "Black" };
string result = string.Empty;
if (!string.IsNullOrEmpty(search))
{
searchList = searchList.Where(x => x.ToLower().Contains(search.ToLower())).ToList();
if (searchList != null && searchList.Count() > 0)
{
foreach (var item in searchList)
{
result += "<li>" + item + "</li>";
}
}
}
else
{
result="<li> Not Found </li>";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
and Create Your Search Page, YourFile.aspx, my file name Search.aspx.
ASPX Page Code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication7.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtSearch" class="js-search" value="Search" />
<div class="searchResult">
<ul>
</ul>
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<script>
$(function () {
$(".js-search").on('keyup', function () {
var term = $('.js-search').val();
if (term.length > 2) {
sendSearchRequest({ "term": term });
}
});
function sendSearchRequest(value) {
var datas = $.ajax({
type: "POST",
url: '/Search.ashx',
cache: false,
async: false,
data: value,
success: function (term) {
$('.searchResult').empty();
$('.searchResult').append(term);
}
});
}
});
</script>
</body>
</html>
This example when all three letters entered send ajax request search.ashx file and contains search term and get result on search page.
I hope that helps.
Modify code as below and check
__doPostBack('Txt_Search', '');
here is demo for dynamic search in asp.net.
Your textbox should be:
<asp:TextBox ID="PopertyName" placeholder="Property Name" href="#"
propertyid="" runat="server" class="dropdownAnchor"
autocomplete="off" onkeydown="SearchProperty()"></asp:TextBox>
here we will call a function named searchProperty() onkeydown event.
so, your ajax should be,
function SearchProperty() {
$.ajax({
url: '<%=Page.ResolveUrl("~/Dashboard/NewDashboard.aspx/GetProperty") %>',
data: "{ 'prefix': '" + $("#PopertyName").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//Your code to bind result that received from your back end.
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
};
these function will call a GetPoprty() method on newDashboard.aspx.cs file.
so my back end method is,
[WebMethod]
public static List<Model.Property> GetProperty(string prefix)
{
// Here you get your text in prefix
}