how to save textbox data in database using javascript json - javascript

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
$(function () {
$("[id*=btnaddrecords]").bind("click", function () {
var user = {};
user.invoice_no = $("[id*=txtinvoice]").val();
user.sale_description = $("[id*=txtsale]").val();
user.transdate = $("[id*=txttdate]").val();
user.transtype = $("[id*=ddtransaction]").val();
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>

There are two main problems in the code you shared:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
$(function () {
A script element can load one script. It can load it from a URL using a src attribute, or it can be embedded a child node. You can't have both at the same time.
You need two script elements.
You should also consider using the current version of jQuery. 1.6.2 is very old.
You say you are sending JSON:
contentType: "application/json; charset=utf-8",
but:
'{user: ' + JSON.stringify(user) + '}'
Will not give you JSON.
You need:
JSON.stringify({ user: user })
This assumes that Default.aspx/SaveUser expects a JSON formatted request in the first place.

Related

Calling a javascript function from a global file and return it to append to html

I have a global javascript file 'Global.js' with a Global Handler 'GlobalHandler.ashx',
what i am trying to do is to render some data in the back-end (inside the handler ), than return text data using context.Response.Write(MyString)
The question is how to append the data to my html element .
I looked into the response (200) and the data is there , but i don't know the reason of not appending my text into the html element
I have tried to append them like the classic way success:function(data){
$(elementID).html(data);}
But that doesnt work
Here In Global.js
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here In MyPage.aspx
$(document).ready(function () {
GetProfession("Profession");
});
HERE In the Handler
string functionName = context.Request["functionName"];
GroupDAO GroupDAO = new GroupDAO();
if (functionName.Equals("GetProfession"))
{
var ListOfGroups = GroupDAO.GetGroups();
string Builder = "";
foreach (var group in ListOfGroups)
{
Builder+="<option value='" + group.GroupID + "'>" + group.GroupName + "</option>";
}
context.Response.Write(Builder);
}
I am expecting to have those options appended to the html element 'Profession'
but this unfortunately it does not happening
I found the answer , i did not recognize the logical reason of such behaviour ,
but the data was not in the success method even if the statuc code was 200 .
in fact it was in the error: properties of ajax request .
what i have done is :
instead of appending the data in success to the html element .
i did it in the response text
.
Here is the code before not working :
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here is the one that works
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "text/html; charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data, fata, meta) {
},
error: function (err) {
$("#Profession").html(err.responseText);
//alert(err.responseText);
}
});
}

Error function called when I parse the parameters using jquery AJAX function to asp.net behind code

This is my aspx page code
function grid(datas)
{
var datass = {datas: datas};
var myJSON = JSON.stringify(datass);
$.ajax({
url: 'EditCustomerBills.aspx/LoadGrid',
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: myJSON,
success: function (data) {
alert("Success");
},
error:function(error){
alert("failed");
}
});
}
and this is my behind code
[WebMethod]
public static string LoadGrid(string datas)
{
//GetCustomerBillDetail(data);
string datass = datas.ToString();
return datass;
}
I'm using code perfectly, but output is failed. I'm struggling for four days. please help me. thank you.
I don't know what is your "myJSON" is . according to me your code should be sometinhg like this.
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string datas)
{
return "Hello " + datas + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/GetCurrentTime",
data: '{datas: "Your Data" }', // your data should be here.
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
</script>
below picture will give you a idea how we can call the server side method.
for more reference please see this.
edit as follows and share with f12 in console output?
error: function (error) {
console.log(error);
}

How to access JS variable of one razor page in other razor page? [duplicate]

This question already has answers here:
.Net Razor - sharing variables between pages
(2 answers)
Closed 5 years ago.
How do i access variable "DataToBind" of One.cshtml page in Two.cshtml page?
One.cshtml
<script>
var DataToBind;
$.ajax({
url: "/Home/getDetails",
type: "POST",
dataType: "json",
data: JSON.stringify({ agencyID: agencyID, salesID: saleID, DebtorID: debtorID, AccountNo: accountNO }),
contentType: 'application/json; charset=utf-8',
success: function (response) {
DataToBind = response[0];
window.location.href = "Two";
}, error: function () {
console.log("new error");
}
});
</script>
Two.cshtml
I get this error : Uncaught ReferenceError: DataToBind is not defined
when i use "DataToBind" variable in this page.
As I understand you are trying to get some value and use it in another page.
This is a bit unusual scenario, but you best shot is
<script>
var DataToBind;
$.ajax({
url: "/Home/getDetails",
type: "POST",
dataType: "json",
data: JSON.stringify({ agencyID: agencyID, salesID: saleID, DebtorID: debtorID, AccountNo: accountNO }),
contentType: 'application/json; charset=utf-8',
success: function (response) {
c= response[0];
window.location.href = "Two?data=" + DataToBind;
}, error: function () {
console.log("new error");
}
});
</script>
and in your page Two access this data
<script>
var DataToBind = #(Request.QueryString["data"])
...
</script>
or another way
<script>
var DataToBind = #HttpContext.Current.Request.QueryString["data"]
...
</script>
and then you can use your DataToBind on Two.cshtml

Autocomplete in two input boxes? - javascript

Hi i am trying to find out how to use my javascript code for two input boxes. the data its grabing and the URL is using C# code but that should not matter. Please help me with my autocomplete..
Here is a test page of it in action
http://www.bivar.com/test.aspx
Here is the code i am using for the javascript.
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
select:function(event, ui){
window.location.href = '/Products/ProductInfoCenter.aspx?partnum=' + ui.item.value;
},
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/test.aspx/GetAutoCompleteData",
data: "{'PartNumber':'" + document.getElementById('txtPartNum').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert(err.message);
}
});
}
});
}
</script>
Here are the two input boxes
<input type="text" id="txtPartNum" class="autosuggest" />
<input type="text" id="txtPartNum2" class="autosuggest" />
Thank you and please help.
Here is your function updated. Tested and its working perfectly. Problem was that, it was passing value of first input box every time. I used $(this.element) to get current element on which autocomplete is requested. When dealing with classes we have to make use of (this) keyword to avoid conflicts.
function SearchText() {
$(".autosuggest").autocomplete({
select:function(event, ui){
window.location.href = '/Products/ProductInfoCenter.aspx?partnum=' + ui.item.value;
},
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/test.aspx/GetAutoCompleteData",
data: "{'PartNumber':'" + $(this.element).val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert(err.message);
}
});
}
});
}
The only problem I see is that both the inputs are sending same data as parameter. But that is what it supposed to do isn't it? Because you are using this -
data: "{'PartNumber':'" + document.getElementById('txtPartNum').value + "'}",
in your code. I think this is the error. But please make sure you ask properly what you are looking for. Your question is not completely understandable. A usual code should look like this -
data: "{'PartNumber':'" + request.term + "'}",
Let me know if this what you were looking for.

How to redirect an asp.net webform to another webform using javascript?

I have the following script in my asp.net webforms project, and I want to redirect to a new page let's say NewForm.aspx in my project how do i do that?? I've tried the window.location.href but it didn't work. A bit of help would be appreciated, thanks!
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'DetailsForm.aspx/InsertMethod',
data: "{'firstname':'" + document.getElementById('firstName').value + "', 'lastname':'" + document.getElementById('lastName').value + "'}",
async: false,
success: function (response) {
$('#firstName').val('');
$('#lastName').val('');
alert("Record saved to database successfully!");
},
error: function ()
{ console.log('there is some error'); }
})
});
});
</script>

Categories

Resources