Ajax Call not returning Partial View - javascript

I am making an AJAX call, and then returning PartialView from Controller to populate it in a div.
The following is my code :-
var file = document.getElementById("file").files[0];
jq.ajax({
type: "POST",
url: '/Main/getData',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
jq('#partialPlaceHolder').html(response);
},
error: function (error) {
alert("Some Error Occured");
}
});
[HttpPost]
public ActionResult getData(FormCollection form)
{
......
return PartialView("_pageMain", retMod);
}
As I debug the Code in Controller, there is no Error till the end, But still the AJAX throws the alert("Some Error Occured").
The PartialView is not populated in div. How to solve this?

You are setting the return data type to json
dataType: 'json'
try changing this to
dataType: 'html'
See here http://api.jquery.com/jquery.ajax/
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.

Why not to use .load() JQuery .load()?
Description: Load data from the server and place the returned HTML into the matched element.
And simple:
$('#partialPlaceHolder').load("#Url.Action('getData')", { form: formData })
Third parameter for .load() is callback function, so feels free with it.
BTW: I did not find using variable file in your code.

Related

Javascript send data to ActionResult that return RedirectToAction

I need to send data from javascript to my action that return RedirectToAction and some data.
My Js:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "GetAssetFilterID",
data: JSON.stringify({ 'VidLink' : clipData.src, 'InitialTime': clipData.markIn, 'EndTime': clipData.markOut }),
dataType: "json",
/*async: false,*/
});
My Action:
[HttpPost]
public ActionResult GetAssetFilterID(string VidLink, string InitialTime, string EndTime)
{
//some code
return RedirectToAction("Share", new { vid = VidLink, fil = filterName });
}
Notes
I had, on js, the url controller/action and the link that it
generated was controller/controller/action.
I don' get any error on console, nothing happens.
I don't need to use Ajax, I just want to send data from my Js to my
ActionResult. Ajax was the sample that I found.
Thanks in advance
You cannot do that. All you can do is return a url in the ajax result and use JS to redirect. Return the url in json or similar and in the ajax success or complete callbacks do your redirect.
Because the browser never posted its not expecting a response that would allow/cause a redirect.
Also duplicate of asp.net mvc4 ajax login: RedirectToAction not working

Call c# code behind from jquery with parameters [duplicate]

This question already has answers here:
C# Web method is not calling in javascript
(3 answers)
Closed 7 years ago.
Ajax Code
$.ajax({
type: "POST",
url: "LiveFeed.aspx/SearchStateList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#Content").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
Code Behind
[WebMethod]
public static string SearchStateList()
{
}
The above code works fine and the code behind is called
But when I send some parameter as given below, code behind is not invoked and when I see the Firebug console errors, it throws
NetworkError: 500 Internal Server Error -
http://localhost:61276/App/LiveFeed/LiveFeed.aspx/SearchStateList
Ajax Code
$.ajax({
type: "POST",
url: "LiveFeed.aspx/SearchStateList",
contentType: "application/json; charset=utf-8",
data:{value:"samplevalue"},
dataType: "json",
success: function (response) {
$("#Content").text(response.d);
},
failure: function (response) {
alert(response.d);
}
});
Code Behind
[WebMethod]
public static string SearchStateList(string value)
{
}
I also tried to change modify the data of ajax call as
var param={value:"samplevalue"}
data:JSON.stringify(param),
and also tried directly with out JSON.stringify
data:param,
Every time when I tried to pass a parameter it did not invoke code behind and 500 error is thrown.
Why don't you try
var param={"value":"samplevalue"}
data:JSON.stringify(param),
I think data content goes with quotes:
data: '{value:"samplevalue"}',
You can access variables sent in the data by accessing the Request Collection.
Request.Form["your_var_name"] // use this when you $.post
Request["your_var_name"] // use this when you $.get
So your code behind can look like this:
public static string SearchStateList(string value)
{
Response.Write("The value of value is: " + Request.Form["value"]);
}
In your Ajax post, you have set the data property as :-
data:{value:"samplevalue"}
Subtle change, to this below would work :-
data:{ "value" :"samplevalue"}

Grails GSP Ajax Call OnSuccess not called

I am performing an ajax call from a .gsp file in grails:
$.ajax({
async: false,
url: '<g:createLink controller="mycontroller" action="myaction"/>',
data: params,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
onSuccess: 'toggleSaveButton(false);'
});
mycontroller
def myaction() {
// do some funky stuff with params
// params are available, everything here works without a problem
}
outcome
the ajax call is performed and the controller function is called correctly with all attached data.
issue
my onSuccess: is ignored and never called
i already tried
using the more generic onComplete
change the onSuccess: to function(){toggleSaveButton(false);}
render (true as JSON) in my controller action
I believe it should be success: instead of onSuccess:, according to JQuery ajax docs.
To demonstrate:
http://jsfiddle.net/bL60Lta9/2/
Rewriting to :
onComplete: dataUpdatedOnSuccess()
did the trick.

What happens when wrong dataType is returned

I perform a call
$.ajax({
type: "POST",
url: url,
data: dataToPost,
dataType: "json",
success: function(data, textStatus){ /*something*/ },
failure: myHttpReqErrorHandler
});
In certain cases when things goes wrong on the server I get
Content-type:text/html; charset=UTF-8
type, and content is a real HTML page, and there is not much I can do about that. I want to manage this case on JavaScript, but when this happens no callback is called on jQuery side (neither success nor failure).
Is there a further parameter to pass to ajax to handle that?
The error handler is error: function(){}
error: myHttpReqErrorHandler
It will throw a parse error(parsererror) if the content is not a parsable json format.
Demo: Fiddle

Ajax request returns 200 OK, but an error event is fired instead of success

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");
}

Categories

Resources