Why isn't my C# function executing from ajax Javascript code? - javascript

I have an HTML canvas on my page. When I click the canvas, a simple dot paints. I pass the coordinates into my InsertIntoDB function to enter the x and y coordinates into a MS SQL Server database, but it's not happening.
I can, however, place the C# call into an HTML element and get it to work fine, so long as I use dummy xCoord and yCoord numbers and return something (not void).
My code is actually popping up the "Success!" alert, but when I run a SQL query, there was no INSERT. Here is the Code from Default.aspx:
function insertIntoDB(x, y) {
try
{
$.ajax({
type: 'POST',
url: 'Default.aspx/InsertPoints',
data: "{'xCoord': '" + x + "', 'yCoord': '" + y + "'}",
// '{"xCoord": "' + x + '", "yCoord": "' + y + '"}',
success: function (data) {
alert("Success!");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail: " + textStatus);
}
});
}
catch (e)
{
alert(e);
}
}
Here is the C# code in Default.aspx.cs:
[WebMethod]
public static void InsertPoints(int xCoord, int yCoord) {
string myConn = "Data Source=MYDATABASEINFO;Initial Catalog=DATABASENAME;Integrated Security=False;User ID=USERID;Password=MYPASSWORD";
SqlConnection myConnection = new SqlConnection(myConn);
try
{
myConnection.Open();
SqlCommand myCommand= new SqlCommand("INSERT INTO DRAW (xCoord, yCoord) " +
"Values (" + xCoord + ", " + yCoord + ");", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
Thanks for your help.

You are trying to send json data to server then you have to declare its content type.
add jquery ajax option for content type.
function insertIntoDB(x, y) {
try
{
var data = {
"xCoord": x,
"yCoord": y
};
$.ajax({
type: 'POST',
url: 'Default.aspx/InsertPoints',
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
alert("Success!");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail: " + textStatus);
}
});
}
catch (e)
{
alert(e);
}
}

Try creating an old school Web Service(.asmx file) and not a Web Page(.aspx file).
It will even be better if you create a WebApi endpoint. It is not good practice to use web pages for web services

Try change :
data: "{'xCoord': '" + x + "', 'yCoord': '" + y + "'}",
to:
data: {'xCoord': x , 'yCoord': y },
and try add datatype:
dataType: "json",
contentType: 'application/json',

Related

Ajax character encoding changed after send to server

I have an ajax like this:
$.ajax('../EditUser?userId=' + editingId + '&full_name=' + name + '&position=' + position + '&office=' + office
+ '&office_address=' + office_address + '&age=' + age + '&user_login_name=' + user_login_name + '&email=' + email
+ '&user_type=' + usertype + '&password=' + password + '&meetingIds=' + selectedmeetingid, {
type: 'POST',
success: function (data) {
if (data.indexOf('error://') < 0) {
$('#tbl_meetings').html(data);
} else {
$('#errorMessage').html(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error " + errorThrown);
alert("error " + textStatus);
alert("error " + jqXHR.status);
}
}
);
and my server received data with wrong encoding,example: "Hà Thị Minh Thắng" became "H? Th? Minh Th?ng" after received on server side.I tried adding
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
and
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
}
to my ajax but it didn't works. So, anyone know how to fix this?
Try specifying content type to the ajax request & you have to add header to the server side to receive the charset.
$.ajax({
data: parameters,
type: "POST",
url: your-url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
dataType: 'json',
success: callback
});
// Server Side... (This is an example in php which I have used in my app)
header('Content-Type: text/html; charset=ISO-8859-1');
Hope this helps you!

Send xml as data param to GET method in jQuery?

I have this jquery ajax call:
$.ajax({
context: this,
contentType: 'application/json; charset=utf-8',
type: "GET",
url: "/api/upload?mathml=" + mathml + "&fileName=math", //+ Utility.getRandomInt(1, 100),
dataType: "json",
beforeSend: function (jqXHR, settings) {
console.log("Sending request to generate image...");
},
success: function (data, textStatus, jqXHR) {
img = result;
tinymce.activeEditor.insertContent('<img alt="MathML (base64):' + window.btoa(mathml) + '" src="' + img + '"/>');
console.log("Success: " + textStatus);
editor.windowManager.close();
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error: " + textStatus + ". Error: " + errorThrown + " ");
}
});
And I am sending raw xml/mathml in the url to the GET method. It gives me error that the page was not found since the characters: "<", ">" get converted to url characters with "%" in front.
Is there some jQuery/JavaScript function to do this or should I convert those characters back to "<", ">" on the server side in C#?
Note: I am developing MVC 4/C# web application in Visual Studio 2010.

Updating record via REST does not trigger workflow, CRM 2011

I have a workflow that wait three days and check a boolean field. If the boolean is yes do something, else finish as completed. That boolean field is default no and change to yes with an update via javascript.
I don't know why the workflow always do something even when the boolean field is no.
Javascript updates are not recognized by Dynamics CRM?
Code I'm using to update:
var obj = new Object();
obj.BooleanField= true;
var jsonEntity = window.JSON.stringify(obj);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/CustomEntity";
var ODataPath = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "(guid'" + CustomEntityId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});

Ajax post not sending data out

var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
I have checked and made sure that dataString was sending out correct stuff, however, the ajax was just not sending out any data, no error whatsoever. Even when I changed the url to an invalid one it still went to my success function.
You should pass data as an object instead of a string when you are sending via POST
Example:
data = {
'edulevel': edulevel,
'course': course
(.....)
};
I have made some changes and now this is working your callback function was success() and jQuery was trying to find the function, either you can write your function at same place or you can write a stand alone function and assign it to sucess:, if you are still getting problem try to change your url, if your current files location is /files/file.php
then your veriamateur.php must be /files/process/veriamateur.php
var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: function(){ alert('success');},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});

Error: $.ajax is not a function

Am getting a error like that, $ajax is not working
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: "loginform.aspx/getdataval",
data: "{'uname':'" + $("#TextBox1").val() + "','passwod':'" + $("#TextBox2").val() + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
alert("welcome");
AjaxSucceeded(msg);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("what is the problem")
}
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
var Emp = result.d;
$("#output").append('<p>' + Emp.Sname + ' ' + Emp.Sno + '</p>');
}
</script>
$ ajax not a function why? When I run this script I get error, it not running, what is the problem?
Thanks
You may have an issue with the single/doule quotes on the data string as the JSON standard says double quotes.
You can also simplify the contentType.
I tend to simplify my use of the .d in asp.net by including a converter and the ajax itself using ajaxSetup like so: (Note that using a converter like this works in jQuery 1.5 forward due to that syntax. Feel free to refactor out the ajaxSetup if you prefer but I find it helps me as I only have to do it once when I have multiple ajax calls.)
$(document).ready(function() {
$.ajaxSetup({
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
error: function(xhr, textStatus, errorThrown) {
var errorMessage = "Ajax error: " + this.url
+ " : " + textStatus + " : " + errorThrown
+ " : " + xhr.statusText + " : " + xhr.status;
alert(errorMessage);
if (xhr.status != "0" || errorThrown != "abort") {
alert(errorMessage);
}
}
});
$("#btnsubmit").click(function() {
var pString = '{"uname":"'
+ $("#TextBox1").val() + '","passwod":"'
+ $("#TextBox2").val() + '"}';
$.ajax({
url: "loginform.aspx/getdataval",
data: pString,
success: function(msg) {
alert("welcome");
AjaxSucceeded(msg);
}
});
});
});
// converter gives us the result instead of the .d here
function AjaxSucceeded(result) {
alert(result);
var Emp = result;
$("#output").append('<p>' + Emp.Sname + ' ' + Emp.Sno + '</p>');
}
EDIT: as of jQuery 1.9, you should bind the ajax setup as such:
$(document).ajaxSetup({..more code

Categories

Resources