var req = $.ajax({
type: 'GET',
cache: false,
url: 'loc.aspx?count=' + str,
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
data:'{}',
success: function (data) {
alert(data.responseText);
}
});
req.fail(function (data) {
TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
});
the above code used to work right in jsp, now i am trying to use in asp.net c#, any way I am getting correct data in error block which i want it in success block. Even data.d is not helping,
If i write something like alert(data) i am getting the complete html, I need just the response text, When i use like this data.responseText, I am getting undefined. Someone help pls.
Thanks
Code below should work fine. I've added some comments where you are doing a mistake
var req = $.ajax({
type: 'GET',
cache: false,
url: 'loc.aspx?count=' + str,
dataType: 'html',// as you return a simple html dataType:json will throw an error as jquery will not be able to parse received string
contentType: "application/json; charset=utf-8",
async: false,
data:'{}',
success: function (data) {
alert(data);// data is not an XHR object. it is a processed response. In your case - simple string with HTML which, of course, has no method responseText
}
});
req.fail(function (data) {
TINY.box.show({ html: 'Server Error. Try again: ' + data.responseText, animate: false, close: false, boxid: 'error', top: 100 });
});
In .fail function you have data.responseText because in this case XHR object is passed as a first parameter (See this). At the same time, first parameter of success callback is a clean data received with request. If without details, you can think that data == xhr.responseText in success callback. See success property description in this section
upd
As appeared, problem is not only with JS. I guess you have a simple .aspx page which is called with ajax. There are two solutions:
1) Use webservice instead. It will be better because it does not go through complete page load cycle and should be executed faster. And it will not produce unused HTML
2) aspx page will output some HTML by default. Before you return a response for ajax request, you should clear response (so HTML which is already generated will not be sent to a server), write your response and immediately end it:
Response.Clear();
Response.Write("hello");
Response.End();
This way you should receive only hello in success.
Related
I want to be able to drag and drop files into multiple folders on a server, I am using jquery to pass to HttpHandler but I can't pass the save location to webhandler. I would like to send the path from jquery in the request is there a way to incluse that when the data for file transfer is passed.
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading files!");
}
});
Maybe something like this:
$.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType: false,
processData: false,
data: data,
filepath: document.getElementById("<%=listDrop.ClientID%>");
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading files!");
}
});
and then retrieve the path in the webhandler to pass as save location?
I have tried this $.ajax({
type: "POST",
url: "FileHandler.ashx",
contentType:false,
processData: false,
data: {
data: newData,
filepath:JSON.stringify("~/uploads/")
},
success: function (result) {
alert('success');
},
error: function () {
alert("There was error uploading files!");
}
}); But I have question about the declaration of the data type for the files I will be uploading when creating the get and set in asp. filepath is a string but what data type are the files.
although i am answering from my mobile, i tried my best to keep the things intact and use ful. If required, Please format it accordingly.
I am not going to write entire code here, just algo.
1. Identify the parameter to be passed. If its only path of multiple folders then you can create an array of objects in javascript for the same. See tge example
var listOfFolder = new string[];
listOfFolder[0]="path of first dir";
:
:
listOfFolder[n]="path of nth dir";
var data = JSON.stringify(listOfFolder);
2. pass this data in data attribute of jquery ajax. 3. Grab this path in Process Request event and deserialize.
4. Do whatever you want.
I make a total of four Ajax calls in my .NET application. Three of them work without a hitch except the last one.
Note: I HAVE to use .aspx for these calls and not mypage.aspx/mymethod because of our architectural constraints.
Ajax call that works:
$.ajax({
type: "POST",
url: "myaddress/GenerateOpinionHTML.aspx",
data: JSON.stringify({ id: featureId, pageNumber: pageNumberIndex }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
SOME PROCESSING (IT WORKS)
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log(err);
}
});
and
[WebMethod]
public static string GenerateOpinionHTML(int id, int pageNumber)
{
// ...
}
Ajax call that does not work:
console.log("SUBMITOPINIONCLICK");
var param = " ";
$.ajax({
type: "POST",
url: "myaddress/SaveOpinion.aspx",
data: JSON.stringify({ parameter: param}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SAVE OPINION SUCCESSFUL");
console.log(msg.d);
CloseLB('GiveOpinionLB');
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log("ERROR " + "STATUS: " + status);
}
});
and
[WebMethod]
public static string SaveOpinion(string parameter)
{
// ...
}
The web method SaveOpinion is never called according to the logs. Do you have any ideas or suggestions? I tried adding parameters, without parameters, checking my web.config file (though I shouldn't have since the other calls work)...
The error I get on the browser console is a "parseerror". I'm certain I wouldn't be getting an error if the method was called.
I think your URL should be like
url: "Your FolderName/PageName/Function Name",
Like
url: "myaddress/SaveOpinion.aspx/SaveOpinion"
but in your code this is different so that please check.
Have you checked if method SaveOption return something to the client?
If you specify dataType as json, you should return (at least): {}
Ok so we "solved" it. We just found a very dirty band-aid workaround that works.
We made a custom handler (.ashx) that we defined in our architecture as a SaveOpinion.aspx page.
We then called this custom handler page with jQuery and voilĂ it works, we had to obviously pass all necessary parameters manually, ie. fetching all values from textBoxes etc with jQuery and not from the context as we did before.
Since this is run in some sort of thread (I don't really know the details) we had to configure it so that it simulates the same user authentification.
Anyway I hope this provides some measure of guidance for those with this kind of obscure problems.
In PHP, I can call a page like this
var data = {
type: 'simple_data'
};
jQuery.ajax({
url: 'http://www.example.com/haha.php', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
And in the PHP server side page, we catch it like
$type=$_POST['type'];
Pretty simple right! It gives back the XML info and GOAL.
Now I want to do it for ASP.NET pages in same way as PHP. I want to call the ASP.NET page like
var data = {
type: 'simple_data'
};
jQuery.ajax({
url: 'http://www.example.com/haha.aspx', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
So how can I catch the data and extract values in ASP.NET. That means I want the functionality similar to this '$_POST['type']' in ASP.NET. I tried to search but nothing found yet or may be didn't find in the right direction. Can anyone please tell me how can I extract this data from this ajax call with XML??
You can use Request.Form["type"]
It is very easy. You need to pass the method name in your URL parameter like so:
jQuery.ajax({
url: 'http://www.example.com/haha.aspx/MethodName', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
ASP.Net will know how to handle the web request and parse the data. You can write something on the .aspx page as simple as:
[WebMethod]
public static string MethodName(string type)
{
// do work with type
}
I am using JQuery to make a AJAX to a local service. My local service is a HttpHandler (e.g., Request.ashx). Within Request.ashx, it's responsiblity is to make a call to an external website (e.g., CallExternalWebsite()). CallExternalWebsite() uses .NET's System.Net.WebRequest() to initiate a request. When the external website is accessed, neither the success or error events are fired. (NOTE: I have also tried this a WCF service hosted in IIS. I am seeing the same results)
Here are two scenarios:
This scenario works:
In ProcessRequest(), comment out callExternalWebsite().
For object o, intialize with data to simulate results.
Click on myButton
The success event fires on the client.
In Fiddler, I can see the header info. I see Json result, etc.
This scenario does not work:
In ProcessRequest(), enable the call for callExternalWebsite().
For object o, callExternalWebsite() will return an appropriate object.
Click on myButton
The success event does not fires on the client.
In Fiddler, I can see the header info. I see Json result, etc.
I know the callExternalWebsite() is working because I have it sending results to my phone.
To sum it up, the external http call within the HttpHandler is effecting the Ajax success event.
Here is a snippet from AJAX call:
(I was trying different interations)
$(document).ready(function () {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
In the HttpHandler Request.ashx,
public Void ProcessRequest(httpContent context)
{
// Do some stuff....
// Make call to external web site
object o = callExternalWebsite (Uri, Data, "POST");
// Return results from callOtherWebsite
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(o);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
Any thoughts?
Thanks.
Steve
What happens if you do this, msg vs msg.d:
$(document).ready(function () {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg.d);
},
error: AjaxFailed
});
});
});
i use first time ajax call from asax page.
it is working fine i am getting data in C# page and but when trying get success function than i am getting error msg in error function
"SyntaxError: JSON.parse: unexpected character"
here is my code
var options = {
type: "POST",
url: "ChemistrieAddToCart.aspx",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function () {
alert("sucsess");
},
error: function (xhr, status, error) {
alert("failed" + xhr.responseText);
alert(error);
alert(status);
}
};
var returntext = $.ajax(options).responseText;
if (returntext = "added") {
alert("Matched");
window.location="shoppingcart.aspx"
}
else {
alert("not completed");
}
Thanks.
if you are passing <img src="1-800-optisource.com/Email/image/jsonstring.jpg"; width="497" height="394"/> as Json string that its is wrong you might look at json format first than pass the value might give you idea and resolve your issue
check json over here : http://www.json.org/