I am trying to add the record to DB using Ajax and get the data back from JsonResult if success, in order to call the function further, but somehow always land in the error: parseerror. However, the record is inserted in DB.
Here is my post method:
$("body").on("click", "#btnAdd", function () {
var txtTermName = $("#txtTermsName");
var txtAlternativeTerms = $("#txtAlternativeTerms");
$.ajax({
type: "POST",
url: "/Administration/AddTerm",
data: '{name: "' + txtTermName.val() + '", alternatives: "' + txtAlternativeTerms.val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var row = $("#tblTerms tr:last-child");
if ($("#tblTerms tr:last-child span").eq(0).html() != " ") {
row = row.clone();
}
AppendRow(row, r.Name, r.Alternatives);
txtTermName.val("");
txtAlternativeTerms.val("");
},
error: function(textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
});
And my controller JsonResult:
[HttpPost]
public JsonResult AddTerm(Term term)
{
this.SaveTerm(term);
return Json(term);
}
Any comment or suggestion is appreciated
UPDATE
Json(term).Data contents:
- Json(term).Data {Models.Term} object {Models.Term}
+ ChangedBy
Description null string
ID 27 int
Inactive false bool
Name "sdfgdsgf" string
SynonymsList "sdfgdsgfdsgsdgf" string
+ Updated {09.08.2018 10:00:50} System.DateTime
Looks like an exception is being called somewhere after your database save call (I take it the SaveTerm method does more than just save the item?) resulting in an error page being returned instead of JSON - hence the parse error.
Try adding a Try { } Catch { } to the action and I reckon there will be an exception caught from the SaveTerm method.
Related
I know this question has been asked many times but no matter what i try i just can't get it to work. I have an actionResult that accepts three parameters and returns a partial view. Now what i want to do is take the values of three elements and re-render the view in a div using them. I have tried to use the captured data to render the div succesfully but i can't figure out what i'm doing wrong with jquery
In the script file are included the last things i tried(although in every attempt there was some tweaking before giving up)
Here is the RenderAction in the main view (that works)
<div id="tables">
#{ Html.RenderAction("_Tables", new { date = "5/10/2019", time = "13:00", seats = "1" });}
</div>
the action result that returns said Partial
public ActionResult _Tables(string date, string time, int seats)
{
return PartialView("_Tables", checkTables(date,time,seats));
}
And finally the script(searchTable is a button near the fields. Their values are captured succesfully but load does not work)
$('#searchTable').click(function () {
var date = document.getElementById("datepicker").value;
var time = document.getElementById("time").value;
var seats = document.getElementById("seats").value;
alert(date);
//var data = JSON.stringify({
// 'date': date,
// 'time': time,
// 'seats': seats
//});
//$.ajax({
// type: "POST",
// url: '/Home/_Table/',
// data: data,
// dataType: "html",
// success: function (result) { success(result); }
//});
//function success(result) {
// alert(result);
// $("#tables").html(result);
// $("#tables").load("#tables")
//};
//$.ajax({
// url: "/Home/_Table",
// type: "GET",
// contentType: "application/json; charset=utf-8",
// data: data,
// success: function (data) {
// $('#target').html(data); // loading partialView into div
// }
//});
//$('#tables').load('#{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
$('#tables').load('#Url.Action("_Tables","Home")', { 'date': date, 'time': time, 'seats': seats });
alert(time);
//alert('#{ Html.RenderAction("_Tables", new { date = "' + date + '", time = "' + time + '", seats = "' + seats + '" });}');
});
I know the problem lies in my lack of understanding but i do not have the time to research ajax. My internship is based on "figuring it out" under deadlines"
Suppose you have a div with id tables as
<div id="tables">
You can use the following method of appending the partial view content based on your paramters as
$.ajax({
url: "/Home/_Tables?date=" + val + "&time="+ val +"&seats="+seats,
type: "POST",
cache: false,
success: function (result) {
$("#tables").empty();
$("#tables").html(result);
},
error: function () {
$("#tables").empty();
}
});
this will be the main view ajax function.and in the controller do the following
public ActionResult _Tables(string date, string time,string seats)
{
// here you can provide model,any viewbag values etc to the partial view and you will get corresponding html result
return PartialView("Yourpartial ViewName");
}
I see a commented line in your code :
$("#tables").html(result);
It's all you need!
You should fill your div with all partial view html that returns from your controller.
I am a beginner in programming, I have researched a few places to implement the jquery autocomplete. I managed to call postback to JSON GROUP method. But after success, I can't manage to get the JSON results or if I code it wrongly. Please help
Code
$(function () {
$("#txtGRP_CODE").autocomplete({
source: function (request, response) {
$.ajax({
url: '/AutoComplete/GRP_CODE',
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ 'prefix': '" + request.term + "'}",
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#txtGRP_CODE").val(i.item.value);
},
minLength: 1
});
});
Server Side
[HttpPost]
public JsonResult GRP_CODE(string prefix)
{
List<AutoCompleteController> listGroup = new List<AutoCompleteController>();
string sSQL = " SELECT * FROM icgrp WHERE GRP_CODE like '" + prefix + "%'";
DataTable dt = conn2.GetData(sSQL);
using (MySqlDataReader dr = conn2.ExecuteReader(sSQL))
{
//foreach (DataRow dr in ds.Tables[0].Rows)
while (dr.Read())
{
listGroup.Add
(new search
{
Name = dr["GRP_CODE"].ToString(),
Sr_no = dr["GRP_PART"].ToString()
}
);
}
}
//**I manage to populate listGroup but when passing it to the client side I can't get the Json data.
return Json(listGroup, JsonRequestBehavior.AllowGet);
}
Server Side
https://ibb.co/sVbKSYG
Client side
https://ibb.co/09CFXdW
Network Client Response
https://ibb.co/BB61dRd
Response
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /AutoComplete/GRP_CODE
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3282.0
I am having gridview showing data from database such as
ProductID ProductName Price
----------------------------------
A00001 Apple 10.00 ADDTOCART
The ADDTOCART is a button.
GridViewRow gr = ((sender as LinkButton).NamingContainer as GridViewRow);
string itemId = gr.Cells[0].Text.Trim();
These are the code I use for codebehind to get the ProductID when click on ADDTOCART
Need assist for the code which can let the variable I declared in Jquery to get the ProductID like what the codebehind do when I click the ADDTOCART button.
function ShowCurrentTime() {
var name = "The name";//$("#<%=txtUserName.ClientID%>")[0].value; //get the data.
var id = "The id";//$("#<%=TextBox1.ClientID%>")[0].value; //get the data.
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}
function OnSuccess(response) { //fetching object come out, object inside got name and id, need to specific which data you want by obj.id/obj.name
var obj = response.d; //fetching the webmethod
alert(obj.id + "" + obj.name) //display the return
$('#trycart').append("<li>" + obj.id + "</li>");
$('#cart').append("<tr><td>" + obj.id + "</td><td>" + obj.name +"</td></tr>"); //access the table id=cart, add in the data comeback from webmethod.
}
I need assist to have the var name to have the product name, and var id to have the id when I click ADDTOCART.
The element name and selectors can be manipulated by looking at the Dom.
In the button onclick pass this as parameter
function ShowCurrentTime(element)
{
var name = $(element).closest("tr").find("input[id*='txtUserName']").val();
var id = $(element).closest("tr").find("input[id*='TextBox1']").val();
$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCurrentTime", //the url and method name of the webmethod
data: "{ name: '" + name + "', id: '" + id + "' }", //pass in 2 data.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) { //fixed
alert(response.d);
}
});
}
I guess that Your data from database is in your C# application, which is on your server side. The code above are jquery/javascript, which is on your client side.
It's very important to know the difference on server side and client side. Basically say, everything you can see from "view source" from browser, are client side, otherwise, on server side.
So go back to your question, you can build html with data from database in your c# application, or build json data object, and in turn use it in jquery.
Hope helps
I have an AJAX method to tell the user whether or not an email is available when registering.
$('#mainArea_txtEmail').keyup(function (e) {
var inputemail = $(this).val();
if (inputemail.length > 5)
{
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert("available"),
failure: alert("unavailable")
});
}
});
When a user types in an email, whether it is available or not, the browser displays the success alert and then the failure alert every time.
Here is the C# method:
[System.Web.Services.WebMethod]
public static string isEmailAvailable(string email)
{
BasePage page = new BasePage();
string returnvalue;
if (page.db.UserGet(email) == null)
{
returnvalue = "true";
}
else
{
returnvalue = "false";
}
return returnvalue;
}
The db.UserGet method will try and find a database record of a user with the email address matching the email parameter. If there is one, then a User class instance is populated and page.db.UserGet is not null, meaning the email is taken. If it is still null, then no user with that email was found and the email is available.
What am I doing wrong here?
I was following this tutorial (http://www.c-sharpcorner.com/UploadFile/20abe2/how-to-check-user-name-or-email-availability-using-Asp-Net)
Your syntax won't work, you can't use alert as the callback function. alert needs to be wrapped in a proper function or it will fire immediately
$.ajax({
type: "POST",
url: "Default.aspx/isEmailAvailable",
data: '{email: "' + inputemail + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(serverResponse) {
alert("available");
/* do something with serverResponse */
},
failure: function() { alert("available"); }
});
$.ajax API Reference
I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.