ReferenceError: toastr is not defined - php

I´ve been trying to show toast notifications on my page with toastr.js, but this error keep showing:
The error
I already included jquery and both js and css, but didn´t anyway, this is the code:
EDIT: when i try to show the toast notifications directly on the html code, it works fine, but when i call them inside of the php function, the error keep appearing
<?php
// WHEN I TRY TO SHOW THE ALERT WITH THIS PHP FUNCTION, IT DOESN'T WORKS!
function cms_alert($message, $type) {
switch ($type) {
case "info":
echo "<script>toastr.info('INFO!');</script>";
break;
case "success":
echo "<script>toastr.success('SUCCESS!');</script>";
break;
case "warning":
echo "<script>toastr.warning('WARNING!');</script>";
break;
case "error":
echo "<script>toastr.error('ERROR!');</script>";
break;
}
}
?>
<?php
// THE ERROR IS HAPPENING HERE!
} else {
// Senão, mostra a página de login
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = ($_POST['password']);
// Caso deixe todos os campos em branco, uma mensagem de erro é mostrada
if (empty($username) or empty($password)) {
cms_alert("Preencha todos os campos!", "error");
} else {
if ($username == $admin_username and $password == $admin_password) {
// Usuário digitou login e senha corretos
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
} else {
// Usuário digitou login e senha incorretos
cms_alert("Nome/senha esta incorreto!", "error");
}
}
}
?>
<html>
<head>
<meta charset="utf-8">
<title>tinyCMS - Login</title>
<link rel="stylesheet" href="../assets/style.css">
<link rel="stylesheet" href="../assets/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
</head>
<body>
<center>
<h1><?php echo $site_name; ?></h1> <!-- Mostra o titulo do site -->
<h5><?php echo $site_description; ?></h5> <!-- Mostra a descrição do site -->
<hr/>
<h4>Digite seu login e senha para continuar:</h4>
<!-- LOGIN -->
<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Usuário" />
<input type="password" name="password" placeholder="Senha" />
<input type="submit" value="Login" />
</form>
</center>
<hr/>
<?php echo $site_footer_admin; ?>
</body>
<!-- WHEN I USE THE CODE DIRECTLY ON THE HTML FILE, IT WORKS FINE! -->
<script>toastr.error('Hello World!');</script>
</html>

You have whitespace in the link which causes a 404.
You put the javascript in a stylesheet tag and the CSS in a javascript tag.
You must include jQuery.
Try this:
<?php
function cms_alert($message, $type) {
switch ($type) {
case "info":
echo "<script>toastr.info('INFO!');</script>";
break;
case "success":
echo "<script>toastr.success('SUCCESS!');</script>";
break;
case "warning":
echo "<script>toastr.warning('WARNING!');</script>";
break;
case "error":
echo "<script>toastr.error('ERROR!');</script>";
break;
}
}
?>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
</head>
<body>
<?php cms_alert("Hello World!", "success"); ?>
</body>
</html>

Related

Button redirecting to php file

when i press the 'continue' button i'm redirected to form's php functions file ( localhost/install/hamburgher.php ),but that must check if the code is correct or it will display an error.
hamburgher.php (functions on clicking of the button):
<?php
session_start();
// connect to database
$db = mysqli_connect('localhost', 'root', '');
mysqli_select_db($db,"licensecode");
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
$errors = array();
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="alert alert-danger">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
if (isset($_POST['btn_lic']) && $_POST['btn_lic'] == 1))
{
checkkey();
}
else
{
array_push($errors, "License key is invalid.");
}
// USER
function checkkey(){
global $db, $username, $errors;
// grap form values
$key = e($_POST['key-get']);
// make sure form is filled properly
if (empty($key)) {
array_push($errors, "A license key is required.");
}
// attempt login if no errors on form
if (count($errors) == 0)
{
$password = md5($password);
$query = "SELECT * FROM licenses WHERE code='$key' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1)
{ // found
// check
$keycode = mysqli_fetch_assoc($results);
if($keycode['expired'] == 1)
{
array_push($errors, "This license has expired.");
}
else
{
header('location: step_4.php');
}
}
else
{
array_push($errors, "License key is invalid.");
}
}
else {
array_push($errors, "Some errors there.");
}
}
Form file - step_3.php:
<?php
include('hamburgher.php');
require_once("settings.inc");
if (file_exists($config_file_path)) {
header("location: ".$application_start_file);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo $application_name;?> Instalation Wizard - 3</title>
<link rel="icon" href="images/brand/favicon.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="styles/basic.css">
<link href="https://fonts.googleapis.com/css?family=Muli&display=swap" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="styles/bootstrap.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<center>
<div class="card">
<img src="../images/brand/logo_wide.png" alt="Thos Host Complete Solutions">
<form method="post" action="hamburgher.php">
<input type="hidden" name="submit" value="step2" />
<div class="container">
<b><div style="font-family: 'Muli', sans-serif;">Step 3: Insert your license key</div></b><br>
<div class="form-group">
<label for="key-get" style="margin-right: 80%">Code:</label>
<input type="text" class="form-control" name="key-get" placeholder='38904ADSUFH8ADS7FH8ASHFASHF8ASHUFHA8SUFHU8ASHF8UHA' size="30">
</div>
</div>
<?php echo display_error(); ?>
<span class="step_active" >1</span>
<span class="step_active">2</span>
<span class="step_active">3</span>
<span class="step_inactive">4</span>
<span class="step_inactive">5</span>
<button type="submit" class="button button_black" name="btn_lic" value="1" style="margin-left : 60%; color: white; text-decoration: none; font-family: 'Muli', sans-serif;"><b>Continue</b></button>
</form><br>
</div>
</center>
<?php include_once("footer.php"); ?>
</body>
</html>
The code must display an error if:
- the input code is null;
- the input code is expired;
- the input code is not existing;
on displaying of error,the page must be same,but with <?php echo display_error(); ?> on the page,there will be the error message.
You must be redirected on page step_4.php if the code is found in database and is not expired
I know,i know,i will modify the code to avoid SQL injections,this is a beta code.
Thanks.
The quickest way to solve the issue would be to move the code from hamburgher.php to step_3.php and then remove the action for the form so it goes back to the same page.

HTML Form sends GET instead of POST (XAMPP, Apache, localhost)

I've looked up other questions with possible solutions to my problem, but they don't seem to work for me.
According to the Network console in Firefox, my contact form sends GET when I set the method to POST.
I have checked my HTML code for errors, but can't find any; no unclosed forms, divs, etc. I've checked the syntax for my php, too.
I also tried setting the submit button to <button type="submit" formmethod="post" formaction="form-to-email.php" name="submit" class="button">Und los</button>'but it doesn't help, either.
EDIT: Here's my complete HTML code for this page:
<!DOCTYPE html>
<html lang="" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="placeholder">
<meta name="keywords" content="placeholder">
<meta name="author" content="placeholder">
<title>MADesign.</title>
<link rel="author" href="robots.txt" />
<link rel="author" href="humans.txt" />
<!-- CSS -->
<link rel="stylesheet" href="css/maincss.css">
</head>
<body>
<div id="holder">
<!-- page header -->
<div class="bg-image-small">
<div id="main_menu">
<header id="page_header">
<img src="images/mad-logo-300px.png" alt="mad logo" id="mad-logo">
</header>
<!-- END page header -->
<!-- main navigation -->
<nav id="main-nav">
<ul>
<li>home</li>
<li>link1</li>
<li>link2</li>
<li>link3</li>
<li>kontakt</li>
<li>impressum</li>
</ul>
</nav><!-- END main navigation -->
</div><!-- END main menu -->
</div><!-- END background image -->
<!-- main content -->
<main>
<!-- contact form -->
<form id="my-form" name="myForm" action="/form-to-email.php" method="post">
<h2>Let's get in touch.</h2>
<p>Schick mir eine Email an abc#placeholder.de oder nutze mein Kontaktformular.</p>
<div class="gender">
<input type="radio" name="titles" value="male" id="mr"
<?php if($titles == "male") echo "checked" ?>>
<label for="titles">Herr</label>
<input type="radio" name="titles" value="female" id="mrs"
<?php if($titles == "female") echo "checked" ?>>
<label for="titles">Frau</label>
<input type="radio" name="titles" value="nonbinary" id="mx"
<?php if($titles == "nonbinary") echo "checked" ?>>
<label for="titles">Hallo</label>
<input type="radio" name="titles" value="person" id="person"
<?php if($titles == "person") echo "checked" ?>>
<label for="titles">Person</label>
<div class="errormsg">
<?php echo $errors['titles']; ?>
</div>
</div>
<div class="form-block">
<label for="usrname">Name:</label><br>
<input type="text" name="usrname" id="usrname" class="styleinput" size="20" maxlength="30" value="<?php echo htmlspecialchars($usrname) ?>">
<div class="errormsg">
<?php echo $errors['usrname']; ?>
</div>
</div>
<div class="form-block">
<label for="email">Email:</label><br>
<input type="text" name="email" id="email" class="styleinput" size="20" maxlength="30" value="<?php echo htmlspecialchars($email) ?>">
<div class="errormsg">
<?php echo $errors['email']; ?>
</div>
</div>
<div class="user-input form-block">
<label for="user-input">Nachricht:</label><br>
<textarea class="styleinput" id="message-me" name="usrmsg" rows="4" cols="50" value="<?php echo htmlspecialchars($usrmsg) ?>"></textarea>
<div class="errormsg">
<?php echo $errors['usrmsg']; ?>
</div>
</div>
<button type="submit" formmethod="post" formaction="/form-to-email.php" name="submit" class="button">Und los</button>
<input type="reset" name="reset" class="button" value="Nochmal neu..." onclick="emptyMsg()">
<div id="message"></div>
</form>
<!-- END contact form -->
</main>
<!-- END main content -->
<!-- footer -->
<footer>
<p>&copy2019 placeholder</p>
</footer><!-- END footer-->
</div><!-- END holder -->
<!-- JavaScript and jQuery -->
<script src="https://code.jquery.com/jquery-3.4.0.min.js" integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg=" crossorigin="anonymous"></script>
<script src="js/mainjs.js"></script>
</body>
</html>
This is the PHP (saved in the same directory as kontakt.php):
<?php
$titles = $usrmsg = $usrname = $email = "";
$errors = array("email"=>"", "usrname"=>"", "usrmsg"=>"", "titles"=>"");
if(isset($_POST["submit"])){
//check Email
if(empty($_POST["email"])){
$errors["email"] = "Bitte Email Adresse angeben.";
} else {
$email = $_POST["email"];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors["email"] = "Die Email Adresse sollte gültig sein.";
}
}
//check name
if(empty($_POST["usrname"])){
$errors["usrname"] = "Wie heißt du?";
} else {
$usrname = $_POST["usrname"];
$usrname = filter_var($usrname, FILTER_SANITIZE_STRING);
if(!preg_match("/^[a-zA-Z\s]+$/", $usrname)){
$errors["usrname"] = "Sorry! Der Name darf nur Buchstaben und Leerzeichen enthalten.";
}
}
//check message
if(empty($_POST["usrmsg"])){
$errors["usrmsg"] = "Hier sollte etwas Text stehen. Muss ja nicht viel sein.";
} else {
$usrmsg = $_POST["usrmsg"];
$usrmsg = filter_var($usrmsg, FILTER_SANITIZE_STRING);
}
//check titles
$titles = $_POST["titles"];
if ($titles==NULL) {
$errors["titles"] = "Welche Ansprache darf ich verwenden?";
}
}
?>
EDIT: Here's the JS for client-side form validation (it's not a finished version, some validations are still missing/may get changed, but so far it's working as it should):
var myForm = document.forms.myForm;
var message = document.getElementById('message');
myForm.onsubmit = function() {
//get IDs for the title
var mr = document.getElementById('mr');
var mrs = document.getElementById('mrs');
var mx = document.getElementById('mx');
var pers = document.getElementById('person');
//get ID for the textarea
var usrInput = document.getElementById('message-me');
if (myForm.usrname.value == "") {
message.innerHTML = "Moment! Wie heißt du?"
return false;
} else if (usrInput.value == "") {
message.innerHTML = "Das Nachrichtenfeld sollte nicht leer sein..."
return false;
} else if (email.value == "") {
message.innerHTML = "Wie lautet deine Email Adresse?"
return false;
} else if (usrInput.value.length < 10) {
//check min length of textarea
message.innerHTML = "Die Nachricht sollte etwas länger sein..."
return false;
} else if (!mr.checked &&
!mrs.checked &&
!mx.checked &&
!pers.checked) {
message.innerHTML = "Welche Ansprache darf ich verwenden?"
return false;
} else {
message.innerHTML = "";
return true;
}
I'm using XAMPP (Apache) to test this via localhost.
How can I get the form to send POST, not GET? Did I overlook syntax errors, typos or are there errors with my variables that I can't find? Thx for any input.
This happens sometimes. I don't think I am experienced enough to give you a perfect solution but here's a bunch of try outs you can implement:
Try to write the "post" keyword in capitals (like "POST").
Sometimes the xampp server does not reflect changes even after you save and refresh. Try refreshing with (ctrl+F5). This imposes a hard refresh causing the xampp server to reload all the resourses.
Try restarting the xampp server.
Please revert if anything was helpful....

Retrieve links from an Access db with PHP

i'm having an issue listing up the links I have in an access database.
I'm new to this so even if i searched thru' the answered questions I couldn't find anything to help me out. I have a search form that when you type, it automatically filters the table i'm accessing from the databse. But i get this error when i'm accessing the field where I have the links listed: "Notice: Undefined index: Título in C:\xampp\htdocs\buscar.php on line 21"
Bassically what I have to do is a search form where you search in a category and all the pdfs related to that category would show up and should be clickable so you can read the one you're interested in.
The code I have is this, where Ser_presenta is the category and Título is where the url's are listed.
Index php page:
<!DOCTYPE html>
<html lang=es>
<head>
<meta charset="utf-8">
<title>Protocolos</title>
</head>
<body>
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script>
<script type="text/javascript">
function buscarq() {
var buscarTxt = $("input[name='Buscar']").val();
$.get("buscar.php", {buscarVal: buscarTxt}, function(output){
$("#output").html(output);
});
}
</script>
<center>
<h2> Protocolos Médicos </h2>
<form action="protocolosphp.php" method="get" enctype="multipart/form-data">
<input type="text" name="Buscar" placeholder="Buscar protocolos..." onkeyup="buscarq();" size="50"/>
<input type="submit" value=">>" />
</form>
<div id="output">
</div>
</center>
</body>
</html>
Php that should retrieve data from the databse:
<?php
$conexion = odbc_connect ("ProtocolosIndex", "", "")
or die ('No se pudo conectar a la base de datos');
$output = '';
//collect
if(isset($_GET['buscarVal'])) {
$buscarq = $_GET['buscarVal'];
$query = odbc_exec($conexion, "SELECT * FROM tblRegistros WHERE Ser_presenta LIKE '%$buscarq%';") or die ("No se ha podido buscar");
$count = odbc_num_rows($query);
if($count == 0){
$output = 'No se han encontrado resultados';
}
else {
while($row = odbc_fetch_array($query)){
$depart = $row['Ser_presenta'];
$titulo = $row['Título'];
$output .= '<div>' .$depart. '<br />' .'$row->Título'. '</div>';
}
}
}
echo ($output);?>
Thanks a lot and sorry for the trouble.

How to put a delete button under each post in my blog/website?

I am wanting to put a delete button, so people can delete their post if they want on my simple blog website. I am just a little unsure how to do it. I guess I need to put a value=delete input field on my posting_wall but not sure where to go from there. Thank you in advnace if you can help me.
Form
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/index.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<link type="text/css" rel="stylesheet" href="../css/header.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
$('form').submit(function (e) {
var value;
// "message" pattern : from 3 to 150 alphanumerical chars
value = $('[name="message"]').val();
if (!/^[-\.a-zA-Z\s0-9]{3,150}$/.test(value)) {
alert('Sorry, only alphanumerical characters are allowed and 3-150 character limit".');
e.preventDefault();
return;
}
// "name" pattern : at least 1 digit
value = $('[name="name"]').val();
if (!/\d+/.test(value)) {
alert('Wrong value for "name".');
e.preventDefault();
return;
}
});
});
</script>
</head>
<body>
<?php include 'header.php' ?>
<form action="posting_wall.php" method="get">
<div id="container">
Name:<input type="text" name="name" pattern="[A-Za-z0-9]{3,15}" title="Letters and numbers only, length 3 to 15" required autofocus><br>
E-mail: <input type="email" name="email" maxlength="20" required><br>
Post:<br>
<textarea rows="15" cols="50" name='message'></textarea>
</div>
Date this event took place: <input type="text" name='date' id="datepicker" > <br>
<input type="reset" value="Reset">
<input type="submit">
</form>
<p>Posting Wall</p>
<div id="time">
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'The time at which you are posting is:'. date('h:i Y-m-d') ."\n";
?>
</div>
<?php include 'footer.php' ?>
</body>
</html>
Posting Wall Page (where I want the delete button under each post)
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="../css/post.css" />
<link type="text/css" rel="stylesheet" href="../css/footer.css" />
<meta name="viewport" content="width=device-width" />
<title>Daily Dorm News</title>
</head>
<body>
<h1>Daily Dorm News <br></h1>
<h2> Your Daily Dorm News Posts </h2>
<div id="container"> <?php if ( isset($_GET['name']) and preg_match("/^[A-Za-z0-9]+$/", $_GET['name']) ) {
echo $_GET['name'];
} else {
echo "You entered an invalid name!\n";
}
?><br>
Your email address is: <?php if ( isset($_GET['email']) and preg_match("/.+#.+\..+/i", $_GET['email']) ) {
echo $_GET['email'];
} else {
echo "You didn't enter a proper email address!\n";
}
?><br>
You Posted : <?php if ( isset($_GET['message']) and preg_match("/^[-\.a-zA-Z\s0-9]+$/", $_GET['message']) ) {
echo $_GET['message'];
} else {
echo "The message is not valid! The message box was blank or you entered invalid symbols!\n";
}
?>
<br>
This event happened :<?php echo $_GET["date"]; ?><br>
</div>
<?php
/* [INFO/CS 1300 Project 3] index.php
* Main page for our app.
* Shows all previous posts and highlights the current user's post, if any.
* Includes a link to form.php if user wishes to create and submit a post.
*/
require('wall_database.php');
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
$is_valid_post = true;
// Checking if a form was submitted
if (isset($_REQUEST['name'])){
// Fetching data from the request sent by form.php
$name = strip_tags($_REQUEST['name']);
$email = strip_tags($_REQUEST['email']);
$message = strip_tags($_REQUEST['message']);
$date = strip_tags($_REQUEST['date']);
// Saving the current post, if a form was submitted
$post_fields = array();
$post_fields['name'] = $name;
$post_fields['email'] = $email;
$post_fields['message'] = $message;
$post_fields['date'] = $date;
$success_flag = saveCurrentPost($post_fields);
}
//Fetching all posts from the database
$posts_array = getAllPosts();
?>
<?php
if(isset($name)) {
echo "<h3>Thanks ".$name." for submitting your post.</h3>";
}
?>
<p id="received">Here are all the posts we have received.</p>
<div id="logo">Dont Forget to tell you’re friends about Daily Dorm Post! <br>
The only Dorm News Website on campus!</div>
<ul id="posts_list">
<?php
// Looping through all the posts in posts_array
$counter = 1;
foreach(array_reverse($posts_array) as $post){
$alreadyPosted = false;
$name = $post['name'];
$email = $post['email'];
$message = $post['message'];
$date = $post['date'];
if ($counter % 2==1)
$li_class = "float-left";
else
$li_class = "float-right";
if ($name == $_GET['name']) {
$alreadyPosted = true;
}
echo '<div class=post';
if ($alreadyPosted) {
echo ' id="highlight"';
}
echo '>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' email is: '.$email.'</span></h3></li>';
echo '<li class="'.$li_class.'"><h3><span>'.$name.' wrote '.$message.'</span> wrote a post.</h3></li>';
echo '<li class="'.$li_class.'"><h3><span>This event occured on '.$date.'</span></h3></li>';
echo '</div>';
}
?>
</ul>
</div>
<p id="submit">Would you like to submit another post?</p>
<?php include 'footer.php' ?>
</body>
</html>
create a delete button or make
<script>
function confirm(){
var responce = confirm("Are you sure want to delete?");
if (responce==true)
{
return true;
}
else
{
return false;
}
}
</script>
<a onclick="confirm()" href="delete_post.php?id=1>">Delete</a>

jQuery Mobile and PHP login system not working

I'm trying to create a login system for my jQuery mobile app but it's not doing anything after the login button is clicked. Right now I'm not using a db connection.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="jquery.mobile-1.1.0/jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css">
<link href="jquery.mobile-1.1.0/jquery.mobile.structure-1.1.0.min.css" rel="stylesheet" type="text/css">
<script src="jquery.mobile-1.1.0/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#loginform').submit(function(){
$('#output').html('Connecting...');
var postTo = 'http://www.hedonsoft.com/game/login.php';
$.post(postTo,{userLbl: $('[name=username]').val(), passwordLbl: $('[name=password]').val()}, function (data){
if(data.message){
$('#output').html(data.message);
}else{
$('#output').html("Could not connect");
}
}, 'json');
return false;
});
});
</script>
<script src="jquery.mobile-1.1.0/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="custom.css" />
</head>
<body>
<div data-role="page" id="mc_main">
<div data-role="header" id="header">
<h1>Main Menu</h1>
</div>
<div data-role="content">
<div data-role="collapsible" id="logindiv"><h2>Login</h2>
<form id="loginform" method="post">
<div data-role="fieldcontain">
<label for="user">Username:</label>
<input type="text" name="user" id="user" value="" />
</div>
<div data-role="fieldcontain">
<label for="pass">Password:</label>
<input name="pass" type="password" id="pass" value="">
</div>
<input type="submit" value="Login" data-icon="check" data-theme="a"/>
</form>
<div id="output"></div>
</div>
</div>
</body>
</html>
login.php
<?php
if(isset($_POST['username'] and isset($_POST['password'])) {
// do logic for logining in (usually query your db)
if ($_POST['username'] == 'test' and $_POST['password'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);
}
?>
I get 'Connecting...' in #output but that's it.
The login.php code has a syntax error on line 2. It should read:
if(isset($_POST['userLbl']) && isset($_POST['passwordLbl']))
Your input name for the user field is "user".
Change your javascript to look like this
$.post(postTo,{userLbl:$('[name=user]').val(), ...
Then your login.php should looke like this:
<?php
if(isset($_POST['userLbl'] and isset($_POST['passwordLbl'])) {
// do logic for logining in (usually query your db)
if ($_POST['userLbl'] == 'test' and $_POST['passwordLbl'] == 'test') {
$data['success'] = true;
$data['message'] = 'Login succesful';
} else {
$data['success'] = false;
$data['message'] = 'Login failed';
}
// return json
echo json_encode($data);
}
?>
Your server is returning an error 500. That's why it doesn't work!
You can check my fiddle if you want: http://jsfiddle.net/ooflorent/7cYae/

Categories