Jquery to ashx not working event not fired - c#

I am using the below code to call a ashx page. But it's not working for me. I have place my code here. I always got the error message message "Request Failed". Please help me..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>

remove these lines:
$(function(){ // <----remove this
return false; // and this
}); // and this too
Update to this function:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
and also your url is not correct:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
and since your type: "post" so you can pass the data like this:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},

Separate your string into a javascript object to be encoded and sent to the server as JSON based on your content type. Also, get rid of $(function(){ in your function call, it's useless here.
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
If this doesn't work, then the issue is likely one of the following:
The URL address is wrong
The server is evaluating a GET as opposed to a POST request
The server expects, application/x-www-form-urlencoded but you've declared it's json
You have a routing issue

Note: Do not send your user and pass in query string.
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// 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: OnComplete,
error: OnFail
});
});
}
Your handler.ashx file
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
source

Related

Trying to redirect from AJAX post

I am trying to call a webmethod from AJAX which is redirecting to a url like this:
HttpContext.Current.Response.Redirect(StoreCode.ToLower() + "/App/home.html?EventClick=True", false);
AJAX call:
function TokenPost() {
var token = $('#hdnToken').val();
$.ajax({
url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
type: 'POST',
data: "{data:'" + token + "'}",
contentType: 'application/json; charset=UTF-8',
datatype: 'JSON',
success: function(response) {
},
error: function(response) {
alert(response.d);
}
});
}
But my AJAX call is not redirecting to that url.Thanks in advance.
I think it' s not possible in HttpPost Methods. But you can return link in your HttpPost method from server. And redirect with Javascript Code if ajax returns success.
$.ajax({
url: 'http://localhost/QDC/WebServices.asmx/ChkToken',
type: 'POST',
data: "{data:'" + token + "'}",
contentType: 'application/json; charset=UTF-8',
datatype: 'JSON',
success: function (link) {
window.location.href = link;
},
error: function (link) {
alert(response.d);
}
});
In Server Method (I am using this in ASP.NET MVC):
string link = "https://...Your Link";
return Json(link, JsonRequestBehavior.AllowGet);
If you are using WebMethod, I think you can return just string, too.
[System.Web.Services.WebMethod]
public static string ChkToken(string data)
{
string link = "...";
// Do things
return link;
}
This time ajax return can be like this,
success: function (link) {
window.location.href = link.d;
},

Ajax function failing to hit method on code behind on server

I have the following ajax function
var jsonId = JSON.stringify(sortedIDs);
$.ajax({
type: "POST",
data: { ids: jsonId },
datatype: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
And the following method in the code behind page
[WebMethod]
public static string GetData(string[] data)
{
return "this is the string from the code behind file";
}
The error I am getting is a 500 internal server error. If I add .cs to the TestSortTable.aspx I get a 404 not found error. This is the first time I have implemented an Ajax function and I am at a loss as to what I have done wrong. I should add that sortedIDs is defined elsewhere.
You're not sending the parameters as JSON. You're converting sortedIDs to JSON, but being wrapped into an object that gets sent as URL-encoded data. You need to do:
var json = JSON.stringify({data: sortedIDs);
$.ajax({
type: "POST",
data: json,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Intranet/Dev/TestSortTable.aspx/GetData",
success: function (msg) {
alert(msg.d + "success");
},
error: function (response) {
alert("an error has occured");
}
});
Also, datatype: should be dataType:

Passing json object to webmethod via jquery ajax

I am trying to pass a json object to my .net webmethod.
Here is my C#:
[WebMethod]
public static string Guncelle(string personel)
{
return "It came.";
}
And my jquery ajax:
var saveData = {};
saveData.Isim = isim;
saveData.Soyad = soyisim;
saveData.Firma = firma;
.
.
.
var result = JSON.stringify({ personel: saveData });
$.ajax({
type: "POST",
url: "Personeller.aspx/Guncelle",
data: result,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
})
When I run code, it returns 'undefined' with alert. What is the correct way of passing json object to C# Webmethod ? I tried other examples for passing an object but none of them worked for me.
try this: data: "{personel:'" + saveData+ "'}"

.JQuery .ajax how do I call WCF method with return value?

I have been able to call WCF methods with .ajax. How do I call a method that returns a value? I need to call this method to see if data is ready and if not wait one second. The WCF method is:
[OperationContract]
[WebGet]
public bool IsDataReady(string requestGUID)
{
if (Global.publicDataDictionary.Keys.Contains(requestGUID))
return true;
else return false;
}
My JavaScript so far is:
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
}
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service never passes a requestGUID. Can't i use the same input variable?
var guid = "<%= this.guid%>";
// var input = '{"SbiId":"' + guid + '"}';
// var input = {requestGUID:"ca222cf7-be5e-431a-ab93-9a31e8ae2f4a"};
function callUpdateGrid(input) {
console.log(input);
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
var mtv = $find("<%= RadGrid1.ClientID %>").get_masterTableView();
console.log(data);
mtv.set_dataSource(data.d.Data);
mtv.dataBind();
}
});
}
function CallIsDataReady(input) {
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
else {
//Continue as data is ready
callUpdateGrid(input);
}
}
});
}
$(document).ready(function () {
var input = { requestGUID: "<%=guid %>" };
CallIsDataReady(input);
});
EDIT2: I broke out the 2nd ajax call into a method but my logging is showing that the call to 2nd web service is never getting called:
url: "http://www.blah.com/services/TestsService.svc/GetContactsDataAndCountbyGUID",
else {
//Continue as data is ready
callUpdateGrid(input);
}
The return value will be contained in the data parameter passed to the success callback setup in your ajax call.
You will need to check the value here, then if false, setup a timeout, which on expiry will attempt the ajax call again.
It would be best IMO to wrap up the Ajax call inside a function, that you can call in a recursive fashion when the timeout has expired. e.g.
function CallIsDataReady(input){
$.ajax({
url: "http://www.blah.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
dataType: "json",
success: function(data) {
if (!data){
setTimeout(function(){CallIsDataReady(input);}, 1000);
}
else{
//Continue as data is ready
}
}
});
}
$(document).ready(function() {
var input = {requestGUID:"<%=guid %>"};
console.log(input);
CallIsDataReady(input);
});
When you view source on this page is:
var input = {requestGUID:"<%=guid %>"};
showing correctly in the javascript? If you put a breakpoint in your IsDataReady method, do you see if requestGUID has a value? Is your service on the same domain as the page calling it?
EDIT:
In your service change: [WebGet]
to:
[WebGet(
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json]
Read up on RESTful web services:
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide

Pass html string to server side with Jquery Ajax

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.
i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}
--For Jquery:
$("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
and Server-Side ASP.NET:
[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
Jquery part gives me an error:
Invalid object passed in and error in
System.Web.Script.Serialization.JavascriptObjectDeserializer.
It's like jquery doesnt accept string with html content.what is wrong with my code ?
Pass it like this
JSON.stringify({'num':HTML});
You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.
var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
You can use this
var HTML = escape($("#t").val());
and on server end you can decode it to get the html string as
HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.
[HttpPost]
public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring)
{
retrun view();
}
$.ajax({
url: '/Controller/ActionMethod',
type: "POST",
data: JSON.stringify({
para1: titletext,
para2: datetext,
para3: interchangeNbr.toString(),
htmlstring : messageText.toString()
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function successFunc(data) {
},
error: function errorFunc(jqXHR) {
$('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show();
}
});

Categories