Ajax & Grails - how to use the params from the model in the success of the Ajax? - ajax

I have an Ajax which call to an action in a controler.
The controller render:
render template:"changePassword", model:[user: user, passwordError: passwordError]
The passwordError is boolean.
In case the passwordError is true I have to perform function in the js.file.
How can I check in the success's Ajax the value of the passwordError?
The code of the Ajax:
$.ajax({
url: changePassword,
type: "post",
data: {
password: $('#password').val(), npassword: $('#npassword').val()
},
success: function(data,textStatus){
$('#changePassSuceess').modal()
}
});

If you dont need to render a template, you can return a json as #Eylen mentioned and then access the flag from json. If you must render a template then you can have a hidden field in your template with value set to the flag passwordError and then you can get the value of flag from this hidden field in your javascript code
See this question for how to find hidden element in jquery ajax response html

If you don't need to show the template that you are returning, then you can change your return from the controller to something like the following
return [passwordChanged:true] as JSON
Ans then in your ajax call you will have access to the JSON object in the data attribute.
console.log(data.passwordChanged);
Maybe you have to tell also in the ajax call that the return type is json.

Related

Ajax query string param are being added to standard get request

I have an ajax code with parameter like this
var data = {
attr1: 'attr1',
attr2: 'attr2',
}
jQuery.ajax({
type: 'GET',
url: '/report/preview.html',
data: data,
dataType: 'html',
success: function(result){
jQuery('#report-body').html(result);
},
error: function(xhr,a, b){
console.error(xhr.responseText);
}
});
The function generates url - /report/preview.html?attr1=attr1&attr2=attr2.
I have a display table in jsp which does a full reload every page navigation. My problem is that it also append the parameter i set in ajax call to the url in browser.
The url of display table action is /report/reportHome.html. after the ajax call, when i navigate to another table page, the url becomes /report/reportHome.html?attr1=attr1&attr2=attr2. It appended the ajax param to its parameter. How can i remove these parameters? thanks.
Use a form and POST the information.
Use Path variable Ex: /report/attr1/attr2/preview.html
Use Session
Use some encode/decode
I have resolved my problem! The problem happens because the 'requestURI' attribute of the generated display table of the ajax call adds any tag generated parameters to its value. That is why the request param in the ajax call are being appended automatically as query string in the 'requestURI' attribute of the generated table.
I have resolved this by adding the ajax parameters in the 'excludedParams' attribute of the generated table so they won't be added as query string
So it does not matter what type of request the ajax uses(get or post).

Refresh form in Django without reloading page

Hi I'm new in Ajax and django and I want to refresh my form. I try some code but it didn't work. I'm sure what I want to do is very basic.
Here my html:
<div class="row" style="padding-top:20px;">
<div class="col-md-12" id="testAjax">
{% load crispy_forms_tags %}
{% crispy form %}
</div>
</div>
I want to refresh my form in the div testAjax.
Here my view:
def createPin(request):
error = False
if request.method == "POST":
form = CreatePinForm(request.POST)
if form.is_valid():
pin = form.save(commit=False)
pin.customer = request.user.customer
pin.save()
msg = "pin saved"
return redirect('/pin/CreatePin', {'form': form, 'msg': msg})
else:
error = True
else:
form = CreatePinForm()
return render(request, 'createPin.html', {'form': form, 'error': error,})
My Ajax:
function refresh()
{
$form=$('#createPin');
var datastring = $form.serialize();
$.ajax({
type: "POST",
url: '/pin/CreatePin/',
dataType: 'html',
data: datastring,
success: function(result)
{
/* The div contains now the updated form */
$('#testAjax').html(result);
}
});
}
Thanks alot for your help.
When I need to do some operations and I don't want to reload the page I use a JQuery call to Ajax, I make the pertinent operations in AJAX and then receive the AJAX response in the JQuery function without leaving or reloading the page. I'll make an easy example here for you to understand the basics of this:
JQuery function, placed in the template you need
function form_post(){
//You have to get in this code the values you need to work with, for example:
var datastring = $form.serialize();
$.ajax({ //Call ajax function sending the option loaded
url: "/ajax_url/", //This is the url of the ajax view where you make the search
type: 'POST',
data: datastring,
success: function(response) {
result = JSON.parse(response); // Get the results sended from ajax to here
if (result.error) { // If the function fails
// Error
alert(result.error_text);
} else { // Success
//Here do whatever you need with the result;
}
}
}
});
}
You have to realize that I cannot finish the code without knowing what kind of results you're getting or how do you want to display them, so you need to retouch this code on your needs.
AJAX function called by JQuery
Remember you need to add an url for this Ajax function in your urls.py something like:
url(r'^/ajax_url/?$', 'your_project.ajax.ajax_view', name='ajax_view'),
Then your AJAX function, it's like a normal Django View, but add this function into ajax.py from django.core.context_processors import csrf from django.views.decorators.csrf import csrf_exempt from django.utils import simplejson
#csrf_exempt
def ajax_view(request):
response = []
#Here you have to enter code here
#to receive the data (datastring) you send here by POST
#Do the operations you need with the form information
#Add the data you need to send back to a list/dictionary like response
#And return it to the JQuery function `enter code here`(simplejson.dumps is to convert to JSON)
return HttpResponse(simplejson.dumps(response))
So, without leaving the page you receive via javascript a list of items that you sended from ajax view.
So you can update the form, or any tag you need using JQuery
I know that this can be so confusing at the beginning but once you are used to AJAX this kind of operations without leaving or reloading the page are easy to do.
The basics for understanding is something like:
JQuery function called on click or any event you need
JQuery get some values on the template and send them to AJAX via
POST
Receive that information in AJAX via POST
Do whatever you need in AJAX like a normal DJango view
Convert your result to JSON and send back to the JQuery function
JQuery function receive the results from AJAX and you can do
whatever you need

What else can I pass to the `form` property of Ext.Ajax.request?

Normally one posts an ExtJS form to the backend using form.submit({...}). I want to make my form submission synchronous now, so I'm switching to using Ext.Ajax.request({async: false, ...}). The form property of Ext.Ajax.request() usually looks like so:
Ext.Ajax.request({
url: 'formsubmit',
form: 'formid',
method:'POST',
success: function(response, opts) {
alert("successfull");
},
failure:function(res,opt) {
alert("request failed");
}
});
I'm dealing with a bunch of anonymous forms right now. Is there any way around this?
Given a var form = {xtype: 'form', items: [...]}
I've tried replacing 'formid' with form.getEl(), form.getForm(), and form.getForm().getFieldValues() which all don't work.
There's no other way around this other than assigning a generated id to each of my anonymous forms, is there.
Thanks for any input
It looks like you could just do this as an alternative to the form attribute:
var form = this.down('form');
Ext.Ajax.request({
url: 'test.xyz',
params: form.getValues()
// etc...
});
getValues gives you the name/value pairs you need for your submission.
It looks like the ExtJS forms do not actually use form elements in the markup. When the submit function is called on an ExtJS form, an HTML form element is crafted as part of the process, and that's the form that is used for the submission.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.action.Submit-method-buildForm
Ideally, you could modify the options that are used in the Ajax request called within the doSubmit function. Since you can't, you might want to consider overriding Ext.form.action.Submit such that you can, then calling the form.submit() function you mentioned in your question.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.action.Submit-method-doSubmit

Content not returned during AJAX call

I attempting to load page content on a jQuery Mobile site via an AJAX call to the desktop version of the same site, which is generating the content for each page as a JSON object. I have confirmed that the JSON objects are good (i.e.: if you place the URLs into the browser, a good JSON object displays). The section of each JSON object that I am attempting to display is identified as "content" in the object itself.
On the jQuery Mobile page, I am placing a function to call the relevant JSON object and replace the content of that page with the JSON content. The function is as follows:
function processJSON(url, id){
$.ajax({
url: url,
data: null,
success: $(id).html(response.content),
dataType: 'json',
});//ends ajax
};//ends processJSON
The arguments for the function are as follows: "url" is a variable set equal to the URL of the appropriate JSON object, and "id" is the id of the div the content of which I want to replace with the JSON content. This page is living on the same server as the desktop version of the site, on an "m." subdomain.
When I place this on a test server, I receive an error in the console stating "Uncaught ReferenceError: response is not defined." Does this mean that the function is not receiving any JSON response, or that it cannot identify the "content" section of the JSON object? How do I correct this?
Thanks for your assistance.
from jquery.ajax doucumentation
success Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server,
formatted according to the dataType parameter; a string describing the
status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
success: function(response)
{
$(id).html(response.content)
}

How to attach html response (got from ajax request )with div tag in jquery?

Below is the code snippet which is hitting the url on server and getting the html response.I can see
the response inside firefox debugger but it does not display in div tag.
$.ajax({
url: url,
dataType: 'html',
data: '',
type: 'POST',
success: function(data) {
//in firefox debugger i can see complete html response inside data
$('#displayContent').html(data); // but here, it does not
// append the html inside div displayContent. Instead it makes
// the current page blank
}
});​
I don't get what mistake I'm making here Can I not directly assign the ajax html response to an selector(div tag in my case) with $('#displayContent').html(data)?
Instead of using html() method use append i.e.
$('#displayContent').append(data);
Or if you want to assign whole content direct to your element use load method
$(function(){
$('#displayContent').load(url);
});
If you've got a form tag on your page, and you're trying to submit it asynchronously with jQuery, your function will need to return false, to prevent the browser from handling the form.
Example:
$("form").submit(function () {
$.ajax(...);
return false;
});

Resources