I have a modal dialog (done through jquery UI) that submit a form to a remote controller Action.
This is the jquery function called:
$("fpForm").submit(function() {
$.ajax({
type: "POST",
url: "ForgotPassword",
data: $("#fpForm").serialize(),
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
}
});
});
The action does some verification on the data and then send back a response in JSON format. Let's say, for example, that this is a sample response:
{"result":"NOK","message":"The user is not registered on the system"}
My questions are:
Why the debug alert that I have set in the "success" and "error" block does not are get executed?
How I can write my code to parse the response while remaining in wait for it on the dialog?
How can I write code to block the form elements during the ajax call?
I am sorry if the question could seem stupid for most of you but I am completely new to ajax and I am trying to learn throgh some experienced pattern that I know.
Thank you for your responses
The first error is the usage of $("fpForm").submit instead of $("#fpForm").submit.
If the server sand back JSON data, for example as JsonResult, you should include dataType: "json" to convert result to the object in object. After that you can replace alert(response); to
alert('Result: ' + response.result + ', Message: ' + response.message);
To block the form element I'll recommend you to use jQuery BlockUI Plugin. On the demos you will find different examples of usage and find the way which you like.
My questions are:
Why the debug alert that I have set in the "success" and "error" block
does not are get executed?
How I can write my code to parse the response while remaining in wait
for it on the dialog?
How can I write code to block the form elements during the ajax
call?
If you meant to use the id then you missed the # designator:
$("#fpForm")
Add the sync : true option on the call?
You could either: set the disabled attribute on the form elements AFTER posting the request, or else mask the page with an element (possibly semi-transparent) to divert the inputs.
Related
I feel like I am missing something here.
To start, you have an AJAX call you can do in tag to post data to the backend, which looks something like,
function changeDom(){
console.log('connecting');
$.ajax({
url: '/loadOrders',
method:'POST'
}).done(function(data){
if(data.success){
$('#recentOrders').append(data.message);
changeDom2();
return;
}
}).fail(function(){
console.log('failed');
return;
});
};
And on the backend you receive it with code that looks something like,
app.post('/loadOrders', function(req,response)
{ // code here });
I have seen that it is possible to pass a parameter along an AJAX call, which looks like,
$.ajax({
url: '/loadOrders',
method:'POST',
data: {field1: 'this is data being passed'}
}).done(function(data){}});
But how would I receive that data on the backend? How would that change in syntax look and how would I call the parameter?
You can get it by doing
req.body.field1
In Django, I tried using form.errors.as_json() to get all form errors and here is sample json data strings.
{"password2":[{"message": "This password is too short. It must
contain at least 8 characters.","code":"password_too_short"}]}
I wanted to loop and get all under "message" key in json so I can use it to notify the user after ajax call.
Thanks
Anyways, I just resolved my issue and just wanted to share what I did.
views.py
if form.is_valid():
...
else:
# Extract form.errors
errMsg= None
errMsg = [(k, v[0]) for k, v in form.errors.items()]
return JsonResponse(errMsg)
Ajax Event
$.ajax({
method: "POST",
url: '\your_url_here',
data: $form.serialize(),
cache: false,
dataType: "json",
beforeSend: function(){
//Start displaying button's working animation
//Do some button or loading animation here...
}
},
success: function(jResults)
{
//This line is to remove field name display
var strErr = jResults + ''; //make json object as string
strErr = strErr.split(",").pop();
alert(strErr);
}
});
Hope this help to anyone out there facing similar issue. By the way, I'm using Django 2.0 and Python 3.6+
Thanks
MinedBP
The correct answer should be:
return HttpReponse(form.errors.as_json(), status=400).
In the AJAX call you can get the content doing:
`$.post("{% url 'your_url'%}", your_payload).done(function(data) {
do_something();
}).fail(function(xhr){
// Here you can get the form's errors and iterate over them.
xhr.responseText();
});`
You are sending a 200 HTTP response, that it is wrong, you should return a 400 HTTP response (Bad request), like Django do without AJAX forms.
I understand that when I submit a form, according to the documentation ExtJs by default parses the response as JSON.
In my case, the server returns HTML, that I want to display in a Panel. When I submit the from using getForm().submit(), ExtJs will throw an error about invalid JSON:
Ext.JSON.decode(): You're trying to decode an invalid JSON String
How can I tell ExtJs not to attempt to parse the response ? I could the access the text with the response object.
I don't know if you are looking for strictly an ExtJS framework solution. However, it seems you may be able to solve your issue possibly using xmlhttprequest directly since you are looking to push the html returned directly to dom?
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','/myPath/here',false);
xmlhttp.send();
var html = xmlhttp.responseText;
//assign value
In Ext.form.Basic configuration you can define your own reader and errorReader
Finally, it was impossible for me to get to work the form.submit() of ExtJs. I needed an implementation using Ext. And since this is a frequent pattern in my application, it is important to have a short an simple solution.
This is what I finally found (I have a modal window containing the form):
var values = me.up('form').getValues(),
panel = Ext.create('My.view.MyPanel', {
xtype: 'panel',
loader: {
url: Paths.ajax + 'sav_vpc/douane.php',
method: 'get',
params: values,
autoLoad: true
}
});
me.up('window').close()
This solution has another advantage over the me.up('form').getForm().submit() solution:
While .getForm().submit() is asynchronous, .getValues() is synchronous. Therefore, it is possible to close the window immediately.
I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?
That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.
This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).
I have this code, and have also tried something similar using the $.getJson function:
jQuery(document).ready(function(){
var kiva_url = "http://api.kivaws.org/v1/loans/newest.json";
jQuery.ajax({
type: "GET",
url: kiva_url,
data:"format=json",
success: function(data){
alert("here");
jQuery.each(data.loans, function(i, loan){
jQuery("#inner_div").append(loan.name + "<br />");
});
},
dataType: "jsonp",
error: function(){
alert("error");
}
});
});
When I look in Firebug it is returning an "invalid label" error. I've searched around a bit some people refer to using a parser to parse the results. I can see the results coming back in Firebug. Can someone point to an example of what I should be doing?
The Firebug error:
invalid label
http://api.kivaws.org/v1/loans/newest.json?callback=jsonp1249440194660&_=1249440194924&format=json&
Line 1
Sample output of what the json looks like can be found here:
http://build.kiva.org/docs/data/loans
Well I found the answer...it looks like kiva does not support jsonp which is what jquery is doing here -
http://groups.google.com/group/build-kiva/browse_thread/thread/9e9f9d5df821ff8c
...we don't have plans to support JSONP.
Supporting this advocates poor
security practices and there are
already some good ways to access the
data from JavaScript that protect your
application and your users. Here's a
great article on the subject:
http://yuiblog.com/blog/2007/04/10/json-and-browser-security/
While the risk to Kiva lenders is low
now since we are only dealing with
public data, allowing private lender
data to be imported via script tags is
a risk further down the road. Our
thought is the risk (and complexity
added to create secure applications)
is not worth the benefit to
developers.
Writing a server-side proxy for the
feeds you need is the most common
solution to accessing data in
browser-based applications. Some
other tricks exist using iFrames. The
best hope is the new breed of client-
based technologies/standards that will
let browser-based JavaScript access
cross-domain resources securely (
http://dev.w3.org/2006/waf/access-control/
http://json.org/JSONRequest.html ).
Some tools like BrowserPlus and Gears
let you play with these today, but you
won't be able to depend on these in
the wild for a while.
As a final note, I'll point out that
anyone using JSON responses in
JavaScript should either parse JSON
explicitly or validate the JSON before
taking eval() to it. See here:
http://www.JSON.org/js.html
Linked from the page is a great
reference implementation of the
proposed ECMAScript JSON parser
interface, JSON.parse().
Cheers, skylar
maybe this can help with jsonp:
http://remysharp.com/2007/10/08/what-is-jsonp/
When you return the data, are you returning it with the correct content type and as a method?
You should return your data as follows (php 5 example):
$return = "my_callback_method(" . json_encode( array('data'=>'your data etc') ). ")";
while (#ob_end_clean());
header('Cache-Control: no-cache');
header('Content-type: application/json');
print_r($return);
In your calling javascript code, you must have a method to match the callback method you returned, in this case:
function my_callback_method( returned_data ){
}
So, your complete calling js should look something like the following
jQuery(document).ready(function(){
var kiva_url = "http://api.kivaws.org/v1/loans/newest.json";
jQuery.ajax({
type: "GET",
url: kiva_url,
data:"format=json",
dataType: "jsonp",
error: function(xmlhttp,error_msg){
alert("error"+error_msg);
}
});
function my_callback_method( data ){
alert("here");
if( data && typeof(data) == 'object') ){
jQuery.each(data.loans, function(i, loan){
jQuery("#inner_div").append(loan.name + "<br />");
});
}
}
});
Where does the error occur? Does error occur when you try to loop through the ajax data and append it to the inner_div? If yes, please show us what the data.loans look like.
Also, there is a typo in your code:
jQuery.each(data.loans, function(i, loan){
jQuery("#inner_div").append(loan.name + "<br />"); //It should be loan.name and not laon.name
});
},
This is the answer
http://forum.jquery.com/topic/jquery-getjson-invalid-label
Simply wrap your Json response with your callback request
E.g. jQuery16203473509402899789_1315368234762({"Code":200,"Message":"Place added successfully","Content":""});
where
jQuery16203473509402899789_1315368234762 is your callback request (you can get it via querystring)
{"Code":200,"Message":"Place added successfully"} is your JSON response