I have an Html template with a form inside of it.
<form id="my_form" method="post" action="/register/">
<input id="cemail" name="email" size="25" class="textbox required email" style="width: 250px"> <br><br>
<input id="csubmit" type="submit" onclick="Clicked();" value="Send" />
I also have a Jquery code for test if the e-mail introduced is correct:
<script type="text/javascript" src="/js/jquery.validate.js"></script>
<script>
function Clicked() {
$("#my_form").validate().form();
value = $("#cemail").val();
alert("ufffff");
$.get("/exists/", {email: value}, function(data) {
$('#text')[0].innerHTML=data;
});
}
</script>
Until here everything is ok. My problem appears when I execute the program. Always the action="/register" is launched, and I don't want that it occurs. I would like that:
If jquery is desactivated on the client browser, execute the action that the form has. In case that jquery is activated on the client browser, just execute the "Clicked()" function and not the form's action ("/register/" --> calls django function)
Does anyone help me to do that? Is it possible?
You need to return false from your Clicked function.
Return false from an event handler in JavaScript tells the browser not to execute the default action associated with that element (a link, or a button).
If you want to be super-duper correct, you should actually attach yourself to your form's submit action and return false there. This will allow a user to hit the return key to submit your form, but stop the browser from doing a POST:
$('#my_form').submit(function(){
$("#my_form").validate().form();
value = $("#cemail").val();
alert("ufffff");
$.get("/exists/", {email: value}, function(data) {
$('#text')[0].innerHTML=data;
});
return false;
});
If JavaScript is disabled, the browser will execute the default action for the form normally.
Related
How I can call a Django API from another Django Project (or from any other project) and get the response back after some processing on the same calling page (the page from which I called the API)
I am calling the API from form action ....but API shows the response in a new blank page
Here is API CODE: (//skipping some code to avoid confusion)
def IdealWeight(request):
#defining a list of data to send back to html
list_of_data=[]
list_of_data.append(name)
list_of_data.append(fatherName)
list_of_data.append(registration)
print(list_of_data)
# outPut_Data = ast.literal_eval(list_of_data)
# return render(request,'LibraryForm.html',{'data1':outPut_Data})
return JsonResponse(list_of_data,safe=False)
I want list_of_data on the calling page in some variable.
Here is my HTML Code from which i am calling the API:
<form action="http://127.0.0.1:8000/idealweight/?image/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" class="form-control-file" name="image" onchange="readURL(this);" required>
<input type="submit" class=" btn btn-primary" title="Process" value="Process" id="processButton">
</div>
{{ data1 }}
</form>
From HTML page, I am sending a picture to API (API build in Django)
and from that, I want to send an array or list of data extracted from the image and want to show that on same HTML page....................from which I called the API how I can do that?
hope I am clear what I want?
Using an Ajax call would be better choice. you would be doing something along the line.
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('file');
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://127.0.0.1:8000/idealweight/?image/',
contentType: false,
data: form_data,
type: 'post',
success: function (response) {
// use response to update html
},
error: function (response) {
// use response to update html
}
});
});
});
and your template would be something like
<input type="file" id="file" name="file"/>
<button id="upload" type="button">Process</button>
note: you might get cross origin request block error. so you have to allow that explicitly.
I am adding a comment functionality in my project. And I am using ajax to make it dynamic so that when the user clicks on the comment submit button it will be added in the comment section dynamically without refreshing the page. But the problem is when prepending a form using ajax I cant add csrf token like this
{% csrf_token %}
in the form because ajax wouldn't understand it and take it as text.
function getids(postid){
console.log(postid)
$(postformid).one('submit', function(event){
event.preventDefault();
console.log(event)
console.log("form submitted!") // sanity check
create_comment(posted);
});
}
// AJAX for posting
function create_comment(postid) {
console.log("create comment is working!") // sanity check
console.log(postid)
console.log(talkid)
$.ajax({
url : "create_comment/"+postid, // the endpoint
type : "POST", // http method
data : { the_comment : $(cmtext).val() }, // data sent with the post request
// handle a successful response
success : function(json) {
$(cmtext).val(''); // remove the value from the input
console.log(json); // log the returned json to the console
$(talkid).prepend(
"<div class='col-1 p-0'><form' id=upvote' method='POST'>{%"csrf_token"%}<button
class='btn btn-md btn-outline-danger btn-
block p-auto' id='btnid' onclick='---' type='submit'></button></form></div>");
console.log("success"); // sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
}
});
};
pretending my form here
<div class="row m-0" id="talk{{post.id}}"></div>
is there any other way around?
Use
{% csrf_token %}
just before the form tag inside your template.
I am submitting a file in a cfdiv container, but the value of the file is not submitting to the processing page. If I submit the file outside of the cfdiv, it sees the file value. However, if the file is inside a cfdiv or div container, the form field is undefined. I have also added the enctype="multipart/form-data" to the cfform, but it is still not working.
UPDATE:
This is the first page (index.cfm)
<div name="loadcontainer" id="loadcontainer">
<cfinclude template="homepage.cfm">
</div>
The homepage.cfm
<cfform name="school_create" id="school_create"
action="pro_create_school.cfm"
enctype="multipart/form-data"
method="post">
<cfinput size="50" type="file" id="school_logo" name="school_logo">
<button type="submit">Save</button>
</cfform>
When the save button is clicked, it doesn't see the form.school_logo value in the action processing page.
I have also tried using a normal form and input, instead of a cfform/cfinput, but the form is being loaded into another tab when submitted, instead of the div container.
"File" is an incorrect "type" for a CFINPUT in earlier CF Versions (not sure what version you are using). I did check the docs and it is allowed in current versions.
Meanwhile, Instead change your CFINPUT to:
<input size="50" type="file" id="school_logo" name="school_logo">
Or better yet, get rid of <cfform> - you aren't using it for anything and you don't need it. A good JS library (jquery) will provide you with better functionality for validation etc.
In this case you could easily do:
<form name="school_create" id="school_create"
action="pro_create_school.cfm"
enctype="multipart/form-data"
method="post">
<input size="50" type="file" id="school_logo" name="school_logo">
<button type="submit">Save</button>
</form>
And it would work as expected. Cfform is designed to provide simple validation functions in a native CF Fashion, but outside of tutorials and books explaining CFML almost no one uses it. When we see it used here at CF Webtools, we refactor it as soon as we are able.
I was able to Submit the form both the <cfinput type="file"..../> and other form field in the form with ajax.
<script>
function validateForm() {
var x = document.forms["add_academic_year"]["start_year"].value;
var y = document.forms["add_academic_year"]["end_year"].value;
if (x == null || x == "" || y == null || y == "") {
alert("Start Year and End Year Must be Selected");
return false;
}
if (y <= x) {
alert("End Year must be greater than Start Year ");
return false;
}
console.log("submit event");
var fd = new FormData(document.getElementById("add_academic_year"));
$.ajax({
url: "pro_academic_year.cfm",
type: "POST",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( response ) {
// display response in DIV
$("#loadcontainer").html( response.toString());
})
.fail(function(jqXHR, textStatus, errorMessage) {
// display error in DIV
$("#outputf").html(errorMessage);
})
return false;
}
</script>
I'm using Ember CLI and have noticed odd behaviour. When the user clicks into the input and presses the enter key, the page refreshes.
My page has a basic element like this that is NOT part of any form:
<input type="text" class="form-control" id="per_page" value="50">
I am currently serving the page via:
ember cli
So node is hosting and has the fancy live reload thing going on so that when I update a page that is part of the underlying app.
So what is causing a page reload the enter key pressed inside an input? Could it be node or live reload? Are inputs just supposed to refresh a page when a user presses the enter key and I missed that in my HTML for dummies book?
**Better still, how can I intercept and instead call a function via:
{{action** "myFunction"}}
That happens because when you hit Enter, form gets submitted which results in page reload. what you need to do is set onsubmit="return false" on the form so nothing happens during submit. you can bind input to execute some action by adding action attribute action="doSomething"
<form onsubmit="return false">
{{input type="text" action="createComment" value=topic id="inputTopic"}}
</form>
Edit: In Ember 3+ you now use the {{on}} modifier to setup events on elements.
<form {{on 'submit' this.submitForm}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
And the action defined like so
#action
submitForm(event) {
event.preventDefault();
// Your code
}
Historically Ember has handled this use case with the following code:
<form {{action 'submitForm' on='submit'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
This prevents the form from refreshing the page.
There is another method that gives you more control, by giving you the event so you can manage that yourself:
<form onsubmit={{action 'submitForm'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
In this case, you will get an event and will have to call event.preventDefault() to stop the page refresh.
actions: {
submitForm(event) {
event.preventDefault();
}
}
This is a running example of the two: https://ember-twiddle.com/827820958e054f7af57b7677630729fc?openFiles=controllers.application.js%2C
I had the same problem - what worked for me, was to overwrite the keyPress Event in the input component like this:
keyPress: function (e) {
var keyCodeEnter = 13;
if (e.keyCode === keyCodeEnter) {
return false;
}
}
Hope it will help someone in the future! :)
I am having some trouble getting the state manager to toggle my views. I have a state machine, which will initially display the login screen and once the user has been authenticated the state machine will transition to the authorized state and display the workspace or dashboard. The problem is that when i load the page I don't see the login screen so i suspect i am missing something. I am using emberjs 0.9.7.1
Here is the div where i want the screens added
<body>
<div id="main-container" class="container">
</div>
</body>
This is the core html snippet of login_view.handlerbars file (there is more but i have omitted it fror brevity sake). I can see this compiled and stored in Ember.TEMPLATES['login_view'].
<form class="form-inline">
<fieldset>
<input type="text" name="email">
<input type="password" name="password">
<button id="sign-in-button" class="btn btn-primary">Sign In</button>
</fieldset>
</form>
Here is the associated view javascript file
App.LoginView = Ember.View.extend({
templateName: 'login_view'
});
Finally, here is my state machine. I see the message "Entering unauthorized state" in the console but i don't see the login html embedded within the specified div.
App.sessionStates = Ember.StateManager.create({
rootElement: '#main-container',
initialState: 'unauthorized',
unauthorized: Ember.ViewState.create({
viewClass: App.LoginView,
enter: function(stateManager, transition) {
console.log("Entering unauthorized state");
},
exit: function(stateManager, transition) {
console.log("Exiting unauthorized state");
}
}),
authorized: Ember.ViewState.create({
view: App.WorkspaceView
})
})
cheers
Actually the docs are wrong and a bit confusing.
They tell you that you have to call this._super() if you overwrite those methods, but they forgot to specify that you have to pass the arguments as well.
I got it running with this code:
enter: function(manager, transition) {
this._super(manager, transition);
}
or if you don't care about the arguments:
enter: function() {
this._super.apply(this, arguments);
}
I think it should be 'view' instead of 'viewClass'
unauthorized: Ember.ViewState.create({
viewClass: App.LoginView, // the key should be 'view'
UPDATE:
Here is a quick example fiddle showing how to use the StateManager. http://jsfiddle.net/lifeinafolder/GNr4M/
If you want to use 'enter' & 'exit' states, be sure to call super(). Ref: http://ember-docs.herokuapp.com/#doc=Ember.StateManager&src=false