Jquery generating html codes from C# method - c#

Basically I have a C# web service method that helps to generate HTML code and return it as a string. Now I would like to grab the HTML string from this method and replace a particular div.
function replaceHTML(ID) {
var gID = ID;
$.ajax({
type: "get",
contentType: //what should it be,
url: "the method location",
data: {"ID" : gID },
dataType: //what should it be,
success: function (data) {
$('#Div ID').empty();
$('#Div ID').html(data);
}
});
}
What should be the content Type and data Type? Am I doing it correctly?

Well it all depends on what your web service is providing you and since we cannot see the web service call, we cannot tell you.
In every average web service it should be specified what type of data it communicates with, whether json, xml, or plain text.
Usually though, it will be xml unless something else is specified because web services are SOAP based and are xml formatted, but you should check your web service or share it's code with us.

contentType is the type of data you send to the server, so it'll be application/json in your case. Not nessecary to provide that info though, jQuery will detect it based on the contents of data.
dataType is the type you expect the server to return, so you set it to text/html.
Also, see:
http://api.jquery.com/jquery.ajax/

Hope this will work for you :).
function replaceHTML(ID) {
var gID = ID;
$.ajax({
type: "get",
contentType: 'text',//what should it be,
url: "the method location",
data: JSON.stringify({"ID" : gID }),
dataType: "application/json; charset=utf-8",,
success: function (data) {
$('#Div ID').empty();
$('#Div ID').html(data);
}
}

Related

how to Increase maxjson length for one ajax request

I am making a ajax post call which will pass the viewmodel as a parameter, but now I am getting below error.
Error during serialization or deserialization using the JSON
JavaScriptSerializer. The length of the string exceeds the value set
on the maxJsonLength
I saw the suggestion to increase the length through web.config, but our team said no for that solution, is there any other solution?
this is my ajax post
$.ajax({
url: method, //getSvcUrl(method),
type: "POST",
data: jsonIn, // ko.toJSON(jsonIn),
dataType: "json",
contentType: "application/json",
is there any way to handle it for one particular post method?

ajax post call return 200 but handle error [duplicate]

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

How to view soap service data from my browser

I'm completely new to how soap services work, please correct me if my understanding is wrong. I would like to pass parameters and call a function from a soap service by typing in a url on my browser (Chrome) and then would like to see the results. I tried searching and following the information from here, but I'm not sure what I'm doing wrong. I have tried the following variations:
http://<servername>/apppath/MyService.asmx?op=GetData?loc=01&status=OPEN
http://<servername>/apppath/MyService.asmx/GetData?loc=01&status=OPEN
This is what I get when I go to the url.
http:/<servername>/apppath/MyService.asmx?op=GetData?
Please help.
Maybe you are requesting wrong urls? If you have .asmx in your application - you should be able to see the description page on the url
http://{servername}/{apppath}/MyService.asmx
Of course you should replace {servername} the {apppath} with your values.
You have to send an HTTP POST request in order to call your web service GetData.
Your JS code should be something like:
//url should be MyService.asmx/GetData
function callWS(url) {
var loc = "01";
var status = "OPEN";
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "webmethods.aspx/UpdatePage",
data: JSON.stringify({ loc: loc, status: status }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(response) { alert(response); }
};
$.ajax(options);
}
So the error was my understanding of SOAP and host to use Postman. In short, I wasn't able to accomplish a SOAP request through the browser. Also, the picture supplied, it showed I was missing 2 things. 1) The SoapAction 2) The parameters were not supplied in the url but rather in the <soap:Body> tag. These were supplied in the POST and I was able to view my results in Postman

processing ajax post on the server using c#

I'm trying to do something that's very new to me. I've done some digging but what I've come up with only had solutions by using some kind of .aspx page to process forms.
What I'd like to do is send some form input via ajax (I'm using jquery) to the server to be processed by c#.
This is, I believe, a fairly general question. It doesn't have to do with submitting form input specifically, but more about how to send some data to be processed by c# in the backend.
I want to make an ajax POST to a certain page for processing such as this:
$.ajax({
type: "POST",
url: "****???****",
data: { name: "Bob", gender: "Male" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var names = response.d;
alert(names);
}
});
Now, my question is, what kind of file/page can I use for the url value in the above ajax call, that will be able to handle the POSTed data using c#?
All the examples I've seen use a .aspx page that processes the form and sends it to a .cs code-behind page. If possible, I'd like to be able to use something other than an .aspx page.
The site I'm working on is using just HTML as I'm working with angular. Is there any other way I can handle ajax on the server in a way that I can use c#?
To be very specific, I'm trying to setup a registration page where a user puts in their username and password. I need the password to be sent to the server to have a hash and salt created in C#.
Thanks, and please let me know if you need any additional information to continue.
Try this
In code behind file:Default.aspx.cs
[WebMethod]
public static void GenerateHash(string name,string password)
{
//Write logic to generate hash
}
.aspx page
$.ajax({
type: "POST",
url: "Default.aspx/GenerateHash",
data: { name: "xxx", password: "xxxx" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var names = response.d;
alert(names);
}
});

Jquery Ajax multi user request

I am very new into ajax and i am having a strange problem, I have created an asp.net website that have a web service within the project I am calling this web service by following ajax code:
$.ajax({
type: "POST",
url: pageUrl + "/PassData",
data: JSON.stringify({ aos_code: code }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall
});
the c# code is not very complicated, basically it will get the code and call the stored procedure and return some value:
[WebMethod(EnableSession = true)]
public string[] PassData(string aos_code)
{
// calling the database and returning some data
return data;
}
And it works fine; the problem is that if two different users accessing the application in the two different computers and let say they clicking a button at the same time to call the server side function via Ajax, it will return the “500 internal server error”.
I am not sure how exactly Ajax work, is request are belong to same session or all user requesting a single function?
Hope it makes sense, and I would really do appreciate for the clarification and help.
Regards,
Error 500 indicates that something went wrong on the server side. Check your console (firebug or similar) to see what exactly happened and try to fix it. Ajax has nothing to do with it, it is simply as if two users visited the same page at the same time.

Categories

Resources