ajax form submitting but calling error function - javascript

This is a simple form which takes 2 dates from and to and I am submiiting those to values to server.
<form action="#" method="get">
<label for="from">From</label>
<input type="text" id="from" name="fromDate">
<label for="to">to</label>
<input type="text" id="to" name="toDate">
<input type="button" value="Recv Amount" id="recv">
</form>
and the following is the controller code
#RequestMapping("getPayments")
#ResponseBody
public void getPayments(HttpServletRequest request,Model uiModel)
{
String toDate=request.getParameter("toDate");
String fromDate=request.getParameter("fromDate");
System.out.println(fromDate+" "+ toDate);
}
and this is js code
$('#recv').click(function(){
var fromDate=$('#from').val();
var toDate=$('#to').val();
$.ajax({
type: "GET",
url: url,
data:{"fromDate":fromDate,"toDate":toDate},
dataType:"json",
success: function( data ) {
console.log('success');
},
error:function()
{
console.log('failed');
}
});
});
when ever I hit the button I can see todate and from date in the server console (This means System.out.println(fromDate+" "+ toDate); is executed) but in the browser console failed is printed(this means console.log('failed'); is executed)
I do not have any error in browser console but the success function of ajax is never executed.
What could be the reason behind it?
jsfiddle

You are waiting for a JSON answer, but you are not returning anything. jQuery is going to give you an error. Remove 'dataType' from your ajax request or return a valid json object.
From jQuery documentation:
"json": 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. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
jQuery ajax query

EDIT:
Based on the information provided issue is that data is expected the way you formed your success parameter.
Since no data is returned (void method) it won't actually do anything.
Therefore you need to use:
statusCode: { 200: function() { alert( "success" ); } }
Remove success and error as success won't work (no data being returned) and error will display (simply because no data is returned) and replace them with relevant status codes.

Related

How to use Model data inside javascript code?

In my View (asp.net) code, I am simply displaying a bunch of checkboxes. Whenever one of them is clicked, the following java script code is called (which I found in another stackoverflow question):
var RatingClicked = function (rate) {
//some initial work goes here
$.ajax({
url: '#Url.Action("SetRate","Home")',
data: { SelectedRate: rate},
success: function (data) {
//call is successfully completed and we got result in data
},
error: function (xhr, ajaxOptions, thrownError) {
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
So far so good. The code works as expected and my SetRate action method gets called passing the right data (i.e. rate, which is the value of the check box). The problem is that I need to pass some other data in addition to "rate" which are my view's model info. However, as soon as I change the line of code to the following, javascript seems to stop working altogether:
data: { SelectedRate: rate, SomeOtherData:#Model.MyData},
I understand that javascript runs on the client-side vs razor's server side run. But what would be the workaround? How can I call my SetRate action method passing the correct values?
Edit: here is all I have inside my view (aside from a couple of other javascript functions)
#using Impoware.Models
#model HomeViewModel
<input type="checkbox" value="1" id="Rating1" onclick="RatingClicked(1)" onmouseover="MouseOverRating(1)" onmouseout="MouseOutRating(1)" />
<input type="checkbox" value="2" id="Rating2" onclick="RatingClicked(2)" onmouseover="MouseOverRating(2)" onmouseout="MouseOutRating(2)" />
<input type="checkbox" value="3" id="Rating3" onclick="RatingClicked(3)" onmouseover="MouseOverRating(3)" onmouseout="MouseOutRating(3)" />
<input type="checkbox" value="4" id="Rating4" onclick="RatingClicked(4)" onmouseover="MouseOverRating(4)" onmouseout="MouseOutRating(4)" />
<input type="checkbox" value="5" id="Rating5" onclick="RatingClicked(5)" onmouseover="MouseOverRating(5)" onmouseout="MouseOutRating(5)" />
Edit 2: I changed the code as Shyju suggests below and it worked for the primary data types (int, bool, etc.) However, when I tried to pass in my whole data Model, I got the following error:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.UserParticipation_D381F3E084EC9A0B56FA60725061B956AEF865280516092D8BDE683C9A32725B'. Path 'userParticipation.AspNetUser.UserParticipations'.
UserParticipation is a class that has a foreign key connecting to AspNetUser (many to 1 relationship). The model was created using EntityFramework. Why would there be a loop back to UserParticipation? Oh and lastly, I am passing back the whole Model data in order to save some trips to the database again to re-retrieve the same data for the trip back to the same View (if that makes any sense).
You can use JsonConvert.SerializeObject method to get a serialized string version of your C# Model/Model property.
This should work.
var myData = { SelectedRate: rate,
SomeOtherData: #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.MyData)) };
console.log(myData);
//Use myData variable for the ajax call now.
Also, since it is a complex js object, you should stringify this js object and send that in your ajax call. Make sure you are explicitly specifying "application/json" as the contentType so that model binding will not fail. You may also consider doing a HttpPost ajax call as GET use querystring to send data and querystring has limitations on how much data you can send(varies in browsers)
$.ajax({
url: '#Url.Action("SetRate","Home")',
type:'POST',
data: JSON.stringify(myData),
contentType : "application/json",
success: function (data) {
//call is successfully completed and we got result in data
},
error: function (xhr, ajaxOptions, thrownError) {
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
While this answers your question, You should double check why you want to send the entire data back ? May be send a unique Id from which your server method will be able to reconstruct the model/specific data as needed
Did you want something a bit more dynamic like this?
<% foreach( var item in Model.Items ) { %>
<input type="checkbox" value="#item.value" onclick="RatingClicked(#item.value,#item.value2) />
<% } %>
var RatingClicked = function (rate,otherValue) {
......

ajax - getting success response values to text fields

I am trying to get the success response to send the values from ajax into their respective fields. For whatever reason I can't get that to happen. In the success section I am issuing a "alert(responseObject)" in which the results are in the attached image. So the data is coming back just as I want it, but I can't get the values to populate into the matching fields.
$(document).ready(function() {
function myrequest(e) {
var man_part_number = $('#man_part_number').val();
$.ajax({
method: "GET",
url: "includes/autofill.php",
data: {
man_part_number: man_part_number
},
success: function(responseObject) {
alert(responseObject);
//This alert response results is in attached image
$('#manufacture').val(responseObject.manufacture);
$('#model').val(responseObject.model);
$('#type').val(responseObject.type);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
<button type="button" id="fetchFields">Fetch</button>
<input type="text" name="manufacture" id="manufacture" />
<input type="text" name="model" id="model" />
<input type="text" name="type" id="type" />
The string returned is not JSON. Look at the end of your string in the Alert box. It has "test". That means that the response is parsed as text by jQuery, since you don't specify the dataType option. If you did specify it as "JSON", it would fail because having "test" next to "{...}" is invalid JSON. I guess the point is that you need to return valid JSON, and if you are indeed expecting JSON back, set the dataType option for the $.ajax call to be "JSON". At the same time, your server should be setting the proper header in the response anyways. It's still better (sometimes) to specify the dataType option.
By default, if you don't specify the dataType option, jQuery will check the headers of the response to get the Content-Type. If it matches a valid type for "JSON", "HTML", "Text", "XML", or a few others, it will attempt to parse it by that. I'm betting your response doesn't have its headers set properly, otherwise jQuery would've attempted to convert it to JSON and failed. It's probably being returned as plain text, so jQuery sees that and parses it as text...which is why it parses fine. But the responseObject you're referencing is not an Object as you expect, because you don't follow these procedures to ensure proper parsing.

Ajaxform getting the data before the submit is called

I am working with AjaxForm plugin
I want to alert the data what is being pushed to server.
<form class='frmAppList'>
<input type='hidden' name='deviceid' value='<deviceId>'>
<input type='hidden' name='operationtype' value='<Coming from server>'>
<input type='hidden' name='type' value='command'>
<button type="submit" class='btnAppsList button'>
APPS LIST
</button>
</form>
This is in loop in jsp so the form is generated more than once having class -> frmAppList.
I am using the class to apply ajaxform like this:
$('.frmAppList').ajaxForm({
url : 'urltoserver',
dataType : 'json',
type : 'post',
beforeSubmit : function() {
return false;
//something here that gives me the device id that is passed
//since the form is not one I cant use id, also every form has **deviceid**
//i need to get that deviceid so that i can pass it in **success** ajax call
//at ***Label->(A)***
},
success : function(response) {
if (response.status) {
//***Label*** ->(A)
//have to call other ajax call to take the data
//for that i need the device id that is going in this ajax call
}
},
error : function(xhr, ajaxOptions, thrownError) {
alert('error');
},
timeout :10000
});
How can I get that device Id,plz help me....
Thanks a ton.....
From ajaxForm doc :
success
Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following arguments:
1.) responseText or responseXML value (depending on the value of the dataType option).
2.) statusText
3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
Default value: null
The third and fourth argument are what you're looking for. Start there:
success : function(response,status,request,form) {
console.log(request,form);
}

Jquery getJson not calling callback

I have the following javascript code:
$.get("categories/json_get_cities/" + stateId, function(result)
{
//code here
}, 'json'
);
And the PHP code which processes it basically outputs something like this:
function json_get_cities($stateId)
{
//code here
echo json_encode(array('cities'=>$cities));
}
In the firebug console I can see that the ajax request is being made as expected, a 200 OK response is received, and a proper-seeming JSON object containing the cities is returned. However for some reason, the callback function I'm passing on to jquery is not being called.
Even putting a debugger call in at the top of the function, i.e
$.get("categories/json_get_cities/" + stateId, function(result)
{
debugger;
//code here
}, 'json'
);
doesn't work. However if I remove the 3rd argument of 'json' the function is then called (but the response text is treated as plain text instead of being a JSON object).
Here's the JSON response returned by the server:
{"cities":[{"id":"1613","stateId":"5","name":"Acton"}]}
Any thoughts?
Did you confirm that this is valid JSON? In jQuery 1.4 the JSON parsing is done in a strict manner, any malformed JSON is rejected and a parsererror is thrown.
Try console.log(arguments) in the callback to debug.
Also, you state that 'json' is the fourth argument, but it should be the third (as in your example).
Make sure the json is valid using this...
JSON Validator
Another way to debug some of these ajax problems is to use the .ajax method, passing GET as the method type, rather than the .get method. This will allow you to specify an error callback function in addition to a success method.
Remember, JSON field names must be surrounded with quotes like the values when writing json in files for jquery to load. Ex:
In code:
{
name: "value"
}
In JSON file:
{
"name": "value"
}

getJSON fails, JSON validates

I have a getJSON call which is inexplicably failing. The idea is, you click to submit a comment, a URL gets hit which determines if the comment is OK or has naughty words in it. The response is given in JSON form.
Here's the paired down JS that generates the call. The comment and the URL are already on the page, it grabs them and hits the URL:
FORM HTML:
<fieldset id="mg_comment_fieldset" class="inlineLabels">
<div class="ctrlHolder">
<textarea id="id_comment" rows="10" cols="40" name="comment"></textarea>
</div>
<div class="form_block">
<input type="hidden" name="next" value="" />
<input id="mg_comment_url" type="hidden" name="comment_url" value="" />
<input id="mg_comment_submit" type="submit" value="Remark" />
</div>
</fieldset>
SPECIFIC JS BLOCK THAT SENDS/READS RESPONSE:
$('input#mg_comment_submit').click(function(){
var comment = $("textarea#id_comment").val();
var comment_url = $('input#mg_comment_url').val();
$.getJSON(
comment_url+"?callback=?&comment="+comment+"&next=",
function(data){
console.log(data);
alert(data);
});
});
The JSON response:
[{"errors": {"comment": ["Weve detected that your submission contains words which violate our Terms and Conditions. Please remove them and resubmit test"]}}]
It's being returned as a mimetype of application/json. It validates in JSONLint. I also tried adding a couple AJAX functions to try to catch errors, and they're both silent. I can see the request going out in Firebug, and coming back as status 200 responses, which validate in JSONLint and which I can traverse just fine in the JSON tab of the response. If I put an alert before the getJSON, it runs; it's just that nothing inside of it runs. I also find that if I change .getJSON to .get, the alerts do run, suggesting it's something with the JSON. I'm out of ideas as to what the problem could be. Using Firefox 3.0.13.
The querystring parameter "callback=?" comes into play if you are using cross-site scripting or jsonp, if you are posting the same server, you don't need to use that.
If you need or want to use that option, the server side code needs to come back with the callback function included in the json response.
Example:
$jsonData = getDataAsJson($_GET['symbol']);
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
So either make a server side change if necessary or simple remove the "callback=?" parameter from the url.
Here's more info on jsonp
Are you able to manually call your service without any errors? Have you tried using firebug and looked under XBR to see the post/response of the JSON payloads? I normally use .NET as my endpoints, and with .NET 3.5 I need to use content type "application/json; charset=utf-8".
Here is an example of a working JSON call I use in .NET with jQuery 1.3.2
$.ajax({
type: "POST",
url: "WebService1.ASMX/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function(res) {
// Do your work here.
// Remember, the results for a ASMX Web Service are wrapped
// within the object "d" by default. e.g. {"d" : "Hello World"}
}
});
Have you tried it with $.ajax? You can then define both error and success callbacks and have better idea.
Can you try adding a global ajaxError function to log the error.
$.ajaxError( function(event, XMLHttpRequest, ajaxOptions, thrownError){
console.log( thrownError );
});

Categories

Resources