I am trying to call c# function from javascript the code i have tried is as below.
C# code
[System.Web.Services.WebMethod]
public void myFun()
{
Response.Redirect("http://google.com");
}
In javascript i have tried following two codes
function CallMe(src, dest) {
//First code i have tried
//var ctrl = document.getElementById(src);
// call server side method
//PageMethods.myFun(CallSuccess, CallFailed, dest);
//Second code i have tried
$.ajax({ type: "POST",
url: myFun, contentType: "application/json; charset=utf-8",
//data: "{passedVal:" + JSON.stringify(clientRequest) + "}", dataType: "json",
success: function (result, status) {
alert("success");
},
error: function (xhr, status, error) {
alert("ERROR");
}
});
}
function CallSuccess(res, destCtrl) {
alert("success");
}
function CallFailed(res, destCtrl) {
alert("fail");
}
but both are not woking.
Can anyone tell me what i am doing wrong?
"myFun" is a function of a WS?
If it is, in the url parameter you need to write the full function url on the WS, and not only it's name.
Hope that will solve the problem.
Related
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);
}
I am using ASP.net MVC, and following is the Html code
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
<div id=waitscreen>
//some code
</div>
Code in external js
function _post(someparameter)
{
$.ajax({
type: "POST",
url: urlAjax,
dataType: 'json',
data: dataValue,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
Also tried adding document ready in above code it is still not working
Above code worked fine and it show and hide as expected, but now I need to repeat ajax call in every page so I decided to move in external JS file now same code is not showing waitscreen.
Things I tried:
Loaded external script in head - Not working
Loaded external script at end of page - Not working
Question: I want to make hide and show work from external JS file
The following code snippet should help you. Tested by including the external JS file in the <head> of the main document and just below the inclusion of jQuery.
// main window
var json = {"key": "value"}
console.log('before calling _post()');
_post(json); // call external JS
// code in external JS say test.js
function _post(someparameter)
{
console.log('external JS called!');
$.ajax({
type: "POST",
url: 'http://www.niketpathak.com',
dataType: 'json',
data: someparameter,
async: true,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
// $("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
//delaying the error callback
setTimeout(function() {
$("#waitscreen").hide();
console.log('after completing the http-request');
}, 500);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=waitscreen>
Waitscreen....
</div>
Also, note that I have used async: true (which is also the default) since setting it to false is deprecated and not a good idea as it blocks the UI.
My ajax code in External.js file,
function _post()
{
var data = {
Email: "a#a.com",
Password:"1111"
}
$.ajax({
type: "POST",
url: "/Home/hello/",
dataType: 'json',
data: data,
async: false,
beforeSend: function () {
$("#waitscreen").show();
},
complete: function () {
$("#waitscreen").hide();
},
success: function (data) {
alert("success")
},
error: function (jqXHR, textStatus, error) {
alert("fail")
}
});
}
In my HomeController, I have hello method like this,
[HttpPost]
public ActionResult hello(LoginViewModel data)
{
ViewBag.Message = "Your contact page.";
return Json(data, JsonRequestBehavior.AllowGet);
}
And in my all the views I have the "waitscreen" div.
Now I just reference the External.js file to my _Layout page, I just drag and drop after jquery reference.
<script src="~/Scripts/External.js"></script>
Then in end of the same _Layout page, i just call the method like this,
<script>
_post();
</script>
Everything working properly.
Note: If you have only one parameter in your hello action method and suppose you have written like (int x) then in that case it will through 500 error. Because in your RouteConfig.js its mentioned that, by default the parameter name should be id. So you need to write int id.
Hope its help.
Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method
Hello everyone and thanks for your time.
Here is my javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
And here is the code in my .ashx handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
While the click event is working, my Ajaxrequest doesn't seem to get any response as the alert at success doesn't popup. I've debugged using the browser's network console and it return the expected response but it doesn't seem to reach the success function in the JavaScript code. Any insights or suggestions are welcome. Thanks.
In case you are still interested in the answer, try this before doing the request
var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);
and change your AJAX request to
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
// do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error");
console.log(textStatus);
console.log(errorThrown);
});
Explanation
You are trying to send the plain data object. You must transform it into a Json string using JSON.stringify(object).
Changing the dataType isn't really a solution but a workaround.
Additional Notes
Also, I think you should use .done() and .fail(). See here for further details.
I'm trying to call a function when I get success from my ajax call, but it's not working. This is what I've tryed so far.
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d) {
console.log(dt);
console.log(msg.d);
buildTableBody(dt, msg.d);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
function buildTableBody(dt, obj) {
dt.fnClearTable();
data = [];
$(obj).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
}
Thanks in advance!
Edit #1
I used console.log in order to show you what I got from dt and msg.d (Image)
Edit #2
If I paste the commands from buildTableBody function in the success: handler instead of calling buildTableBody function in the success: handler it actually works:
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
dt.fnClearTable();
data = [];
$(msg.d).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
But it makes no sense to me, since this actually should work in both ways.
Pretty sure you have a typo on your function call
buildTableBody(td, msg.d);
should be
buildTableBody(dt, msg.d);
Also what is the return type from Index.aspx/getMRPReasonCodeReport? If it is string, you've got to unescape the string before you can treat it as JSON.
Try removing contentType : "application/json utf-8" from your AJAX call. That is the type of the data sent to the server. It is likely that you want the default content type.
Unless your server-side resource was configured to accept json it likely accepts application/x-www-form-urlencoded
http://api.jquery.com/jQuery.ajax/