HTML FORM - have form action="" occur before onsubmit="" - action

I've got a pop-up form, onsubmit it closes itself and also refreshes the parent screen.
It uses action="x.php" to transfer session data.
My problem is that in the form onsubmit="js()" is occuring before action="x.php", so the data doesn't get sent before the window closes.
How can I switch the order that these are executed?

Use jQuery AJAX to submit the form and perform your onsubmit code in the success callback.
$("#formID").submit(function() {
/*
Do client side validation before you submit the form with AJAX
*/
var formData = $("#formID").serialize();
$.ajax({
type: "POST",
url: "x.php",
data: formData,
success: function() {
/*
The actions you want to perform
window.close(); // etc etc
*/
}
});
return false; // stop default form submit because we're using ajax
});

Related

Django select option

I have a form which has a select field (your color). In front of the select field, I have a button that produces a popup which allows users to create new color before they submit. I am submitting that color form via Ajax. After adding a new color to the database, the popup closes.
I want the newly added color to show in the select list without reloading the page.
Is this possible?
I think you can do this by the same ajax where the success triggers. Code below may help a little :
$(".submit").click(function () {
$.ajax({
url: 'url where your view waits',
data: {
'post': "your data on post",
},
type: 'post',
cache: false,
success: function (data) {
// here you can do DOM manipulation add new object to the list.
// You can also get data from backend in json format an then
// add it to your DOM.
},
});
});
I hope this helps.

How to handle multiple actions in Django-Template

I have created a web app in which page which consist of choose file input and Now I need to preprocess the data with one button and that preprocessed data should be used for next button called forecast to show the result in that page.Is it possible with Django.
Does it compulsory to take any action in page with url changes in django?
The question is not completely clear, but from what I understand you can use Ajax. On first button click send an ajax request, process it in the view logic, send the appropriate data using maybe JsonResponse, and in the success block of your ajax request set the appropriate data for your forecast button using jquery. Something like -
$.ajax({
url: <url_of_data_processing_logic>,
type: 'post',
data: <required data>,
dataType: 'json',
success: function (data) {
$("#<forecast_button_Id>").html(data.forecast_html);
},
error: function (e) {
console.log(e);
}
});

Return in Http Response and Html page but its not showing on the browser in Django

I have created a page on locahost:8080/kar, i am sending an ajax POST request to different Url(same domain) i.e. locahost:8080/kar/create_post there i am returning an HTML response but its not showing on the browser as the URL is still on locahost:8080/kar, the data is stored in the database.Where as in the developer console i can see the response in the network tab .When i redirect it is also showing the same thing in the developer console
Why i am not able to change the URl and see the response ?
It's a client side thing, that means the desired behaviour needs to be implemented with javascript. Django is functioning normally here.
When you're sending Requests via AJAX, that is a non blocking request with the XMLHttpRequestheader set, your browser won't trigger the chain of events that occurs when a server side script evaluates your form and returns something, which may be data, or a redirect, depending on whether the form validated or not.
A typical AJAX call in jQuery looks like this:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
If you would like to perform some actions when the request you sent by XMLHttpRequest returns, you could attach that to the appropriate success handler:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
If you need to redirect to the URI that is returned as a redirect from your server you can get the redirect URI from the response in the success handler:
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
If you would like to modify the URL in the users bar without reloading the page you could have a look at this question.

can't access to the POST variable that sent from register form in django

I have a register form in html that has a button that type of submit and the name of registerSubmit like this:
<input class="RegisterButton right green" name="registerSubmit" type="submit" value="Continue">
I want to check the form with Ajax and then if every thing is valid then redirect the user to her/his profile.But when I want to redirect the user to his/her profile I can't send the submit input that its name is registerSubmit. here is a section of JQuery code that related to this event:
$("#mainRegisterForm").submit(function(event){
var thisRegisterForm = $(this);
$(".ajaxLogoRegister").show();
event.preventDefault();
var firstName = $("input[name='firstname']").val();
var lastName = $("input[name='lastname']").val();
var emailAddress = $("input[name='email']").val();
var password = $("input[name='password']").val();
var rePass = $("input[name='rePass']").val();
var sex = "NULL";
if ($("input[name='gender']").is(":checked")){
sex = $("input[name='gender']:checked").val();
}
var data ={
firstname:firstName,
lastname:lastName,
emailaddress:emailAddress,
password:password,
repass:rePass,
sex:sex
};
$.ajax({
url: 'ajax/registercheck',
data: data,
dataType: 'json',
success:function(result){
if(result.fn==0){
//do some stuff
}
//another if conditions that checks the validity of every field of refister form
...
...
$(".ajaxLogoRegister").hide();
if(result.isOK=='1'){ //isOK = 1 when every filed is valid and user must redirect to his/her profile
thisRegisterForm.unbind('submit').submit();
}
}
});
});
My main problem is that when I click the registerSubmit button in views.py the request.POST.get('registerSubmit') returns None object instead of Continue value.
when I don't use Ajax and send the form normally registerSubmit value is Continue and every thing is OK.where I am wrong?
By default, $.ajax(); will issue a GET request, not a POST. You need to specify that in your ajax options. Second, I don't see where you're accessing the value of the element named "registerSubmit". I see an "rePass", but you're not including the value you're expecting to find in the request.
You need to either specifically set the "type" ajax option type to "POST" or retrieve the method property from the form element:
$ajax({
url: 'ajax/registercheck',
data: data,
dataType: 'json',
type: 'POST',
....
});

AJAX call not returning -- success function not being executed in Django

I am doing AJAX calls using jQuery in Django. Everything seems to be working fine except that the ajax call is not being returned as a result the success function is not being executed. This is my jquery file
$.ajax({
type: "POST",
url: "/contact_us/",
data: {
'name': name_val,
'email': email_val,
'message': message_val,
'subject': subject_val,
'cc': cc_val,
},
success: function()
{
// display success message and reset values in the form fields
$("#reply-message").html('Your message has been sent!').fadeOut(3000, function() {});
// clear the fields
$("#contact-name").val("");
$("#contact-email").val("");
$("#contact-message").val("");
$("#contact-subject").val("");
}
});
I do not know what to return in the view for an AJAX call so right now I am just returning a dummy message, but it is not working. Here is the views.py
def contact_us(request):
if request.is_ajax():
if request.method == 'POST':
name = request.POST.get('name', False)
email = request.POST.get('email', False)
message = request.POST.get('message', False)
subject = request.POST.get('subject', False)
cc = request.POST.get('cc', False)
recipients = ['abc#gmail.com']
if cc:
recipients.append(email)
from django.core.mail import send_mail
send_mail(subject, message, email, recipients)
return_message = "Sent mail"
return Httpresponse(return_message)
The return_message is dummy, I don't even want to process it in my response. But why is the ajax call not returning, rest everything is working fine and I am also receiving the mail.
I just realsed that I had made a very stupid mistake I have written Httpresponse whereas it has to be HttpResponse. Now it is working absolutely fine
I can't see any immediate problems with your code. If you have Firebug, open up the 'Net' tab and you should be able to see the response code received and inspect the response. You should be getting a '200 OK'.
Another debugging option - try putting in the following:
$.ajax({
type: "POST",
url: "/contact_us/",
data: {
'name': name_val,
'email': email_val,
'message': message_val,
'subject': subject_val,
'cc': cc_val,
},
success: function()
{
// display success message and reset values in the form fields
$("#reply-message").html('Your message has been sent!').fadeOut(3000, function() {});
// clear the fields
$("#contact-name").val("");
$("#contact-email").val("");
$("#contact-message").val("");
$("#contact-subject").val("");
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
That should tell you what the problem is if the Ajax call fails.
The reason your success function isn't being executed is probably because you aren't returning valid xml. jquery checks the data coming in to see if its the right format, aka xml because you are using the ajax call.
Reformat your data, or switch to a different jquery call.
from the jquery website on the ajax call.
success(data, textStatus, jqXHR)Function, Array 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. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
Edit: Additional info from the jquery site, check your MIME type for the return:
Note: We must ensure that the MIME type reported by the web server
matches our choice of dataType. In particular, XML must be declared by
the server as text/xml or application/xml for consistent results.
This is a bit late, but here it is.
Are you passing a CSRF token with your ajax requests?
To explicitly do this with each request, add the token to the data being sent to the server
$.ajax({
...
data: {
...
csrfmiddlewaretoken: '{{ csrf_token }}',
...
},
...
});
If you want the token to be sent automatically with each request, then you'll have to jump through the hoops described in the link.
Either way, be sure to add django.middleware.csrf.CsrfViewMiddleware to you MIDDLEWARE_CLASSES list in your settings.py file.