Send to database using ASP.NET, c# and jQuery - javascript

New to AJAX here.
Been trying to send to my database using AJAX but is is not working.
In my aspx.cs:
[WebMethod]
public static void saveMsg(string roomCode, string userName, string msg)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LBConnectionString"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT into chatTable(roomCode, uName, msg) VALUES (" + roomCode + ", '" + userName + "', + '" + msg + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
I am trying to insert data using AJAX and C# ASP.NET.
This is my aspx file
$.ajax({
type:'POST',
contectType: "application/json; charset=utf-8",
dataType: "json",
url:"Room.aspx?Board='" + roomCode + "'",
data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
})
The full url is http://localhost:1759/Room?Board='//roomcode'.
Is there anything that went wrong? Like how I put the url into the AJAX function?
Thanks in advance!
EDIT:
Is it needed to put data type as JSON? New to JSON too...

Try this code :
Javascript :
function Getpath() {
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
}
var Domainpath = window.location.origin + "/";
if (Domainpath.indexOf("localhost") == -1) {
return Domainpath;
}
else {
return Domainpath;
}
}
Ajax:
You will get the path in Getpath() Method.
var path = Getpath();
$.ajax({
type:'POST',
contectType: "application/json; charset=utf-8",
dataType: "json",
url: path +"Room.aspx?Board='" + roomCode + "'",
data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
})

You Need to Pass correct URL to call method.
$.ajax({
type:'POST',
contectType: "application/json; charset=utf-8",
dataType: "json",
url:"Room.aspx/saveMsg",
data: "{'roomCode':'" + roomCode + "','uName':'" + userName + "','msg':'" + <%=message.ClientID %> + "'}",
})

Related

how to sent a text to a specified email address when pressing a button html and javascript

function sendEmailToUser(){
var msgTo = "cigma#gmail.com";
var msgFrom = "drrama#gmail.com";
var messageBody = " Your code is 1234567";
var msgSubject = "CODE";
$.ajax({
type: "POST",
url: "/services/Mail.asmx/SendMail",
cache: false,
contentType: "application/json; charset=utf-8",
data: "{ 'body':'" + messageBody + "'," +
"'to': '" + msgTo + "'," +
"'from': '" + msgFrom + "'," +
"'subject': " + msgSubject + "'" +
"}",
dataType: "json",
complete: function (transport) { if (transport.status == 200) $("#formcontainer").html("Success"); else alert("Please try again later"); }
});
}
This is my function in javascript code that is called when ever a button is clicked, so as to sent text to the specified email address as shown in the code, but the function always returns "Please try again later" as a error message. It does not sent a text to cigma#gmail.com

Trying to stringify textbox input data and uploaded images in json format to send through ajax

I am trying to stringify textbox input data and uploaded images in json format to send through ajax.but getting error at alert(file[0].name + " is not a valid image file.");
and at this point in ajax part data: '{user: "' + JSON.stringify(user) + '",byteData: "' + byteData + '", imageName: "' + fileName + '", contentType: "' + contentType + '" }',
Given below is the script which is accepting value from textboxes, labels and image upload control and then stringify all the values and passing it through Ajax in json Format.
enter image description here
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
var reader = new FileReader();
var fileName;
var contentType;
$("#pdfForm").on('change', 'input[name=flImage]', function () {
alert('Thanks for selecting image');
if (typeof (FileReader) != "undefined") {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
fileName = file[0].name;
contentType = file[0].type;
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
user.REVISION = $("#Revision").text();
user.REVISION_DATE = $("[id*=Revision_Date]").text();
user.P_GROUP = $("[id*=P_Group]").val();
user.PROD_DESC = $("[id*=Prod_Desc]").val();
user.N_I_PRD_STD = $("[id*=N_I_Prd_Std]").val();
user.APPLN = $("[id*=Appln]").val();
user.FRM_SUPP = $("[id*=Frm_Supp]").val();
user.CREATED_DATE = $("#Revision_Date").text();
user.CREATED_BY = $("[id*=lblUserName]").text();
var byteData = reader.result;
console.log(byteData);
byteData = byteData.split(';')[1].replace("base64,", "");
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: '{user: "' + JSON.stringify(user) + '",byteData: "' + byteData + '", imageName: "' + fileName + '", contentType: "' + contentType + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
For ajax file upload, it is better to use Formdata refer the link below
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Hope this helps. Please feel free to ask for any clarifications

display image using jquery and ajax

To display company details with image,
I have controller like:
public JsonResult PrintHeading()
{
CompanyModel cm = new CompanyModel();
string qry = "select CompanyName,Address,ContactNo,EmailAddress,LogoFileName from tblCompanyInfo";
DataTable dt = cls.LoadData(qry);
foreach (DataRow dr in dt.Rows)
{
cm.CompanyName = Convert.ToString(dr["CompanyName"]);
cm.Address = Convert.ToString(dr["Address"]);
cm.ContactNo = Convert.ToString(dr["ContactNo"]);
cm.EmailAddress = Convert.ToString(dr["EmailAddress"]);
cm.LogoFileName = Path.Combine("\\Content\\Logo", Convert.ToString(dr["LogoFileName"]));
}
return Json(cm, JsonRequestBehavior.AllowGet);
}
and Function:
function getPrintHeading() {
var heading = '';
$.ajax({
url: '#Url.Content("~/Bank/PrintHeading")',
type: "GET",
dataType: "JSON",
async: false,
success: function (headdata) {
heading = '<img src="' + headdata.LogoFileName + '" width=50 height=50>' + headdata.CompanyName + '<br>' + headdata.Address + '<br>' + headdata.ContactNo + ', ' + headdata.EmailAddress ;
}
});
return heading;
}
It displays all other data but doesn't display image.please Can you give the idea?
I think you forgot to close img tag.Check it once may help You.
<img src="' + headdata.LogoFileName + '" width=50 height=50 />

Retrieve multiple using OData in CRM 2011

I want to retrieve multiple record. Here is my code;
function GetQuoteDetails(quoteId) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataSetName = "QuoteDetailSet";
var odataSelect = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "$filter=QuoteId/Id eq guid'" + quoteId + "'";
var jSonArray = new Array();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null) {
jSonArray.push(data.d);
}
},
});
return jSonArray;
}
It returns nothing. But there should be 4 records returned. Where is the problem?
Since this is Asynchronous call, you cannot return from function GetQuoteDetails. For verification either use Console.log or alert to check what is data.d value.

How to pass values to asp pages from javascript?

I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {
var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;
var stat = document.getElementById('drp_state').value;
$.ajax({
async: false,
type: "POST",
url: "DealerDetails.aspx/UpdateDealer",
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
$.each(msg.d, function (index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function () {
sprtengId = $(this).val();
});
},
error: function () {
alert("Error");
}
});
}
And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
}
catch {}
return update;
}
#endregion
When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;
Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr
also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;
Make sure you debug and variables you have defined are initialized.
remove static from
public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
Int32 DlrLan, Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
}
catch { }
return update;
}
function btn_upgrade_onclick() {
var dealerID = "1";
var dlr = "1";
var dlrname = "abc";
var addr1 = "india";
var addr2 = "delhi";
var addr3 = "delhi";
var mobno = "1234567890";
var stat = "";
var DlrLan = "123";
var Dlrddd = "1123";
$.ajax({
type: "POST",
url: "AutoComplete.asmx/UpdateDealer",
data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
+ DlrLan + "', DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
alert(data);
$.each(msg.d, function(index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function() {
sprtengId = $(this).val();
});
},
error: function() {
alert("Error");
}
});
}

Categories