For some reason, the "window.location.href" function does not work for me, can't seem to find out why.
This is the code from index.php:
<div class="dropdown-menu">
<div style="width: 300px;">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-heading">
<label for="email">Email</label>
<input class="form-control" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required />
<p><br/></p>
Forgotten Password<input type="button" class="btn btn-success" name="login" id="login" value="Login">
</div>
</div>
<div class="panel-footer"></div>
</div>
</div>
And this is the function in the "action.php" file that is mentioned in the jQuery function:
<?php
if(isset($_POST["userLogin"])){
$email = mysqli_real_escape_string($con, $_POST["userEmail"]);
$password = md5($_POST["userPassword"]);
$sql = "SELECT * FROM user_info WHERE email = '$email' AND password = '$password'";
$run_query = mysqli_query($con, $sql);
if($run_query===false){
echo mysqli_error($con);
} else {
$row = mysqli_fetch_array($run_query);
$_SESSION["uid"]= $row["user_id"];
$_SESSION["name"]= $row["first_name"];
echo "welcome";
}
}
?>
This is the jQuery with the AJAX function:
$(document).ready(function(){
$("#login").click(function(event){
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "action.php",
method : "POST",
data : {userLogin: 1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "welcome"){
window.location.href = "profile.php";
}
/* alert(data);*/
}
});
});
});
notes:
As you can see in the jQuery function, there is this: "alert(data);". I wanted to look if it does work and put it on the screen without the "window.location.href" function to see that the "if" statement is correct, and it does work. Further more, when I go directly to the profile.php file, I see That the user is logged in, which means for me that the SQL functions is working fine, just it will not Re-Direct me to that (profile.php) page.
window.location.href expects an absolute url or a url relative to your domain (if it starts with a /).
If you only want to change the file part of your current path, you can use window.location.assign("profile.php")
If you want to redirect inside same domain
window.location.href = "/profile.php";
If you want to redirect to another domain
window.location.href = "http://www.antotherdomainname.com/profile.php";
Related
I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???
Don't use die.
Use echo or print.
Also set contentType to true.
I'm very new to ajax, and I'm trying to make a login script that doesn't require a page reload - it's working well except I attempt to set a session variable on the processing page, but no session variable is set.
My form:
<div class="form-bottom">
<form role="form" class="login-form">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="submit" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
<? echo $_SESSION['Name']; ?>
</div>
My ajax:
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+ username + '&password=' + password;
if(username=='' || password=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
});
}
return false;
});
});
</script>
My php script:
include('./static/config.php');
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
I was able to get it working the way I wanted it to.
Form:
<div id="box">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Log-in</h3>
<span id="error" class="error"></span>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div id="box" class="form-bottom">
<form class="login-form" action="" method="post">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="login" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
</div>
</div>
</div>
</div>
AJAX Code:
<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() {
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
else
{
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
PHP (ajax/login.php):
<?php
include("../static/config.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$result=mysqli_query($con,"SELECT Name FROM techs WHERE Username='$username' and Password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['Name']=$row['Name'];
echo $row['Name'];
}
}
?>
Since you've stated you're very new to Ajax, you start off pretty well.
There are however a couple of things to know how this works.
You want to avoid a page refresh, yet you don't print out any responses because you're not returning anything in the ajax request. You instead set a session variable which will show up at the next page request (so a refresh)
$.ajax({
type: 'POST',
url: 'ajax/login.php',
data: { username: $("#username").val(), password: $("#password").val() },
success: function (data) {
$('.form-bottom').html(data); // here we replace the form with output of the ajax/login.php response.
}
});
And for the PHP side of things:
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
if(($result = mysqli_query($con, $sql)) != false){ // always verify if your query ran successfully.
if(mysqli_num_rows($result)){ // or compare with == 1, but assuming a username is unique it can only be 1 so it equals to true.
echo mysqli_fetch_assoc($result)['name']; // index, columns, etc should always be lower cased to avoid confusion.
// Obviously you can store it in a session
// But for now just output the data so we can use it as our response.
// json is very usefull with sending large amounts of data.
}
}
The idea of Ajax is that you can request an update, but you need to update your page with javascript manually in order to make it work.
I think you forget to start the session.So start the session at the top of your script. Hope it will help.
session_start();
include('./static/config.php');
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
3 things you could try:
On the page where you are trying to set the session variable you would have to use proper php opening tags like <?php
Second thing is that you would have to put a value in your session like $_SESSION['hello'] = 'hello';
Third thing, on every page where you handle your session you would have to call <?php session_start(); ?> for it to work.
Goodluck!
I've got one big problem on only 1 page of a web site: Javascript doesn't want to be executed.
I tried to copy and paste from another web site i've done where it works perfectly... but not here. Maybe you can help me to figure out why it doesn't work...
I tried many ways, no ajax seems to work here.
Here is one of them, when i try to send a mail, i got no alert but {"reponse":"Mail sent corretly!"} instead, and the mail is corretly sent.
The submit button works! The page is refreshing, so i think the js is not executed. (i'd like to have the information without refreshing the page, like a normal ajax request).
I've tried to put the script (and the link to librairies) in the head, nothing changed.
Here is my code:
<--! Some HTML -->
<form class="form-horizontal myForm" method="post" action="contact.php">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="prenom" id="prenom" placeholder="First Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="nom" id="nom" placeholder="Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Mail" required >
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="objet" id="objet" placeholder="Object" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required >
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" name="message" id="message" placeholder="Your message" required>
</div>
<div class="form-group">
<label for="captcha" class="col-xs-12 col-sm-2 control-label">Captcha</label>
<div class="col-xs-6 col-sm-2">
<input type="text" class="form-control" id="captcha" name="captcha" required>
</div>
<div class="col-xs-2 col-sm-1">
<img src="form.php">
</div>
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="the-return"> </div>
</form>
<--! Some HTML -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script> <!-- Gem jQuery -->
<script>
$(document).ready(function() {
// On submit
$('.myForm').on('submit', function(e) {
e.preventDefault(); // Prevent default submit
var $this = $(this);
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And my php file:
session_start();
if(isset($_GET['err']))
{
$reponse = 'Mail not sent corretly!';
echo json_encode(['reponse' => $reponse]);
echo 'An error occurred, please try again
<form .... /form>'; //Same form
}
if(isset($_POST["captcha"]) && $_POST["captcha"]!="" && $_SESSION["captcha"]==$_POST["captcha"])
{
if(isset($_POST["nom"]))
{
if(preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['nom']))
{
if(isset($_POST["prenom"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['prenom']))
{
if(isset($_POST["objet"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['objet']))
{
if(isset($_POST["email"]))
{
if (preg_match("/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/",$_POST['email']))
{
$passage_ligne = "\r\n";
$emailAdmin = 'benjamin#parisbeaute.fr';
// Subject
$subject = $_POST['objet'];
// Headers
$headers = 'FROM: "'.$_POST['nom'].' '.$_POST['prenom'].'" <'.$_POST['email'].'>'.$passage_ligne;
$headers .= 'MIME-Version: 1.0'.$passage_ligne;
$headers .= 'Content-type: text/html; charset=UTF-8'.$passage_ligne;
$message = $_POST['message'];
// Formulaire
// Fonction mail()
mail($emailAdmin, $subject, $message, $headers);
echo '<div>Thanks a lot !</div>';
$reponse = 'Mail sent corretly!';
echo json_encode(['reponse' => $reponse]);
}}}}}}}}}
?>
Thanks in advance, sorry for my poor English, it's not my native language as you can see in my code.
Not sure why it did't work, but If you want sending the data using the $.ajax request, then stick to click event. Try change the code into this :
$(document).ready(function() {
// On button click
$('#my_button').on('click', function(e) {
var $this = $('.myForm');
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And change button type into :
<button type="button" class="btn btn-default" id="my_button">Submit</button>
I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).
I have the following situation:
index.html (which is my login page)
<div data-role="page" id="page_login">
<div id="wrapper_top_image">
<div id="top_image"></div>
</div>
<div data-role="content" data-theme="b">
<div id="landmark-1" data-landmark-id="1">
<form id="loginForm" onsubmit="return submitLogin();">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
</div>
<div data-role="footer">
<h4>© 2013 Company</h4>
<h6>Developed by Alex</h6>
</div>
and then my PHP Script that is going to check everything -> ps.. I fixed to avoid injection already! :
auth.php
$mysqli = new mysqli($mysql_hostname,$mysql_user, $mysql_password, $mysql_database);
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
$username =$_POST['username'];
$password =$_POST['password'];
$sql = "SELECT id, password, username FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$result = $mysqli->query($sql) or die( $mysqli->error() );
$rowN= mysqli_num_rows($result);
if($rowN==1){
$response_array['status'] = 'success';
} else {
$response_array['status'] = 'error';
}
echo json_encode($response_array);
}
$mysqli->close();
Finally my JQuery Script:
function submitLogin(){
jQuery.support.cors = true;
$.ajax({
url: 'http://www.xxxx.com/mobile/auth.php',
crossDomain: true,
type: "post",
data: $("#loginForm").serialize(),
success: function(data){
if(data.status == 'success'){
//alert("Granted Access!");
$.mobile.changePage("main.html");
}else if(data.status == 'error'){
alert("Authentication Invalid. Please try again!");
navigator.app.exitApp();
$.mobile.changePage("index.html");
}
}
});
};
Everything is working ok! Data is checked and if it is okay, is redirected to main.html (main page) otherwise the app pops up a window saying that the authentication is wrong, keeping the user in the same page.
Here is the dilemma: If users type the wrong credential trying to login again, any credential that he/she enter will be considerate invalid even if he/she entered the right one and the app will keep going back to the login page until I refresh the browser or end the app in case of running in the device.
Does anyone knows what may be happening?