javascript ajax login form handling - javascript

Im working on an ajax form to show errors without reloading the page. So if everything is good, the user we be redirected to home.php. At the moment the user will also be redirected when there is an error.
This is my code so far:
index.php:
<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>
login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>

Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);

Throw a 401 error if it fails login, this will stop the redirect.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
?>

do you know jquery ?
jquery w3 school search on google
avaible
$('#data-div-id').load('www.sdasd .php ? or whatevver');
function tmp_func_sil_ok(e){
$.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}

Related

PHP and jQuery/Ajax auto logout with header(Location)

In my Dashboard.php I call an Ajax Request every 800ms that fetches data from a php file and changes the inner html of an element on my Dashboard.php.
I use it to display a 60 seconds coundown since last activity. Once it reaches 0 it should send the user to logout.php and from there to index.php.
The problem now is that I stay on my page and index.php gets inserted into my div. How can I force it to a site refresh?
Dashboard.php
<script type="text/javascript">
setInterval(function(){
getSessionEnd();
}, 800);
</script>
app.js
var st = document.getElementById("sessiontime");
if (typeof(st) != 'undefined' && st != null){
sessionEnds();
}
function getSessionEnd() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("sessiontime").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./assets/ajax/sessionEnds.php");
xhttp.send();
}
SessionEnds.php
<?php
session_start();
require_once '../../includes/datacon.php';
global $pdo;
$sql = $pdo->prepare('SELECT * FROM userdata JOIN user ON user.id = userdata.uid WHERE username=?');
$sql->bindParam(1, $_SESSION['user']);
$sql->execute();
$sqlu = $sql->fetch( );
$timeS = strtotime($sqlu['lastseen']);
$timeE = strtotime(date("Y-m-d H:i:s", strtotime("+". 1 . " minutes", $timeS)));
$timeD = $timeE - time();
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%i minutes and %s seconds');
}
$timeD = secondsToTime($timeD);
if($timeE < time()){
Header('Location: ../../includes/logout.php');
exit();
} else {
echo $timeD;
}
?>
change to
if($timeE < time()){
echo "0"; // send 0 response
} else {
echo $timeD;// send time
}
also
if (this.readyState == 4 && this.status == 200) {
if (this.responseText=="0" || this.responseText==" 0"){
window.location("logout.php");// got to logout page
}
else
document.getElementById("sessiontime").innerHTML = this.responseText;
}
Change the code as this
give the correct path to logout page..
You need to go to the logout page from the current page in browser.
PHP is server side and you'd like to force the client to reload, so, it looks like you need to add something in jscript to force the client to refresh the page, like changing the window.location, or location.reload
window.location=<your target>
//or
location.reload()
To add in logout.php I presume.

Getting values from php to ajax request with Javascript

Greetings to everyone,
I'm a beginner in javaScript and I am kinda new to ajax... I am trying to get a return value from php like error message or success message and pass it to the user. Any kind of suggestion is welcome
PS: Everything was working when I have not started using ajax
$('button[post-request]').click(function() {
// event.preventDefault();
var request, address, form, response;
address = $('form').attr('action');
response = document.getElementById("return");
$('input').prop('disabled', true);
request = new XMLHttpRequest();
request.open('POST', address, true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
response.innerHTML = this.responseText;
console.log(request.responseText);
}
else{
console.log(request.statusText);
}
}
request.send();
});
Here is my php code
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller
{
public $data, $uid;
public function __construct()
{
parent::__construct();
// loading models
$this->load->model(['logic/auth_action'=>'auth','validations/auth_validation'=>'verify']);
// store ecncrypted user uid in a session
$this->uid = $this->session->userdata('uid');
$this->data['user'] = $this->usr->fetch_all_information($this->uid);
}
public function login()
{
$this->func->is_logged_in(true, 'dashboard');
$this->data['title'] = "Sign in";
if(!empty($_POST) && $this->input->is_ajax_request()):
// validating users inputs coming from the form
$user_inputs = $this->verify->authenticate_userInputs('login');
// checking if no error isset && carry on with the next step
if(!isset($user_inputs['error_msgs'])):
// performing neccessary action after validating
$return = $this->auth->login($user_inputs);
else:
// store error for $return variable if there is any && pass it on
$return = $this->func->return_validation_error($user_inputs);
endif;
// retrieve the error stored and display it to user
print $this->func->fetch_message('error',$return);
endif;
// this display login page
$this->load->view('auth/login', $this->data);
}
}

how to send data to php file then echo a message

I am trying to send data to php file then echo the word "Hello!" when i call a function in javascript, however, no message appear, i guess there is en error in the calling, can you guide me please?
Here is my code:
Javascript:
function asyncpost_deviceprint() {
var xmlhttp = false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
else if (!xmlhttp) return false;
xmlhttp.open("POST", "http://localhost/Assignment/insert.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("userAgent" + userAgent()); /* fire and forget */
return true;
}
PHP:
<?php
echo "Hello!";
?>
echo "Hello!";
won't display any message because in Ajax request this function sends a respond to Javascript.
If you want to display sth on the screen with PHP instead of Ajax you should use:
window.location.href="path to your php site"
it will redirect you to php file and display Hello!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
document.body.innerHTML += xmlhttp.responseText;
}
}
};
Add this before xmlhttp.send
It will literally just stick the php echo text after the last thing in the document.

how to handle php echo'ed message in ajax.

I am creating an AJAX+PHP submit form, for example purposes. For this, I will need Ajax, PHP and index.html file to write into the inputs. The problem is that, when I submit I have no way of redirecting a page, so I created this hack. (since page redirect get permission from the PHP script first) otherwise show error.
AJAX
function submit_form(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success'){
location.href = '/success';
}
//
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
And this is my PHP.
<?php
echo "/success";
if($_GET){
}else{
echo "error, no value found";
}
as you can see, this allows me to redirect the page, as the javascript will read the "/success" and redirect the document, but one problem with this is that, I don't like using echo, because the page actually shows "success" before redirect. I don't want it to show anything to the page.
Change your echo statement to return json_encode(), then in your JS code, you can parse it using JSON.parse();
In your PHP removes the slash of this line: echo "/success";
And in your java script code, add a else sentence before print error:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
if(xmlhttp.responseText.trim() == 'success') {
location.href = '/success';
}
else {
var e = doc.querySelector('.form-error').innerHTML = xmlhttp.responseText;
}
}
}

Undefined $_POST after xmlhttp request

My code makes an xmlhttp request to a php file, sending an ID so that a record can be identified and deleted from the database. However, when performing the delete query, I'm get an error saying 'comicID' is undefined (the variable using the ID value sent by POST). I'm not sure how to make sure it is defined correctly. Currently, the error I'm getting back from error handling is: "No comic supplied." and the error I get when removing the ISSET section of code is: "Error. Pages in comic not deleted." As it stands, the delete query doesn't work.
Javascript:
function delComic()
{
var radioButtons = $("#listID input:radio[name='comicList']");
var radioID = radioButtons.index(radioButtons.filter(':checked'));
console.log(radioID);
if (radioID < 0)
{
window.alert("You must select a comic before deleting.");
}
else
{
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php?comicID="+radioID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
}
PHP:
<?php
if (isset($_POST["comicID"]))
{
$comic = $_POST["comicID"];
$dir = 'comics/'.$comic.'/';
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
include_once('includes/conn.inc.php');
mysqli_query($conn, "DELETE FROM serieslink WHERE comicID = '$comic'");
$query = ("DELETE FROM page WHERE comicID = '$comic'");
if (!$result = mysqli_query($conn, $query))
{
echo ("Query1 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
$dirHandle = opendir($dir);
while($file = readdir($dirHandle))
{
if(!is_dir($file))
{
unlink("$dir"."$file");
}
}
closedir($dirHandle);
rmdir($dir);
$query2 = ("DELETE FROM comic WHERE comicID = '$comic'");
if (!mysqli_query($conn, $query2))
{
echo ("Query2 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
echo ("The selected comic was successfully deleted.");
}
else
{
echo ("Error. Comic not deleted.");
}
}
}
else
{
echo "Error. Pages in comic not deleted.";
}
}
$conn->close();
}
else
{
$comic = null;
echo "No comic supplied";
}
?>
With POST you do your Ajax request different that with GET. The query string is an argument to the send() function rather than part of the url, and you leave off the ?:
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send("comicID="+radioID);
Edit:
You also really should urlencode the parameter values, if they can contain spaces, etc. And to circumvent possible browser caching you can add a parameter with the time:
var d = new Date();
xmlhttp.send("comicID="+encodeURIComponent(radioID)+"&ts="+d.getTime());
There's no need to read that timestamp param on the server-side; its only to trick the browser.
Change the three first lines to, and everything should work fine.
if (isset($_GET["comicID"]))
{
$comic = $_GET["comicID"];
I actually solved it myself by accident. It turns out the error is that the program is halting at the point that it tries to delete all pages associated with a comic. When it is presented with an already empty comic, it tries to delete nonexistent records. Manually adding a page to the comic and THEN trying to delete the comic outright worked perfectly.
So basically, I just need error handling for empty comics.
Thanks for the pointers regarding POST, however.

Categories

Resources