Step1:
I have defined my script as: on home.aspx page:
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
headers: { "Content-Type": "application/json" },
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Step2:
Call to the script function from button: it's on home.aspx page:
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Step3:
Defined Web method at home.aspx.cs page:
[System.Web.Services.WebMethod]
public static string GetData(string name)
{
return "Welcome";
}
I am getting:
JavaScript runtime error: Unable to get property 'd' of undefined or
null reference
You have to stringify your data:
data: JSON.stringify({ name: "Mobile" })
And use ajax like this:
$.ajax({ ... });
Full script updated:
function ShowCurrentTime() {
$.ajax({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: JSON.stringify({ name: "Mobile" }),
contentType: "application/json",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Try this and tell me if it work :
<script type = "text/javascript">
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);},
failure: function() {
alert("Fail");}
});
}
</script>
Related
I want to pass a list of int ids into my controller, but when the data hits the controller action, the parameter is null
[HttpGet]
public async Task<ActionResult> GetReport(int[] items)
{
var viewModel = await _reportLogic.GetReportByIdAsync(items);
// return something;
}
I have this code in my front end
$('#testPreviewList').click(function (e) {
var items = new Array();
$('.reportId').each(function () {
items.push(this.id);
});
console.log(items);
$.ajax({
url: "/home/GetReport",
type: "GET",
//contentType: "application/json; charset=utf-8",
data: { "items": items},
dataType: "json",
success: function (data) {
//do something
});
$("#datos").html(row);
$('#authorNameTextBox').val('');
},
error: function (result) {
//alert("Error");
}
});
});
What am I doing wrong?
thank you
Use POST instead of GET.
Use Traditional property in ajax, set to true.
$.ajax({
url: "/home/GetReport",
type: "POST",
//contentType: "application/json; charset=utf-8",
data: { "items": items},
dataType: "json",
Traditional: true,
success: function (data) {
//do something
});
$("#datos").html(row);
$('#authorNameTextBox').val('');
},
error: function (result) {
//alert("Error");
}
});
I am using json result to populate the textbox and I can see the values are returned to Razor view using alert. But I am unable to bind them to textbox.
in my layout.cshtml i am loading the jquery files.
![This is in the header section of my layout page][1]
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/jquery-ui")
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/Site")
This is my index file,
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
any help is greatly appreciated.
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
async : false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
try the async:false in ajax
You haven't posted your data response, but if it is an array of strings, the following should do it.
success: function (data) {
response(data);
},
Since you've already provided the data in the format that it needs (a label and a value), you don't have to map the data. Just pass it directly into the response.
login.aspx.cs
[System.Web.Services.WebMethod]
public static string jQueryPageMethod(string name)
{
return "<h3>jQuery - PageMethod </h3>result" + name;
}
JS/Jquery:
If i run below method it works.
$.ajax({
type: 'POST',
url: 'login.aspx/jQueryPageMethod',
data: '{ "name":"exampleValue" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
alert("success");
},
error: function() {
alert('error');
}
});
If i run below method it does not work.
var somevalue = "Value";
$.ajax({
type: 'POST',
url: 'login.aspx/jQueryPageMethod',
data: '{ "name":' + somevalue + ' }', // Problem here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
alert("success");
},
error: function() {
alert('error');
}
});
Where i miss in second example in part of data ?
Your data should not be formatted as a string, but rather as a javascript object like this:
data: { "name": somevalue }, // No Problem here :)
Try this data: '{"queryname":"' + queryname + '"}'
I am calling a web method from asp.net 1.1 site and getting a response.
I use this object to populate some data, Now I want to store this object so that I can also save this data in database while saving click event.
How can I achieve this.
$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (**msg**) {
// STORE THIS msg object.
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
// STORE THIS msg object.
//if hidden field has id 'name'
$('#name').val(data.name);//if json object contains a key 'name'
//if hidden field has class name
$('.name').val(data.name);
//if hidden field name is name <input type="text" name="name" />
$(document).filter(':[name=name]').val(data.name)
//do the same for all elements to save
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
$(document).ready(function () {
$("#Ok").click(function () {
$.ajax({
type: "POST",
url: "/Service.svc/xyz",
data: JSON.stringify(jData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, jqXHR){
// STORE THIS msg object.
/* now you can store data object to where you want to store.*/
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
i have been facing an issue in my loginscreen of my application which is developed with mvc3 and jquery, as i am writing the code for checking login credentials in controller and and that controller event is firing by clciking the buttoon click which is developed using jquery. i would like to navigate someo other page('/Customer/CollaborationPortal') when the login credentials are correct, else i want display message box stating that "credentials are wrong" and this is my code.
JQuery Code
$("#btnGo").click(function (e) {
var RegData = getRegData();
if (RegData === null) {
console.log("Specify Data!");
return;
}
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
Console.Log("success");
error: function () {
//aler('Login error');
Console.Log("error");
}
}
});
});
function getRegData() {
var UserName = $("#txtUserName").val();
var Password = $("#txtPassword").val();
return { "UserName": UserName, "Password": Password };
}
});
Controller Code
public ActionResult IsLoginExsit(BAMasterCustomerDO loginData)
{
if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty (loginData.Password))
{
bool result = Businesss.Factory.BusinessFactory.GetRegistration().IsLoginExist(loginData.UserName, loginData.Password);
if (result)
{
System.Web.HttpContext.Current.Session["UserName"]=loginData.UserName;
return RedirectToAction("/Customer/CollaborationPortal");
}
else
{
ViewData["message"] = "Registration failed";
return View();
}
}
return View();
}
and also it is not entering into "success" and "error" code.
Thanks in advance.
you have specified the error callback inside success callback, move it outside like:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
console.log("success");
},
error: function () {
//alert('Login error');
console.log("error");
}
});
You have error function inside of success function....
This it's what you must have:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//window.location.href('/Customer/CollaborationPortal');
Console.Log("success");
},
error: function () {
//aler('Login error');
Console.Log("error");
}
});
If I were you, I'd return a JSON object to the client like this:
Success:
{
'error' : false,
'redirect' : '/Customer/CollaborationPortal',
'message' : ''
}
Error:
{
'error' : true,
'redirect' : false,
'message' : 'Please do this or that'
}
My jQuery would be:
$.ajax(
{
url: '/Registration/IsLoginExsit',
type: 'POST',
dataType: 'json',
data: JSON.stringify(RegData),
contentType: 'application/json; charset=utf-8',
success: function (response) {
if (response.error)
{
alert(response.message);
return;
}
window.location.pathname = response.redirect;
}
});