Unable to insert data in a table using php - javascript

I have this following code->
html5 code block:
<div class="col-md-8 blogger-right-container">
<form action="blogger_account.php" method="post" role="form" enctype="multipart/form-data">
<div class="form-group">
<h2>Blog Title</h2>
<input type="text" class="form-control" name="blog_title" placeholder="Enter title for your blog.">
</div>
<div class="form-group">
<h2>Blog Content</h2>
<textarea name="blog_content" class="form-control" cols="30" rows="10" placeholder="Enter the content here."></textarea>
</div>
<div class="form-group" style="text-align: center;">
<input type="submit" class="btn btn-success btn-lg" name="add" value="Insert">
</div>
</form>
</div> <!-- blogger right container -->
php code block:
`
if(isset($_POST['add'])){
$blogger = $_SESSION['blogger_email'];
$blog_title = $_POST['blog_title'];
$blog_content = $_POST['blog_content'];
$insert_blog = "insert into blogs (blogger_email,blog_title,blog_content) values ('$blogger',$blog_title','$blog_content')";
$run_blog = mysqli_query($con,$insert_blog);
if($run_blog){
echo "<script>alert('Blog inserted.')</script>";
echo "<script>window.open('blogger_account.php','_self')</script>";
}
}`
The php code block is not inserting the data in blogs table. The columns are in proper order, but still i tried to change the sequence and it didn't worked.
Can anyone tell me whats wrong with my code.

Please mention Error you are receiving.
In order to show detailed php errors, navigate to " How to get useful error messages in PHP? "
MySQL errors in php can be thrown this way --> PHP MySQL error handling

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.

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

restricting access to specific users in php error

I have a made a simple website with login. My users sql table is as shown below:
my login form is like below:
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Sign In</h3>
</div>
<div class="panel-body">
<form role="form" method="post" action="login.php">
<fieldset>
<div class="form-group" >
<input class="form-control" placeholder="E-mail" name="email" type="email" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="pass" type="password" value="">
</div>
<input type="submit" value="login" name="login" >
i want to restrict some users from entering some pages. i have made the access column for this. I have added the following code to the protected page
session_start();
if($_SESSION["access"]!=0)
{
header('Location: login.php');
}
there are some problems with this coode i guess. when the access=0,the page is shown even if the user is not logged in and shows like Undefined index: access in C:\xampp\htdocs\nurse\index.php on line 12
when the access is set to 1 ,its redirected to login page. can anyone help me?
You need to check session is set or not like this
if(isset($_SESSION["access"])) {
if($_SESSION["access"] !=0) {
header('Location: login.php');
}
}

Javascript function defined in the head is not working

<script>
$(document).ready(function() {
$('#submitButton').submit(function(event) {
event.preventDefault();
$.post('http://sentiment.vivekn.com/api/text/',
$('#myForm').serializeArray(),
function(data, status) {
var json = JSON.parse(data);
$('text').html(document.getElementById('message').innerHTML);
$('sentiment').html(json.result.sentiment);
$('confidence').html(json.result.confidence);
console.log(json.result.sentiment);
console.log(status+"\n");
});
});
});
</script>
<section class="container content-section">
<div class="row">
<div class="col-lg-10 col-lg-offset-1">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<form id="myForm" method=POST action="http://sentiment.vivekn.com/api/text/">
<p>Enter your sentences:</p>
<textarea rows="5" type=text name="txt" class="form-control" placeholder="Sentences to detect" id="message" required data-validation-required-message="Please enter a message."></textarea>
<br>
<button class="btn btn-primary align-right" type="submit" id="submitButton">Submit</button>
</form>
</div>
</div>
This part should work when the page is loaded, but it doesn't response at all.
EDIT: The script does not execute at all, what we get instead is a GET request to the url: ...index.html/?txt=[inputfrommyform] and nothing changes on the page, instead of the page even hitting the target POST request server.
Just updated according to the comments. Thank you!
The error we get from Chrome Inspect is still
Uncaught ReferenceError: $ is not defined
Four issues:
You need to listen to the submit event of #myForm instead of #submitButton which doesn't emit such an event.
Your post callback receives an already parsed JSON object, parsing again fails as a string is expected but an object given.
You need to prevent the default action on form submit by returning false from your submit event handler.
You need to include jQuery before your script.
Fixed code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#myForm').submit(function() {
$.post('http://sentiment.vivekn.com/api/text/',
$('#myForm').serializeArray(),
function(json, status) {
$('text').html(document.getElementById('message').innerHTML);
$('sentiment').html(json.result.sentiment);
$('confidence').html(json.result.confidence);
console.log(json.result.sentiment);
console.log(status + "\n");
});
return false;
});
});
</script>
<section class="container content-section">
<div class="row">
<div class="col-lg-10 col-lg-offset-1">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<form id="myForm" method=POST action="http://sentiment.vivekn.com/api/text/">
<p>Enter your sentences:</p>
<textarea rows="5" type=text name="txt" class="form-control" placeholder="Sentences to detect" id="message" required data-validation-required-message="Please enter a message."></textarea>
<br>
<button class="btn btn-primary align-right" type="submit" id="submitButton">Submit</button>
</form>
</div>
</div>
</div>
</div>
</section>

Can I reload a div using jQuery?

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');
});

Categories

Resources