PHP & Jquery Refresh id with external file - javascript

I'm trying to refresh one ID of my page within the click of a button.
I've tried several ways but none of them work. Although I've created the button to refresh it, it keep the submission of the page (triggering the validation event). So, each time I click that button, he tries to submit the form, validation the inputs instead refresh that div.
Here's my code right now:
function refreshCaptcha() {
$("#captcha_code").attr('src','./inc/captcha.php');
}
<div class="form-group">
<div class="col-xs-4">
<button class="btn btn-sm btn-warning" id="refreshcap" name="refreshcap" onclick="refreshCaptcha();">
<i class="fa fa-refresh push-5-r"></i>
<img id="captcha_code" src="inc/captcha.php" />
</button>
</div>
<div class="col-xs-8">
<div class="form-material floating">
<input class="form-control" type="text" id="cap" name="cap">
<label for="cap">Captcha</label>
</div>
</div>
</div>
Can someone help me trying to get what's wrong?
Thanks.

Assuming that your button is inside the form,
add type in your button
which will stop button from submitting your form
<button type="button" class="btn btn-sm btn-warning" id="refreshcap" name="refreshcap" onclick="refreshCaptcha();">
<i class="fa fa-refresh push-5-r"></i>
<img id="captcha_code" src="inc/captcha.php" />
</button>
other than that you can use javascript return false; in your function end
with js
<script>
$(document).ready(function() {
$("#refreshcap").on("click",function(event){
event.preventDefault();
$("#captcha_code").attr('src','./inc/captcha.php');
});
});
</script>
with this you wont need to call on click event this will do it for you, no matter type is button or submit

I think your JS function should return false; in order to not submit the form.
<script>
function refreshCaptcha() {
$("#captcha_code").attr('src','./inc/captcha.php');
return false;
}
</script>

Related

How to focus next textarea on button click

I'm trying to do something like a social network, but I'm having problems with jquery, I want, by clicking the comment button, the user is taken to the comment field, but I'm not able to use $(this).
When the user click here
The code:
<button type="button" class="btn btn-default abreComentarios" >
<span class="fa fa-comments-o"></span>
</button>
The field:
The code:
<div class="comentar">
<textarea class="txtComentario form-control caixaComentario" placeholder="Seu comentário" onkeypress="comentarEnter()"></textarea>
</div>
My jquery:
$('body').on('click', '.abreComentarios', function() {
//console.log('entrou');
$(this).next('.caixaComentario').focus();
});
Remember, I'm using a foreach, so I have to use $(this)
Your next() isn't .caixaComentario but .comentar,
So use the next() but then you'll have to use find() (or children()) to focus the textarea
$('.abreComentarios').on('click', function() {
//console.log('entrou');
$(this).next('.comentar').find('.caixaComentario').focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-default abreComentarios">click</button>
<div class="comentar">
<textarea class="txtComentario form-control caixaComentario" placeholder="Seu comentário"></textarea>
</div>
Solved, i just did it:
1- Added a data-id with the id of the post in the button
<button type="button" class="btn btn-default abreComentarios" data-id="'.$post->id.'"><span class="fa fa-comments-o"></span></button>
2- Added the same id in the end of the name of class "caixaComentario"
<div class="comentar">
<textarea class="form-control caixaComentario'.$post->id.'" placeholder="Seu comentário" onkeypress="comentarEnter()"></textarea>
</div>
3- Call without $(this) on jQuery
$('body').on('click', '.abreComentarios', function() {
var id = $(this).data("id");
$('.caixaComentario'+id).focus();
});
and Worked :D
$(this) will be your <button>, but calling .next(".caixaComentario") will look for a sibling element to the button. If your <button> and <div class="comentar"> are siblings, the .next(".caixaComentario") will not match any elements as they aren't siblings. The would be a niece/nephew.
Try changing .next(".caixaComentario") to .next("div .caixaComentario")

jQuery expand and collapse text

I am having trouble expending and collapsing text on a button click. I was able to make so when you click the button, text collapse, but I also need to make so you can expand it back. I need to make it so first it is hidden, and when you click button it expends and you can collapse it again after that. Here is my code
$(document).ready(function() {
$('#btnSlideUp').click(function() {
$('#p1').slideUp(1000);
});
$('#btnSlideDown').click(function() {
$('#p1').slideDown(1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="btnSlideUp" class="btn btn-outline-success"><h1 class="jumbotron-heading">Expand</h1></button>
<p class="lead text-muted" id="p1">Below this post you can find different articles, tips&tricks about how to find the job. You can try to contact us, and we will greatly try to answer all of your questions. You can click on "Start finding a job" and we will take you through the basics
of finding a job, from the beginning till the end if you have absolutely no excperience.</p>
<p>
<a href="contactus.html"><button type="button" class="btn btn-
outline-primary btn-lg">Contact Us</button></a>
<a href="path.html"><button type="button" class="btn btn-outline
secondary btn-lg">Start finding a job</button></a>
</p>
</div>
The issue is that you bind two handlers to the click event on the button. When the button is clicked, both are triggered but you only see the initial one (slideUp).
$('#btnSlideDown') refers to an element that doesn't exist (at least not in your example).
The easiest way to resolve this is to use jQuery's slideToggle() method to handle the click event.
$(document).ready(function() {
$('#btnSlideUp').click(function() {
$('#p1').slideToggle(1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="btnSlideUp" class="btn btn-outline-success"><h1 class="jumbotron-heading">Expand</h1></button>
<p class="lead text-muted" id="p1">Below this post you can find different articles, tips&tricks about how to find the job. You can try to contact us, and we will greatly try to answer all of your questions. You can click on "Start finding a job" and we will take you through the basics
of finding a job, from the beginning till the end if you have absolutely no excperience.</p>
<p>
<a href="contactus.html"><button type="button" class="btn btn-
outline-primary btn-lg">Contact Us</button></a>
<a href="path.html"><button type="button" class="btn btn-outline
secondary btn-lg">Start finding a job</button></a>
</p>
</div>
You can use jQuery's toggle method instead:
$(document).ready(function(){
$('#btnSlideUp').click(function(){
$('#p1').toggle(1000);
});
});
Try This.
$(document).ready(function() {
$('#btnSlideUp').click(function() {
$('#p1').slideToggle(1000);
});
You can read the full documentation here
Use jquery .slideToggle() function.
$(document).ready(function() {
$('#btnSlideUp').click(function() {
$('#p1').slideToggle(1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="btnSlideUp" class="btn btn-outline-success"><h1 class="jumbotron-heading">Expand</h1></button>
<p class="lead text-muted" id="p1">Below this post you can find different articles, tips&tricks about how to find the job. You can try to contact us, and we will greatly try to answer all of your questions. You can click on "Start finding a job" and we will take you through the basics
of finding a job, from the beginning till the end if you have absolutely no excperience.</p>
<p>
<a href="contactus.html"><button type="button" class="btn btn-
outline-primary btn-lg">Contact Us</button></a>
<a href="path.html"><button type="button" class="btn btn-outline
secondary btn-lg">Start finding a job</button></a>
</p>
</div>
Use a boolean
var isDown=true;
$('#btnSlideUp').click(function() {
if(isDown){
$('#p1').slideUp(1000);
isDown=false;
}else
{
$('#p1').slideDown(1000);
isDown=true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button id="btnSlideUp" class="btn btn-outline-success"><h1 class="jumbotron-heading">Expand</h1></button>
<p class="lead text-muted" id="p1">Below this post you can find different articles, tips&tricks about how to find the job. You can try to contact us, and we will greatly try to answer all of your questions. You can click on "Start finding a job" and we will take you through the basics
of finding a job, from the beginning till the end if you have absolutely no excperience.</p>
<p>
<a href="contactus.html"><button type="button" class="btn btn-
outline-primary btn-lg">Contact Us</button></a>
<a href="path.html"><button type="button" class="btn btn-outline
secondary btn-lg">Start finding a job</button></a>
</p>
</div>

Bootstrap Popover Inside Popover not working

I am using twitter bootstrap to share my post on social media, i have made a link whose popover with some buttons content, but further when i click on buttons in popover, their popover function does not work.
<div class="well text-center">
<button id="but1" title='Popover' class="btn btn-success" rel='popover' data-placement="bottom" data-toggle='popover2'>Share</button>
</div>
<div class='container hide' id='cont'>
<a onclick="Facebook()"
class="btn btn-default">
Facebook
</a>
<a onclick="twitter()"
class="btn btn-default">
Twitter
</a>
<a class="btn btn-default"
data-placement="bottom" data-toggle="popover" data-title="Login" data-container="body"
type="button" data-html="true" href="#" id="login">
Email
</a>
</div>
<div id="popover-content" class="hide">
<form class="form-inline" role="form">
<div class="form-group">
<input type="text" placeholder="Name" class="form-control" maxlength="5">
<button type="submit" class="btn btn-primary" onclick="EmailToSomeOne();">Send</button>
</div>
</form>
</div>
and the js
$('#but1').popover({
html: true,
content: $('#cont').html()
});
$("[data-toggle=popover]").popover({
html: true,
content: function() {
return $('#popover-content').html();
}
});
function Facebook(){
alert('share on facebook');
}
function twitter(){
alert('share on twitter');
}
function EmailToSomeOne(){
alert('Email to send');
}
for more clearing i have created a fiddle also.
Your code works fine. Its just a jsFiddle setting issue.
In your fiddle select no wrap (head) in the dropdown on the left, click Run and it will work.
See example
When onLoad is selected your functions are defined within the closure of the $(document).ready(function() {}); only. Thats the reason it shows the error Uncaught ReferenceError: Facebook is not defined (see the console)
BTW, here's an equivalent example on plunkrenter link description here
You can simply bind the buttons with an id like
<a id="Facebook"class="btn btn-default">Facebook </a>
and access it using
$("#Facebook").on('click',function(){
alert('share on facebook');
})
EDIT:
You cannot have nested popover in bootstrap.However you can use the below two approaches
1)You can change the html inside the popover and display your email form
$('.popover-content').html($('#emailform').html())
Please refer to the fiddle attached for this appproach
https://jsfiddle.net/mohit181191/mxstLfnf/
2)You can open a modal on popover button click.
<a data-toggle="modal" data-target="#facebook"
class="btn btn-default">
Please refer to the below fiddle for this approach
http://jsfiddle.net/mohit181191/o35zqy7w/
Bootstrap not support the Nested popover
http://getbootstrap.com/javascript/#modals
Use this :
$('body').on('click',".btn-default", function(){
alert('share on facebook');
});
.btn-default change this to your button default id

using modal as submit confirmation

I currently have a form. As per below.
<form action="/process" id="formTest" name="formTest" enctype="multipart/form-data" method="POST">
<input type="text">
</form>
I added a modal to confirm on the submit.
<div class="modal fade" id="bondModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<p>Test;</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="accept" class="btn btn-primary">Accept</button>
</div>
</div><!-- /.modal-content -->
Now if the user submit, the modal of confirmation will be showed, and if the user subsequently choose accept, it will proceed the submit.
The problem is , the subsequent submit never works.
$('#formTest').submit(function(e) {
e.preventDefault();
$('#bondModal').modal('show');
$("#accept").click(function(e) {
$("#formTest").submit();
e.preventDefault();
$('#bondModal').modal('hide');
}
);
} });
The thing is if I change the code to reset instead of submit..it works for reset ..
$('#formTest').trigger('reset');
You've got yourself stuck in a loop.
When you fire the action:
$("#formTest").submit();
You are not submitting the form because you are calling your own function which prevents the default action:
$('#formTest').submit(function(e) {
e.preventDefault();
//do stuff
});
If you want to use the code you have currently you can do 1 of 2 things:
use one() on the submit function so it only fires once. This would require you to rebind on a reset or cancel
$('#formTest').one('submit', function(e) {
e.preventDefault();
//do stuff
});
Or unbind the submit function just before your forced submission.
$('#formTest').on('submit', function(e) {
e.preventDefault();
$("#accept").click(function(e) {
$('#formTest').unbind('submit');
$('#formTest').submit();
});
});
However, I would go a different way, and take the submit button out of the visible markup on the page. Just put an a tag in the form that you fire the open-modal function from upon click. Then you don't need to do any submission in your code, you just have the standard submit and reset buttons in the modal and they carry out their default behavior:
The markup:
<form>
<input type="text">
<a class="open-modal">Submit</a>
<div class="modal">
<h4 class="modal-title">Confirm?</h4>
<p>Test</p>
<input type="reset" class="btn btn-default">Cancel</button>
<input type="submit" class="btn btn-primary">Accept</button>
</div>
</form>
And the code:
$('a.open-modal').on('click', function(e) {
e.preventDefault();
$('.modal').fadeIn();
});
Much simpler. Hope this helps.
The issue is this line:
document.getElementbyname("formTest").submit();
There is no function called "getElementbyname()". It seems you are looking for document.getElementsByName() which returns a NodeList. In that case:
document.getElementsByName("formTest")[0].submit();
However, you can also use the document.forms array:
document.forms["formTest"].submit();
Finally, since your form has an ID, you could also use that:
document.getElementById("formTest").submit();

Modal Form Submission without refresh

I have a modal window that pops up when I want to add a new project to my dashboard. I have gotten it to work with jquery post however, I cannot prevent it from refreshing. What I want to do is after the project is added to the database, show a success message and close the modal window after few seconds and not refresh the page (parent page of modal).
Here is my modal
<div class="modal fade" id="add-project-dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Add a new Project</h4>
</div>
<div class="modal-body">
<h3>New Project:</h3>
<form class="form-horizontal" id="add-project-form" action="/projects/add" method="POST">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Project Name</label>
<div class="col-md-4">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="description">Project Description</label>
<div class="col-md-4">
<input id="description" name="description" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="project_state">Project State</label>
<div class="col-md-4">
<input id="project_state" name="project_state" type="text" placeholder="" class="form-control input-md">
</div>
</div>
</fieldset>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add-btn" class="btn" type="submit">Add</button>
</div>
</form>
</div>
</div>
Here is my project-dashboard.js
AddProject = function(){
$(document).ready(function() {
$("#submit").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
}
My views.py
class AddProject(webapp2.RedirectHandler):
def get(self):
template_values = {
#'greetings': greetings,
#'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), '../templates/project-add.html')
self.response.write(template.render(path, template_values))
def post(self):
project = Project()
project.name = self.request.get('name')
project.description = self.request.get('description')
project.project_state = self.request.get('project_state')
time.sleep(2)
project.put()
self.redirect('/projects')
I have tried removing the self.redirect('/projects') however that only takes me to a blank page that is /projects/add (that is the action in the form).
The issue is that you added .ready(foo) handler inside of the AddProject function. I suppose that document is loaded when AddProject is called.
Another issue is that in your HTML, the form has id add-project-form, so you should do $("#add-project-form") instead of $("#submit").
$(document).ready(function () {
$("#add-project-form").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
});
Take ready handler outside of the AddProject function and it should work (the submit handler is added).
Edit: After some debugging, the answer was to use the right id and proper placing of the javascript code, as noted by the comments.
For starters, a refresh is easy to avoid, just make sure to prevent the default event from running; since you're using jQuery, I would recommend doing return false to end the function, since it both 'prevents default' and 'stops propagation'.
So the first thing you should do is check if your javascript code is actually running and not erring in the middle of execution. If everything is fine there, the worst case is that the project is not actually added (server side error) but the page should not refresh.
Your server side code has nothing to do with the refresh (if it's being properly hijacked), so the response doesn't really matter, I would actually return the id of the new project (so you could provide a link for the newly created item or something like that), but i digress...
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok")) //custom validation dont copy
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular class button
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Now you should get no page refreshes on any of your modals if u follow these steps.

Categories

Resources