I'm Junior Django dev. It's my first project in my company and I have a FrontEnd task.
The frontend is black magic for me but trying my best but here I am totally lost;/
Task to do:
"If I click on checkbox it redirect to page with an endpoint which change
value of checkbox from on to off"
I wrote all backend staff... and even some kind of frontend but it is not working as I want it to. I've tried loads of combination but I still don't know.
Code of checkbox:
<table>
<thead>...</thead>
<tbody>
<td>
<a href="{% url 'product_user_paid_change' tp_id=item.pk paid=item.paid %}" onclick="return confirm('For surechange - {{ item.full_name }}?')">
<div class="checkbox m-15">
<label for="id_paid"><input type="checkbox"{% if item.paid == True %} checked{% endif %} ><i class="input-helper"></i></label>
</div>
</a>
</td>
</tbody>
</table>
And what is happening here?
When I click directly on checkbox there appears a confirmbox when I
click "OK", checkbox change state but request is not send...
When I click outside checkbox there is confirmbox and when I click "OK" I'm correctly redirected to request site.
How to make it work when I click directly on checkbox... not only outside? ;/
I tried to transport this before div, after div, before label, inside label... nothing works.
I will appreciate any help!
Its pretty simple, and as my edit dont have nothing to do with python or django.
What you have to do it create one input checkbox at your template
<input type="checkbox" id="my_awesome_checkbox">
Create one javascript function or just bind the code to event in that input
<input type="checkbox" id="my_awesome_checkbox" onchange="myCuteFunction">
function myCuteFunction() {
var checkBox = document.getElementById("my_awesome_checkbox")
if (checkBox.checked == true){
let result = confirm("Hey! You really want to leave me here?");
if (result){
location.replace("the url you wan to go");
}
}
}
EDIT: You want to changed the Checkbox value based on information from your backend?
If is that you can use ajax to get the response you want from your endpoint and change your checkbox
So using the previous code you can call the ajax to reach your backend instead of changing the page your url... and than change the value of your checkbox
function myCuteFunction() {
var checkBox = document.getElementById("my_awesome_checkbox")
if (checkBox.checked == true){
let result = confirm("Hey! You really want to leave me here?");
if (result){
$.ajax({
url: "<your endpoint>",
context: <necessary paramenters>
}).done(function() {
<your response to add your logic to change the checkbox>
});
}
}
}
Related
I have a Google App Script addon. This addon is initiated by a click on a checkbox. I am trying to figure out the way I can redirect back once the add-on finishes installing.
view file
<div class="checkbox">
<label><input type="checkbox" required="true" onclick="window.location.assign('/path/to/addonscript/')" id="addon-checkbox">Enable Addon</label>
</div>
While the addon script Code.gs has some functions related to ad-on working. I am trying to implement a redirect mechanism to playframework view page.
A pretty close thing looks like the onInstall(e) trigger available here. Any pointers towards solutions?
Ok first of all lets look at your code:
<div class="checkbox">
<label><input type="checkbox" required="true" onclick="window.location.assign('/path/to/addonscript/')" id="addon-checkbox">Enable Addon</label>
</div>
It seems you want to redirect when the the checkbox is clicked. So, you could do this in two steps:
Add an event listener to the checkbox.
Send a redirect to the route, if a condition satisfies (such as something is true/false when the installation finishes).
You could have it something like this in your is code:
function onInstall(addOnElement) {
return true;
}
document.getElementById("checkBox").addEventListener('click', function(){
var addonElement ="whatever"; //or use docuement.getElementById if you need to get it from the page.
var isInstalled = onInstall(addonElement); //calling a function that returns true when the installation finishes.
if(installed){ //or simply use onInstall()
var redirectUrl = "/time/to/redirect";
window.location.replace(redirectUrl);
}
}
For the above code, you can remove the the onclick attribute; and add an id (e.g., id="checkBox").
Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot
I have a popup modal that displays on page load that has the following form in it:
<form class="enterForm">
<label class="modalFields" id="userName" style="display: none;">
<span>user Number :</span>
<input type="text" name="userNum" placeholder="User Number" required/>
</label>
</form>
<label>
<span> </span>
<input type="submit" value="Submit" class="submitButton">
<input type="hidden" id="hiddenInput">
</label>
And on user submission of the form, I want to hit a certain API via an AJAX call, which returns a JSON that looks like:
{
"results":[
{
"person":{
"firstName":"John",
"lastName":"Smith"
},
"userNumber":"12345"
}
]
}
If the userNumber matches the value that the user submitted, I then want to update the nav bar to say the person's first name. In terms of process flow I want it to go: user types in user number -> submits form -> AJAX call hits API -> checks to see if user input matches userNumber value in JSON --> if match, selects the firstName value and updates it in the nav bar. How could I go about achieving this?
Considering you know how to do AJAX calls and you're using an API, integrating jQuery to facilitate the thing shouldn't be too hard (if it is, I included additional information after the solution).
Solution
JavaScript
//On form submit
$('#enterForm').submit(function(){
var userNum = $('[name="userNum"]').val();
//AJAX call to your API
$.ajax({
url: 'myAPICall.php',
/* data: {userNumber: userNum}, //If necessary */
success: function(data) {
// Note: this code is only executed when the AJAX call is successful.
if(data.results.userNumber == userNum){
$('#navBarFirstName').text(data.results.person.firstName);
}
},
error: function (err) {
//If the AJAX call fails, this will be executed.
console.error(err);
}
dataType: 'JSON'
});
return false; //Prevents the page refresh if an action is already set on the form.
});
Explanation
You use jQuery to bind a function (event listener) to the submit event of your form.
When the submit event is triggered, the function runs:
It gets the value of your DOMElement with the name attribute "userNum"
It makes an AJAX call to your API (with/without the userNum value, you choose if you want to check that on the server side or not)
On success, (when the call is done successfully), it updates the navbar content using .text() with the firstName attribute of your JSON response.
Including jQuery
You can integrate jQuery by including the script within your HTML page. You can either download it or use a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">
/* Don't put your code in here it won't be parsed */
</script>
<!-- the following tag could also be <script src="link/to/your/script.js"></script> -->
<script>
/* Your actual script */
</script>
Make sure to put this line before your actual javascript file containing the script written above, otherwise jQuery won't be initialized and the script won't work.
UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.
I want to know abt DOM manipulation in meteor. My code goes as follows:
<template name = "studentList">
{{#each}}
<div class = "name">
Name: {{this.name}}
</div>
<div class = "age">
Age: {{this.age}}
</div>
<button class = "edit"> Edit </button>
{{/each}}
<button class = "addStudent"> Add Student </button>
</template>
Template.studentList.helpers({
studentlist:function(){
return Students.find();
}
});
Template.studentList.events({
//I am doing the DOM manupulation here based on the buttons clicked
});
I get a list of Student Info from the DB and display them in the template. Now for each student, there is an edit button. When user clicks this edit button, I want to change the "name" and "age" field of the student as text field and give an option to "save" and "cancel".
Similarly, I have an "add student" button at the end of the template. When a user clicks it, I want to display a form, where student's name and age is added and then saved.
So far, I am being able to do this, but in a very naive way by using lots of Jquery/Javascript code in the events of studentList. I read many post that says this is not the correct way.
Can anyway please tell how can this feature be achieved in meteor. Or just to some possible ways of doing it.
Help appreciated.
This is a possible way to accomplish this.
Lets try to do this step-by-step
First this is how the HTML should look.
{{#if editName}} <!-- editName template helper -->
<!-- If the Session is equal to true this part of the html will be showed -->
<input type="text" class="newName" value="{{this.name}}" />
{{else}}
<!-- this is what we show by default on the view, if user click the div, the input will be showed -->
<div class="name">Name: {{this.name}} </div>
{{/if}}
Now the JS.
The helper should look like this.
Template.studentList.helpers({tName:function(){
return Session.get("studentName" + this._id); //getting the session true or false.
}
});
And the Events.
Template.studentList.events({
'click .name' : function(event,template){
//On this event we are Setting the Session to true and holding the id of the student
return Session.set("studentName" + this._id,true)
},
'keypress .newName':function(event,template){
//Some keypress to update the value
//using http://docs.meteor.com/#/full/template_$ to get the value using meteor
var newNameStudent = template.$('.newName').val();
if(event.keyCode == 13){ //if enter lets update the value
Students.update({_id:this._id},{$set:{name:newNameStudent}})
return Session.set("studentName" + this._id,false) //setting to false the session to hide the input and show the <div>
}
},
'click .cancel':function(){
return Session.set("studentName" + this._id,false) //setting to false the session to hide the input and show the <div>
}
})
If you see there is not too much code (i guess), you get the idea how to use the sessions to do simple CRUD operations.
I made a Meteorpad of this working example, check it.