user profile update via ajax - javascript

hi guys im trying to update user details via ajax but its not updating my users table and just stop executing when possessing... appear here is my code please help if possible
edit_profile.php
<?php
if(isset($_POST["la"])){
$firstname = strip_tags(preg_replace('#[^a-z0-9]#i', '', $_POST['fi']));
$lastname = strip_tags(preg_replace('#[^a-z]#', '', $_POST['la']));
$age = strip_tags(preg_replace('#[0-9]#', '', $_POST['ag']));
$gender = strip_tags(preg_replace('#[^a-z]#', '', $_POST['g']));
// FORM DATA ERROR HANDLING
if($gender == "" || $firsname == "" || $lastname == "" || $age == ""){
echo "some account info is empty.";
exit();
}else{
$sql = "UPDATE users SET gender='$gender', age='$age', lastname='$lastname, firstname='$firstname' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo "account_success";
exit();
}
}
?>
ajax and js
<script type="text/javascript" language="javascript">
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "firstname"){
rx = /[^a-z0-9]/gi;
} else if(elem == "lastname"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function update_profile() {
var fi = _("firstname").value;
var la = _("lastname").value;
var g = _("gender").value;
var ag = _("age").value;
var status2 = _("status_profile");
if(fi == "" || la == "" || ag == "" || g == ""){
status2.innerHTML = "Fill out all of the form data";
status2.style.color = "red";
}else {
_("profilebtn").style.display = "none";
status2.innerHTML = 'processing ...';
var ajax = ajaxObj("POST", "edit_profile.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "account_success"){
_("profilebtn").style.display = "block";
}
}
}
ajax.send("&fi="+fi+"&la="+la+"&g="+g+"&ag="+ag);
}
}
</script>
the html
<div class="row profile-classic">
<div class="col-md-12 m-t-20">
<form name="updateform" id="updateform" onsubmit="return false;">
<div id="profile_form" class="panel">
<div class="panel-title line">
<div class="caption"><i class="fa fa-phone c-gray m-r-10"></i>ACCOUNT</div>
</div>
<div class="panel-body">
<div class="row">
<div class="control-label c-gray col-md-3">Username:</div>
<div class="col-md-6">
<input type="text" class="form-control" value="<?php echo $uname; ?>" disabled="disabled">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Firstname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="firstname" contenteditable="true" value="<?php echo $firstname; ?>">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Lastname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="lastname" placeholder="your lastname" value="<?php echo $lastname; ?>" >
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Age: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="age" value="<?php echo $age; ?>">
</div>
</div><br />
<div class="row">
<div class="col-md-6">
<select class="form-control" onfocus="emptyElement('status_profile')" id="gender" class="form-control">
<option value="<?php echo $gender; ?>"><?php echo $sex; ?></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<button id="profilebtn" onclick="update_profile()" class="btn btn-sm btn-default"><i class="fa fa-floppy-o"></i> Save</button><span id="status_profile"></span>
</div><br />
</div>
</div></form>
</div></div>

You can use mysqli_error($db_conx) to determine what the error is... just have your javascript display it nicely for you.
But also - the variable in your WHERE clause ( $log_username ) is undefined.

Related

jQuery POST form that is viewed with Ajax

Ok, this is my first time logged in, but have a question which I can`t find. Maybe I used the wrong search terms or it is my broken English.
But hopefully, somebody can point me in the right direction.
My situation. I have a list of users. When I click on one of them a second screen opens using javascript/AJAX. Some CSS styling does the split screen thing.
In the second screen, I show a form with some info or not. So far so good.
What I want is that when you change some info and you press the submit/save button, data gets saved in the database without a page refresh. But I can't get it right. When I press the button the ajax split-screen disappears. But the page that I linked on the jquery does nothing.
Some code is in Dutch so ask if you need translation.
My code is as follows:
Page users.php
<script>
function jsAjaxVieuwUser(str) {
if (str == "") {
document.getElementById("mainRight").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();
document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table
}
}
</script>
<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>
<div class="mainContent">
<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></div>
</div>
<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit'])){
// START, AANTAL
$limit = '0 , 10';
}
$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));
while ($row = $result->fetch_assoc()) {
echo '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</ul>
</div>
</div>
<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>
</div>
</div>
Page ajaxBeheer.php
if(isset($_GET['VieuwUser'])){
$disabled = 'disabled';
$idUser = $_GET['VieuwUser'];
$result = $db->select(" SELECT users.ID,
users.user_name,
users.user_email,
userinfo.userid,
userinfo.user_firstname,
userinfo.user_lastname,
userinfo.user_birthday,
userinfo.user_adress,
userinfo.user_adressnr
FROM users INNER JOIN userinfo
ON userinfo.userid = users.ID
WHERE users.ID=? ", array($idUser),array('%i'));
while ($row = $result->fetch_assoc()) {
//Gebruikers gegevens
$username = $row['user_name'];
$user_email = $row['user_email'];
//Personal data
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_birthday = $row['user_birthday'];
$user_adress = $row['user_adress'];
$user_adressnr = $row['user_adressnr'];
}
// make the date readable, but if its empty make it 0000
if ($user_birthday == '0000-00-00' || empty($user_birthday)) {
$user_birthday = ' ';
}else{
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');
}
?>
<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>
<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" method="POST">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="firstname" value="" /></div></p>
<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>
<style type="javascript">
function save(){
var query = $('#formId').serialize();
var url = 'updateUser.php';
$.post(url, query, function (response) {
alert (response);
});
}
</style>
page updateUser.php
<?php
$table = 'userinfo';
$data = array('user_firstname' => 'test');
$format = array('%s');
$where = array('id' => '3');
$where_format = array('%i');
$updateCalc = $db->update($table, $data, $format, $where, $where_format);
?>
The reason of refreshing the page is because you're using a form with submit button, to prevent it just prevent the form to submit
if you have Jquery use the following
//option A
$("form#formId").submit(function(e){
e.preventDefault();
});
and Pure js solution is
document.getElementById('formId').addEventListener('submit', function(e) {
e.preventDefault();
});
Ok have it finally worked. Had the jquery in the ajaxBeheer.php script. Now i have it in the page where the ajax is executed. And that worked for me.
The Jquery link
Is located in the header.
I have now a second screen where the information is updated without a refresh page. :D
It`s without security so thats need too update for everyone that wants too use it! The question was for the second screen no refresh page.
Hopefully i can help some other people with it, becease it was a pain for me too find information.
The whole code:
Page users.php:
<?php
require_once (__DIR__.'/safeuser.php');
require_once (__DIR__.'/include/topheader.php');
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');
?>
<script>
function jsAjaxVieuwUser(str) {
if (str == "") {
document.getElementById("mainRight").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainRight").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "ajaxBeheer.php?VieuwUser=" + str, true);
xmlhttp.send();
document.getElementById("mainRight").style = "display: inline-block;"; // Don`t show the start table
document.getElementById("closeUser").style = "display: block;"; // Don`t show the start table
}
}
function save(){
// Get the form.
var form = $('#formId');
// Get the messages div. Too show the messages on screen
var formMessages = $('#form-messages');
// TODO: The rest of the code will go here...
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// TODO
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
alert (response);
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
}
function closeUserVieuw() {
var x = document.getElementById("mainRight");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
document.getElementById("closeUser").style = "display: none;"; // Don`t show the start table
}
}
</script>
<style type="text/css">
</style>
<div class="main">
<div class="mainInfo">
<h3>Gebruikers</h3>
</div>
<div class="mainContent">
<div class="mainLeft" id="mainLeft">
<div class="actionBar">
<div><button class="button button2">Nieuwe gebruiker</button></div>
<div id="closeUser"><button class="button button2"> << </button></div>
</div>
<div class="list" id="userList">
<ul>
<li class="listheader"><div class="listFirstColum">Naam gebruiker</div> <div class="listSecondColum">Laatste login</div></li>
<?php
if(!isset($_GET['limit'])){
// START, AANTAL
$limit = '0 , 10';
}
$result = $db->select("SELECT ID, user_name, user_last_login FROM users ORDER BY ID ASC LIMIT ".$limit." ",array(''),array(''));
while ($row = $result->fetch_assoc()) {
echo '<li> <div class="listFirstColum">'.$row['user_name'].'</div> <div class="listSecondColum">'.$row['user_last_login'].'</div> </li>';
}
?>
</ul>
</div>
</div>
<div class="mainRight" id="mainRight">
<h1>HALLO</h1>
</div>
</div>
</div>
<!-- FOOTER -->
</div>
</body>
</html>
ajaxBeheer.php:
<?php
// name: ajaxBeheer.php
require_once (__DIR__.'/classes/class-users.php');
require_once (__DIR__.'/include/config.inc.php');
if(isset($_GET['q'])){
$zoek = $_GET['q'];
$param = "$zoek%"; // Zoek alleen op voorletter
$getGebruiker = $db->select("SELECT * FROM users WHERE naam LIKE ?",array($param),array('s'));
?>
<div id="tableUsers">
<div class="headRow" style="" id="tableUsers">
<div class="cell" style="width: 70%">Gebruiker</div>
<div class="cell" style="width: 30%; border-left: 2px solid #fff; border-right: 2px solid #fff;">Status</div>
</div>
<?php
while ($myrow = $getGebruiker->fetch_assoc()) {
if($myrow['active'] == '1'){
$gebrActive = 'Aktief';
} else {
$gebrActive = 'gedeaktiveerd';
}
echo '<a style="display:block" href="?ID='.$myrow['id'].'">
<div class="row">
<div class="cell" style="width: 70%">'.$myrow['naam'].'</div>
<div class="cell" style="width: 30%; border-left: 1px solid #fff; border-right: 1px solid #fff;">'.$gebrActive.'</div>
</div></a>';
}
echo '</div>';
}
if(isset($_GET['VieuwUser'])){
$disabled = 'disabled';
$idUser = $_GET['VieuwUser'];
$result = $db->select(" SELECT users.ID,
users.user_name,
users.user_email,
userinfo.userid,
userinfo.user_firstname,
userinfo.user_lastname,
userinfo.user_birthday,
userinfo.user_adress,
userinfo.user_adressnr
FROM users INNER JOIN userinfo
ON userinfo.userid = users.ID
WHERE users.ID=? ", array($idUser),array('%i'));
while ($row = $result->fetch_assoc()) {
//Gebruikers gegevens
$username = $row['user_name'];
$user_email = $row['user_email'];
//Personal data
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_birthday = $row['user_birthday'];
$user_adress = $row['user_adress'];
$user_adressnr = $row['user_adressnr'];
}
// make the date readable, but if its empty make it 0000
if ($user_birthday == '0000-00-00' || empty($user_birthday)) {
$user_birthday = ' ';
}else{
$date = DateTime::createFromFormat('Y-m-d', $user_birthday);
$user_birthday = $date->format('d-m-Y');
}
?>
<div class="contentHolder" style="width: 100%;">
<div class="header">
<h3 style="width: 100%; text-align: center;">Gegevens medewerker: <?= $username ?></h3>
</div>
<div class="prLeftColomn colomn">
<form name="gebruiker" id="formId" action="updateUser.php">
<p><div class="omschrijving">Voornaam</div><div class="waarde"><input type="text" name="firstname" value="<?= $user_firstname ?>" /></div></p>
<p><div class="omschrijving">Achternaam</div><div class="waarde"><input type="text" name="lastname" value="<?= $user_lastname ?>" /></div></p>
<p><div class="omschrijving">Email</div><div class="waarde"><input type="text" name="useremail" value="<?= $user_email ?>" /></div></p>
<p><div class="omschrijving">Geboorte datum</div><div class="waarde"><input type="text" name="userbirthday" value="<?= $user_birthday ?>" /></div></p>
<p><div class="omschrijving">Telefoon</div><div class="waarde"><input type="text" name="usertel" value="" /></div></p>
<p><div class="omschrijving">Adres + huisnummer</div><div class="waarde"> <?= $user_adress.' '.$user_adressnr ?></div></p>
<p><div class="omschrijving">Postcode</div><div class="waarde"> </div></p>
<p><div class="omschrijving">Plaats</div><div class="waarde"> </div></p>
<p><div><input class="button" type="submit" name="updateGebruiker" value="UPDATE" onclick="save()"/></div></p>
</form>
</div>
<div class="header" style="margin-top: 5%">
<h3 style="width: 90%; text-align: center;">Uren overzicht</h3>
</div>
<div id="tableUserUren">
<div class="prLeftColomn colomn">
<label>Uren deze week</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren deze maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren vorige maand</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label>Uren Vrij genomen</label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
<label></label>
<input type="text" value="" style="background: white;" <?= $disabled ?> />
</div>
<div class="prRightColomn colomn">
</div>
</div>
</div>
<?php
}
?>
updateUser.php
<?php
require_once (__DIR__.'/include/config.inc.php');
require_once (__DIR__.'/classes/class-db.php');
$username = $_POST['firstname'];
// Ready too add the username
$table = 'users';
$data = array('user_name' => $username);
$format = array('%s');
$newJob = $db->insert($table, $data, $format);
if($newJob != $db::SQLSUCCESFULL){ // Variable is 00000
echo 'Er is helaas iets fout gegaan met het toevoegen van de regel. Code:'.$newJob;
header('location: '.$_SERVER['REMOTE_HOST'].'newuser.php?err=DATABASE&code='.$newJob);
exit();
}else{
echo 'succes!'.$username;
}
?>

How to send the selected value of a drop down menu to an email?

I have an question that send the selected value of a drop down menu to an email in php. I already send the text values to a email. But I did not know how to send the drop down menu value to a email. I did some code. But it does not work. Could anyone support me.
Here is the php, HTML and JS code.
php code...
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'support#ribelz.net';
$subject= 'Contact Request of privateeyelk.com';
$htmlContent = '
<h4>Contact request from : '.$email.'</h4>
<p>Name: '.$name.'</p>
<p>Email: '.$email.'</p>
<p>Message: '.$message.'</p>
';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: Private Eye<privateeyelk.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}
?>
HTML code...
<!-- Contact form -->
<div class="modal fade" id="modalForm" role="dialog" style="width: 100%;">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name" style="border: 1px solid #fff; border-bottom: 1px solid #ccc;"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
<div class="form-group">
<label for="inputMessage">Services</label>
<select name="size" class="form-control"
id="inputService" size="1">
<option value="Option1">Pr-Matrimonial Services</option>
<option value="Option2">Extra Marital Affairs</option>
<option value="Option3">Divorce Case Support</option>
</select>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JS code...
<script>
function submitContactForm(){
var usernameRegex = /^[a-zA-Z0-9]+$/;
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
var service = $('#inputService').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(name.trim() != '' && !usernameRegex.test(name)){
alert('Please enter valid name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else if(service.trim() == '' ){
alert('Please select your service.');
$('#inputService').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'contact.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message+'&service='+service,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('#inputService').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Just add a new variable:
$value_from_dropdown = $_POST['your_select_name'];
Then you can use that variable in your script like you do for any other variable

PHP undefined index and file_get_contents(): Filename cannot be empty

I get these following errors
Notice: Undefined index: imgupload in
C:\xampp\htdocs\cdrrmo\includes\newsfeed.inc.php on line 9
Warning: file_get_contents(): Filename cannot be empty in
C:\xampp\htdocs\cdrrmo\includes\newsfeed.inc.php oI line 9
I want to save the photo in my database, although I get the mentioned errors, the other values are accepted and stored in my database:
if (isset($_POST['send'])){
include_once 'includes/dbh.inc.php';
$_SESSION['location'] = mysqli_real_escape_string($conn, $_POST['location']);
$_SESSION['message'] = mysqli_real_escape_string($conn, $_POST['message']);
$file = addslashes(file_get_contents($_FILES["imgupload"]["tmp_name"]));
//insert the user into the database
$sql = "INSERT INTO newsfeed (user_email,user_uid,user_location, user_message,user_attachment) VALUES ('{$_SESSION['u_email']}','{$_SESSION['u_uid']}','{$_SESSION['location']}', '{$_SESSION['message']}','$file');";
if(mysqli_query($conn, $sql)){
echo "Event has been reported!";
exit();
}?>
<form action="includes/newsfeed.inc.php" method="POST">
<br><br><br><br>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Location</label>
<input type="text" name="location" class="form-control" placeholder="Press 'Get Geolocation'" id="location" required readonly="readonly"><p id="demo1"></p>
<center><button type="button" onclick="getLocation();" required>Get Geolocation</button></center>
<script>
var x = document.getElementById("demo1");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById("location").value = position.coords.latitude + ',' + position.coords.longitude;
}
</script>
</div>
</div>
</div>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12"">
<label for="name">Message</label>
<textarea name="message" class="form-control" placeholder="Message" id="message" rows="15" required></textarea>
</div>
</div>
</div>
</form>
<br>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Upload Image</label><br>
<form method="post" enctype="multipart/form-data">
<div class="container">
<p><div class="fileUpload btn btn-primary">
<form action="" method="post" enctype="multipart/form-data">
<span>+</span>
<input type="file" class="upload" name="imgupload" id="imgupload" multiple="multiple">
<br />
</form>
</div><a id="imgpreview"></a></p>
<button class="btn btn-primary" name="send" id="send">POST</button>
</div>
</form>
</div>
</div>
</div>
<!-- script of upload photo -->
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#imgupload').on('change', function(){
var imgItem = $(this)[0].files;
var imgCount = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var imgExt = imgPath.substring(imgPath.lastIndexOf('.')+1).toLowerCase();
var imgPreview = $('#imgpreview');
imgPreview.empty();
if(imgExt == "gif" || imgExt == "png" || imgExt == "jpg" || imgExt == "jpeg" || imgExt == "bmp"){
if (typeof(FileReader) != "undefined") {
for(var i = 0; i < imgCount; i++){
var reader = new FileReader();
var fn = imgItem[i].name;
var fs = imgItem[i].size;
var ft = imgItem[i].type;
reader.onload = function(e){
$("<img />",{
"src": e.target.result,
"width": "60px",
"height": "60px",
"class": "imgClass",
"title": fn +" and size "+ fs + " bytes and types "+ ft,
"alt": fn +" and size "+ fs + " bytes and types "+ ft,
}).appendTo(imgPreview);
}
imgPreview.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
imgPreview.html("This browser does not support FileReader");
}
}else{
imgPreview.html("File not supported!");
}
});
});
</script>
<!-- end of script -->
<!-- SCRIPT OF UPLOADED PHOTO -->
<script>
$(document).ready(function(){
$('#send').click(function(){
var image_name = $('#imgupload').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#imgupload').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#imgupload').val('');
return false;
}
}
});
});
</script>
<!-- END OF SCRIPT -->
what i did here is, I just removed the other <form> tags
if (isset($_POST['send'])){
include_once 'includes/dbh.inc.php';
$_SESSION['location'] = mysqli_real_escape_string($conn,
$_POST['location']);
$_SESSION['message'] = mysqli_real_escape_string($conn, $_POST['message']);
$file = addslashes(file_get_contents($_FILES["imgupload"]["tmp_name"]));
//insert the user into the database
$sql = "INSERT INTO newsfeed (user_email,user_uid,user_location, user_message,user_attachment) VALUES ('{$_SESSION['u_email']}','{$_SESSION['u_uid']}','{$_SESSION['location']}', '{$_SESSION['message']}','$file');";
if(mysqli_query($conn, $sql)){
echo "Event has been reported!";
exit();
}?>
<form action="includes/newsfeed.inc.php" method="POST" enctype="multipart/form-data">
<br><br><br><br>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Location</label>
<input type="text" name="location" class="form-control" placeholder="Press
'Get Geolocation'" id="location" required readonly="readonly"><p id="demo1"></p>
<center><button type="button" onclick="getLocation();" required>Get Geolocation</button></center>
<script>
var x = document.getElementById("demo1");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
document.getElementById("location").value = position.coords.latitude + ',' + position.coords.longitude;
}
</script>
</div>
</div>
</div>
<div class="container" method="POST">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Message</label>
<textarea name="message" class="form-control" placeholder="Message" id="message" rows="15" required></textarea>
</div>
</div>
</div>
<br>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<label for="name">Upload Image</label><br>
<div class="container">
<p><div class="fileUpload btn btn-primary">
<span>+</span>
<input type="file" class="upload" name="imgupload" id="imgupload" multiple="multiple">
<br />
</div><a id="imgpreview"></a></p>
<button class="btn btn-primary" name="send" id="send">POST</button>
</div>
</div>
</div>
</div>
</form>
<!-- script of upload photo -->
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#imgupload').on('change', function(){
var imgItem = $(this)[0].files;
var imgCount = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var imgExt = imgPath.substring(imgPath.lastIndexOf('.')+1).toLowerCase();
var imgPreview = $('#imgpreview');
imgPreview.empty();
if(imgExt == "gif" || imgExt == "png" || imgExt == "jpg" || imgExt == "jpeg" || imgExt == "bmp"){
if (typeof(FileReader) != "undefined") {
for(var i = 0; i < imgCount; i++){
var reader = new FileReader();
var fn = imgItem[i].name;
var fs = imgItem[i].size;
var ft = imgItem[i].type;
reader.onload = function(e){
$("<img />",{
"src": e.target.result,
"width": "60px",
"height": "60px",
"class": "imgClass",
"title": fn +" and size "+ fs + " bytes and types "+ ft,
"alt": fn +" and size "+ fs + " bytes and types "+ ft,
}).appendTo(imgPreview);
}
imgPreview.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
imgPreview.html("This browser does not support FileReader");
}
}else{
imgPreview.html("File not supported!");
}
});
});
</script>
<!-- end of script -->
<!-- SCRIPT OF UPLOADED PHOTO -->
<script>
$(document).ready(function(){
$('#send').click(function(){
var image_name = $('#imgupload').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension =
$('#imgupload').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#imgupload').val('');
return false;
}
}
});
});
</script>
<!-- END OF SCRIPT -->

fill half form input fill on basis of another filled input

I want to create a billing system for my society application, in this system I want to generate few field dynamically on the basis of what value are reside in the form.means half form will have few data on that data I want to generate another field.
for example: when I select username I will have user type,flatno,parking slot value, now I want to particular charges if user type is owner / tenant.
my code is :
<form class="form-horizontal" role="form" method="post" id="genbill">
<div class="form-group">
<label class="col-lg-3 control-label">Person Name:</label>
<div class="col-lg-8">
<select id="user_nm" name ="user_nm" class=" form-control"></select>
<input type="hidden" name="email" id="email" class="form-control" value="">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">User Type:</label>
<div class="col-lg-8">
<input type="text" name="role" id="role" class="form-control" value="">
<!-- <select id="flatno" name ="flatno" class=" form-control"></select> -->
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Flat No.:</label>
<div class="col-lg-8">
<input type="text" name="flatno" id="flatno" class="form-control" value="">
<!-- <select id="flatno" name ="flatno" class=" form-control"></select> -->
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">PAN No.:</label>
<div class="col-lg-8">
<input type="text" name="pan" id="pan" class="form-control" value="">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Parking Slot.:</label>
<div class="col-lg-8">
<input type="text" name="parking" id="parking" class="form-control" value="">
</div>
</div>
<div id="chargeField">
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Bill Due Date:</label>
<div class="col-lg-8" >
<select name="Duegroup" id="billdate"></select>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Bill Period:</label>
<div class="col-lg-8">
<select name="billgroup" id="daterange">
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Total:</label>
<div class="col-lg-8">
<input type="text" class="form-control" onfocus="findTotal()" name="total" id="total" value="" >
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save" type="submit" name="Add">
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
fill input on usernm chnages
$('#user_nm').on('change', function() {
//alert( this.value );
//var user_nm = document.getElementById('user_nm').value;
var user_nm = this.value;
var flat = document.getElementById('flatno');
var email = document.getElementById('email');
var pan = document.getElementById('pan');
var role = document.getElementById('role');
var park = document.getElementById('parking');
//alert('nm'+user_nm);
$.ajax({
type: "post",
url: "getFlatno.php",
dataType: "json",
data: { email: user_nm },
success: function(data) {
if (data.result == 1) {
flat.value = data.flat;
email.value = data.email;
pan.value = data.pan;
role.value = data.role;
park.value = data.parking;
} else {
alert('failure');
}
}
});
})
retrive charges field
$( "#parking" ).focusout(function() {
// alert( "Handler for .focus() called." );
var email = document.getElementById('email').value;
var role = document.getElementById('role').value;
var park = document.getElementById('parking').value;
alert(email);
alert(role);
alert(park);
$.ajax({
type: "post",
url: "getChargeAsperRole.php",
dataType: "json",
data:{
email:email,
role:role,
park:park
},
success: function(data) {
var html = "";
alert('success');
$.each(data, function(i, item) {
html = html + '<div class="form-group"><label class="col-lg-3 control-label">' + item.charge_title + ':</label><div class="col-lg-8"><input type="checkbox" name="charge_Arr[]" value= "' + item.charge_amt + '" class="checkValue" /><input class="form-control" id="field' + item.num + '" type="text" name="field' + item.num + '" value="' + item.charge_amt + '" readonly><input type="hidden" name="fieldid[]" id="fieldid' + item.num + '" class="form-control" value="' + item.Id + '"></div></div>';
});
$("#chargeField").html(html);
}
});
});
get Charges code :
if($_SERVER['REQUEST_METHOD']=='POST'){
$email = $_POST['email'];
$role = $_POST['role'];
$parking = $_POST['park'] ;
echo $parking;
if($role!='' && $parking!='' && $parking!=0){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id and u.role='$role' and parking_slot='$parking'";
echo "one==".$sql;
}elseif($role!='' && $parking=='' && $parking!=0){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id and u.role='$role'";
echo "two==".$sql;
}elseif($role!='' && $parking=='' && $parking!=0){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id and parking_slot='$parking'";
echo "thiree==".$sql;
}elseif($parking!='0'){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id";
echo "four==".$sql;
}else{
echo "nkagg";
}
// $sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id";
$sql = "select * FROM `billing_charges`";
//echo $sql;
$arrVal = array();
$sqltran = mysqli_query($con,$sql )or die(mysqli_error($con));
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'num' => $i,
'Id' => $rowList['charge_id'],
'charge_title'=> $rowList['charge_title'],
'charge_type'=> $rowList['charge_type'],
'charge_amt'=> $rowList['charge_amt'],
);
array_push($arrVal, $name);
$i++;
}
echo json_encode($arrVal);
mysqli_close($con);
}
If you need to change the content on input B based on the change of content of input A you can use the onchange Event
Change input A to include the call to a javascript function like the following:
<input id="a" onchange="myFunction()">
And in the script section implement myFunction() to do your intended work
<script>
function myFunction() {
var x = document.getElementById("a").value;
if(x=="Hello")
document.getElementById("b").value = "World";
}
</script>

HTML/JS Contact Form Not Sending or Showing Error Message

I have a contact form that I can't seem to send to my Gmail account. It's different from all the contact forms I've seen because the error message is within the HTML. Nothing happens when the submit button is pressed (no email, no error or success message). Please be gentle for I am somewhat new to PHP. I just need some help please.
The HTML
<div class="contactForm">
<div class="successMessage alert alert-success alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Thank You! E-mail was sent.
</div>
<div class="errorMessage alert alert-danger alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Oops! An error occured. Please try again later.
</div>
<form class="liveForm" role="form" action="form/send.php" method="post" data-email-subject="Contact Form" data-show-errors="true" data-hide-form="false">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Name <span>(Required)</span></label>
<input type="text" required name="field[]" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Email <span>(Required)</span></label>
<input type="email" required name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject</label>
<input type="text" name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Message <span>(Required)</span></label>
<textarea name="field[]" required class="form-control" rows="5"></textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Send Message">
</fieldset>
</form>
</div>
</div>
The JS
/**
* Contact Form
*/
jQuery(document).ready(function ($) {
"use strict";
$ = jQuery.noConflict();
var debug = false; //show system errors
$('.liveForm').submit(function () {
var $f = $(this);
var showErrors = $f.attr('data-show-errors') == 'true';
var hideForm = $f.attr('data-hide-form') == 'true';
var emailSubject = $f.attr('data-email-subject');
var $submit = $f.find('[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$('[name="field[]"]', $f).each(function (key, e) {
var $e = $(e);
var p = $e.parent().find("label").text();
if (p) {
var t = $e.attr('required') ? '[required]' : '[optional]';
var type = $e.attr('type') ? $e.attr('type') : 'unknown';
t = t + '[' + type + ']';
var n = $e.attr('name').replace('[]', '[' + p + ']');
n = n + t;
$e.attr('data-previous-name', $e.attr('name'));
$e.attr('name', n);
}
});
$submit.addClass('disabled');
$f.append('<input class="temp" type="hidden" name="email_subject" value="' + emailSubject + '">');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
$('span.error', $f).remove();
$('.error', $f).removeClass('error');
$('.form-group', $f).removeClass('has-error');
if (data.errors) {
$.each(data.errors, function (i, k) {
var input = $('[name^="' + i + '"]', $f).addClass('error');
if (showErrors) {
input.after('<span class="error help-block">' + k + '</span>');
}
if (input.parent('.form-group')) {
input.parent('.form-group').addClass('has-error');
}
});
} else {
var item = data.success ? '.successMessage' : '.errorMessage';
if (hideForm) {
$f.fadeOut(function () {
$f.parent().find(item).show();
});
} else {
$f.parent().find(item).fadeIn();
$f[0].reset();
}
}
$submit.removeClass('disabled');
cleanupForm($f);
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.removeClass('disabled');
cleanupForm($f);
}
});
return false;
});
function cleanupForm($f) {
$f.find('.temp').remove();
$f.find('[data-previous-name]').each(function () {
var $e = jQuery(this);
$e.attr('name', $e.attr('data-previous-name'));
$e.removeAttr('data-previous-name');
});
}
});
The PHP
<?php
// Contact subject
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Enter your email address
$to ='divagraphicsinc#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
?>
<?php
$ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
$ajax = true;
//we do not allow direct script access
if (!$ajax) {
//redirect to contact form
echo "Please enable Javascript";
exit;
}
require_once "config.php";
//we set up subject
$mail->Subject = isset($_REQUEST['email_subject']) ? $_REQUEST['email_subject'] : "Message from site";
//let's validate and return errors if required
$data = $mail->validateDynamic(array('required_error' => $requiredMessage, 'email_error' => $invalidEmail), $_REQUEST);
if ($data['errors']) {
echo json_encode(array('errors' => $data['errors']));
exit;
}
$html = '<div style="width: 640px; font-size: 11px;">
<h2>' . $mail->Subject . '</h2><ul>
';
foreach ($data['fields'] as $label => $val) {
$html .= '<li>' . $label . ': ' . $val . '</li>';
}
$html .= '</ul></div>';
$mail->setup($html, $_REQUEST, array());
$result = array('success' => 1);
if (!$mail->Send()) {
$result['success'] = 0;
}
echo json_encode($result);
exit;

Categories