Can I reload a div using jQuery? - javascript

I have an area made up in a navigation by bar some PHP code that either shows a inline login form or the users username. The login form is submit using jQuery so no page load is required to set the users session variables etc. but how can I get around not having to refresh the page so that the correct text is shown (i.e. the users username rather than the inline form)?
At the moment the login works seamlessly without having to refresh the page but I need to somehow update that area also.
<div id="divLogin">
<?php if (!logged_in()) { ?>
<div class="form-group">
<input type="text" placeholder="Email" class="form-control" id="user">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control" id="pass">
</div>
<button type="button" class="btn btn-success" id="login">Sign in</button>
<button type="button" class="btn btn-primary" id="register">Register</button>
<?php } else { ?>
<div class="form-group">
<p>You are logged in as <strong><?php echo $_SESSION['user']; ?></strong></p>
</div>
<?php } ?>
</div>

You can do that using load() function or by using AJAX.
$('.your_button').on('click', function(){
$('#divLogin').load('your_page_url_here');
});

Related

How to reload this form without refreshing whole page?

I am using "Send Email from a Static HTML Form using Google Apps Mail" on my static site. But when I submit a form i have to refresh the whole page to submit another mail. If I don't reload the page success text don't vanish and send button don't work. So i am asking is there any way to refresh my form section without refreshing the whole page? please help me how to do it.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container mail text-center justify-content-center mt-5">
<div class="row">
<div class="col-12">
<h3>Contact Me Now!</h3>
<hr>
</div>
<div class="col-md-12 col-xs-12 form">
<form method="post" role="form"
action="https://script.google.com/macros/s/AKfycbwtLbTgUDGQxi9FY8Jks6bJs3TnYPBNU7rvO8b8_zrdyD4Pa6g/exec"
method="post" role="form" class="gform " data-email="">
<div class="form-row">
<div class="col form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name"
data-rule="minlen:4 " data-msg="Please enter at least 4 chars " required="true" />
</div>
<div class="col form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email"
data-rule="email " data-msg="Please enter a valid email " required="true" />
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject"
data-rule="minlen:4 " data-msg="Please enter at least 8 chars of subject "
required="true" />
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required"
data-msg="Please write something for me " placeholder="Message " required="true"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-success w-100 submit">Send Message</button>
</div>
<div style="display:none" class="thankyou_message">
<div class="alert" role="alert"> <em>Thanks</em> for contacting me!
I will get back to you soon!<br>
<i class="fas fa-sync fa-spin"></i>
</div>
</div>
</form>
</div>
</div>
</div>
<script data-cfasync="false" type="text/javascript"
src="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-without-server/master/form-submission-handler.js"></script>
If the form is refreshing the page, you'll need to use preventDefault to cancel its default behaviour then use reset() to reset the form.
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
[...form.elements].forEach(input => console.log(`${input.name}: ${input.value}`)); // Not Important
form.reset();
});
<form method="POST">
<input type="text" name="name" placeholder="name">
<input type="password" name="password" placeholder="password">
<button type="submit">Submit</button>
</form>
In JavaScript there is a function for forms which will reset the form clearing all the data in it, ready for another submit. This can be accomplished by running a JavaScript function on submit. This requires a couple changes in your code.
Firstly, we need to change this:
<button type="submit" class="btn btn-success w-100 submit">Send Message</button>
to this:
<button type="button" onclick="submitForm1()" class="btn btn-success w-100 submit">Send Message</button>
Once done, we can add some JavaScript to your page. If you have a JavaScript file linked to the page already, you can just add this code to that.
function submitForm1() {
let form = document.getElementsByClassName("gform");
form.submit();
form.reset();
}
You can also use document.getElementById("[id]"); and add an ID to your form. This is also preferable.
The first thing that comes to mind it's do all this on js so you can through ajax request send what you want. But I think it's not what you're looking for. You can't send data from page without refreshing, that's how it's work, php or html with some functional. You can change ...
<button type="button" class="btn btn-success w-100">Send Message</button>
... and collect all data by JavaScript and send it through ajax.

Display a progress bar when a search submit button is clicked until search results are loaded

I look for a way to display a progress bar in the following scenario in PHP:
search button is clicked at search.php
display a progress bar (showing percentage) over the page (a small popup window at the centre, for example)
Just before the search results are displayed at result.php, stop and hide the progress bar
Currently, JQuery and Bootstrap are available, but others can be added. I like simplicity. Do you have a good idea? Cheers!
search.php
<form class="form_container validationForm" action="result.php" method="post">
<input type="text" class="form-control validationInput" name="search" placeholder="Type a search keyword"><br>
<button class="btn btn-primary" type="submit" >Search</button>
</form>
result.php
<main>
<div class="container">
<div class="row">
<div class="col-sm-2">
<div class="col-sm-12">
// Below is the query function
<?php include('_partials/query_functions.php'); ?>
</div>
</div>
</div>
</div>
</main>
add this in result.php
<div class="spinner-border" id="loader" role="status">
<span class="sr-only">Loading...</span>
</div>
add attribute id your submit button
<button class="btn btn-primary" id="submit" type="submit" >Search</button>
And in your javascipt file
$("#loader").hide();
$("#submit").on('click', function(){
$("#loader").show();
})

How to implement cookies on my login using php"

This is homework - I'm trying to make a login with cookies so that the browser remembers that you previously logged in but I have no idea how to implement it into my code. And to logout how can I delete cookies to login again?
<?php
session_start();
require_once('conexion.php');
$usuario=$_POST['usuario'];
$contrasena=$_POST['pass'];
$con=md5($contrasena);
$consulta= "SELECT * FROM usuarios WHERE usuario='$usuario' and contrasena='$con'";
$result= mysqli_query($link, $consulta);
$contador=0;
while($fila = mysqli_fetch_array($result))
{
$contador=1;
//cambiar por cookies
$_SESSION['id']=$fila['id'];
$_SESSION['nombre']=$fila['usuario'];
}
if($contador==0)
{
echo '<script type="text/javascript">window.location.assign("login.html");</script>';
}else{
echo '<script type="text/javascript">window.location.assign("index.html");</script>';
}
?>
This is my form:
<form action="validacion.php" method="POST">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Usuario" name="usuario" id="username">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Contraseña" name="pass" id="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">enter</button>
</div>
<!-- /.col -->
</div>
</form>
You should remember that sessions and cookies are not the same thing:
What is the difference between Sessions and Cookies in PHP?
Still with me?
You have to "set" a cookie on your validacion.php:
$username = $_POST['usuario']; //I would highly recommend that you clean the input.
setcookie("usuario", $username);
On your index.html page simply convert it to a php file by adding the php at the top of the HTML. Add a php listener that detects a user that is logged in. Please also remember to change your index.html to index.php
<?php
if (isset($_COOKIE["usuario"])) {
echo "Welcome ".$_COOKIE["usuario"];
}
?>
On your log out simply "unset" the cookies after making sure they exist.
if (isset($_COOKIE['usuario'])) {
unset($_COOKIE['usuario']);
}
I would highly recommend you lookup:
http://php.net/manual/en/function.setcookie.php &
http://php.net/manual/en/function.unset.php

PHP :unable to check if a form is submitted

I am using a form in php file inside a modal window like this
<div class="modal-body">
<form method="post" action="m.php">
<div class="form-group">
<lable>Name</lable>
<input type="text" class="form-control" required="required">
</div>
<div class="form-group">
<lable>Email</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Details</lable>
<input type="text" class="form-control" required>
</div>
<div class="form-group">
<lable>Message</lable>
<textarea name="" id="" class="form-control"></textarea>
</div>
<div class="form-group">
Submit
</div>
</form>
</div>
file name is m.php now when i press the submit button it doesn't detect form submission
<?php
if( ($_SERVER['REQUEST_METHOD'] == 'POST')){
die("form submitted");
}
?>
i tried $_POST['submit'] as well kindly help me whats wrong with it
This is because you dont press a submit button, you press a link called submit. Try replacing it with <input type="submit" value="Submit" />.
Also, your check wether your form has been submitted uses a dangerous method. If you have multiple forms to be handled in your code, it will catch them all. A better approach would be:
if( isset($_POST['nameOfSubmitbutton']) ){}
// because you can now easily do:
if( isset($_POST['completelyDifferentButton']) ){}
If you want to keep the anchor (I advice against it), you can use javascript to fake the submit for you:
document.getElementById('yourAnchor').onclick = function(){
document.getElementById('yourForm').submit();
}
// Or if you have jQuery:
$('#yourAnchor').on('click', function(e){
e.preventDefault();
$(this).closest('form').submit();
});
The submit button you are using is pointing towards the same url, can you try something like?
<input class="btn btn-default" type="submit" value="Submit">
and then try to see if the form is submitted from PHP.
And i also would recommend that you use some framework for this to handle sql injections and/or other exploits.
Wrong use of form submit.
<div class="form-group">
Submit
</div>
You should use it like:-
<div class="form-group">
<input type="submit" class="btn btn-default" name="submit" style="background: #eee; width:100px;display: block;margin-left:auto;" value="Submit"/>
</div>
Hopefully this will solve the issue.

Dynamic change form using jQuery, AJAX

I've got little problem because I don't really know how should I do this.
Let's say I've got this HTML form:
<form action="#" method="post">
<select name="change_reason" required>
<option value="">Please choose</option>
<option value="1">Getting apple</option>
<option value="2">Walking outside</option>
<option value="3">Other</option>
</select>
<input type="submit" value="Submit">
Depending on the selected answer I want to present second (different) form but without reloading the page (AJAX) and which would be submitted to PHP script. So let's say someone chose 'Getting apple', hit Submit so then the form would changed to:
<form action="/my_script.php" method="post">
<p>Getting apple, OK!</p>
<textarea name="apples" rows="2">So I am getting some apples</textarea>
<input type="submit" value="Submit">
Let's say someone chose 'Walking outside' so the form would change to:
<form action="/my_script.php" method="post">
<p>Walking outside, OK!</p>
<textarea name="apples" rows="2">So I will walk outside now</textarea>
<input type="submit" value="Submit">
Can anyone please tell me how can I get this done?
Just place a switch on your script and load form content from the ajax response.
<form action="#" method="post">
<div class="dynamic-inputs">
<select name="change_reason" required>
<option value="">Please choose</option>
<option value="1">Getting apple</option>
<option value="2">Walking outside</option>
<option value="3">Other</option>
</select>
</div>
<input type="submit" value="Submit">
</form>
<script>
$(document).ready(function(){
$("form").submit(function(){
var myForm = $(this);
var data = $(this).serializeArray();//serialize form inputs and pass them to php
$.post("/myscript.php",data,function(data){
myForm.find(".dynamic-inputs").html(data);
});
return false;
});
});
</script>
While you can place a switch on your PHP script and return a value based on the change_reason input parameter
<?php
$change_reason = isset($_REQUEST["change_reason"]) ? $_REQUEST["change_reason"] : null;
if($change_reason){
switch ($change_reason) {
case 1:
echo '<p>Getting apple, OK!</p>
<textarea name="apples" rows="2">So I am getting some apples</textarea>';
break;
case 2:
echo '<p>Walking outside, OK!</p>
<textarea name="apples" rows="2">So I will walk outside now</textarea>';
break;
}
}
?>
Steps
1)Add each form into a modal or in lightbox
2)open each modal onchange event of select box
3)Write ajax for each individual form and close modal after submission.
$(":select[name='change_reason']").change(function() {
/*If you are using Bootstrap the create sprate modal for this.
For more details
http://getbootstrap.com/javascript/#modals
Add each form in separate modal and open that on by giving name to each form
*/
$('#' + $('select[name=selector]').val()).modal()
});
/* Write Ajax for sumission of indivusal forms and close that modal after submission of each form
http://api.jquery.com/jquery.ajax/
Take a look at it.
*/
<!-- Add this forms into modal and give it a id -->
<div class="modal fade" id="same-id-as-value-of-select-box">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<form action="/my_script.php" method="post">
<p>Getting apple, OK!</p>
<textarea name="apples" rows="2">So I am getting some apples</textarea>
<input type="submit" value="Submit">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- Add this forms into modals -->
<form action="/my_script.php" method="post">
<p>Walking outside, OK!</p>
<textarea name="apples" rows="2">So I will walk outside now</textarea>
<input type="submit" value="Submit">
Hope this will Help you
If the forms are reasonably small like the ones you presented. I would just load them on the page in separate hidden div's. Then as stated in the comments, use a submit handler to determine which form to show on the page and hide the initial form.
If the forms are "too long" for this concept, I would definitely use jQuery AJAX to submit the form data and load the new form into a destination div on the page. . . maybe even replacing the existing form.

Categories

Resources