duplicate page content after ajax to the same page - php

I have simple registration formulae and I want I want to firstly send with ajax and without refreshing the page to control if I insert correct data and then just redirect to some other page. The problem is that after I send it through ajax to the same page everything is working but content of my page is being duplicate, I can see it twice...
here is my ajax
function registruj () {
var name = $('#meno').val();
var priez = $('#priezvisko').val();
var log = $('#login').val();
var mail = $('#mail').val();
var cisloTel = $('#cislo').val();
var heslo = $('#heslo').val();
var heslo1 = $('#heslo1').val();
$.post( "", {
'meno': name,
'priezvisko': priez,
'login':log,
'mail':mail,
'cislo':cisloTel,
'heslo':heslo,
'heslo1':heslo1,
}, function (data) {
$('#result').html(data);
}
);
$('#nove').load(document.URL + ' #nove');
}
and this is my php file
<?php
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
}
?>
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8" />
<title>blblblbl</title>
<link rel="stylesheet" type="text/css" href="./fancybox/jquery.fancybox-1.3.4.css" media="screen" />
<script src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script>$(function(){$('.img').fancybox();});</script>
<style type="text/css"> </style>
<script type="text/javascript" src="mojskript.js"></script>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="css/style1.css" />
</head>
<body class="registracia">
<div class="container">
<div id="nove">
<form >
<table >
<tr><td><label for="napdis">Vyplňte nasledujúci formulár:</label></td></tr>
<tr><td><input type="radio" name="pohlavie" value="zena" id="zena" >Žena</td></tr>
<br>
<tr><td><input type="radio" name="pohlavie" value="muz" id="muz">Muž</td></tr>
<br>
<tr><td><label for="meno">Meno :</label></td><td><input type = "text" id="meno" name="meno"></td></tr><br>
<tr><td><label for="priezvisko">Priezvisko :</label></td><td><input type = "text" id="priezvisko" name="priezvisko"></td></tr><br>
<tr><td><label for="login">Login :</label></td>
<td><input type = "text" id="login" name="login"></td></tr><br>
<?php
if(isset($heslo)) {
if (($heslo != "" && $hesloZnovu != "") && ($heslo == $hesloZnovu)) {
$hesloOk = 1;
}
else {
echo '<tr><td><label for="heslo">Heslo :</label><td><input type = "password" name="heslo"></td><td><label for="zleHeslo">Heslá sa nezhodujú</label></td></tr>';
$pocet = 1;
}
}
?>
<?php
if(!isset($pocet)) {
echo'<tr ><td ><label for="heslo" > Heslo :</label ></td >
<td ><input type = "password" id="heslo" name = "heslo" ></td ></tr ><br >';
}
?>
<tr><td><label for="heslo2">Heslo znovu :</label></td>
<td><input type = "password" id="heslo1" name="heslo1"></td></tr><br>
<?php
if(isset($mail)) {
if (!stristr($mail, "#") OR !stristr($mail, ".")) {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" name="email"></td><td><label for="zlyMail">Zlý formát emailu</label></td></rd></tr><br>';
} else {
$mailOk = 1;
}
}
else {
echo '<tr><td><label for="email">E-mail :</label></td>
<td><input type = "text" id="mail" name="email"></td></tr><br>';
}
?>
<tr><td><label for="cislo">Telefónne číslo :</label></td>
<td><input type = "text" id="cislo" name="cislo"></td></tr><br>
<tr><td><input type="button" value="Zaregistrovať" onclick="registruj()" ></td></tr>
</table>
</form>
<?php
if(isset($mailOk) && isset($hesloOk)) {
$length = 20;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
$zasifrovane = crypt($heslo,$randomString);
echo $zasifrovane;
mysql_query("INSERT INTO uzivatelia (Meno,Priezvisko,Login,Heslo,mail,pohlavie,cislo) VALUES ('$meno','$priezvisko','$login','$zasifrovane','$mail','$pohlavie','$cislo')");
header("location:index.php");
}
?>
</div>
<div id="result"></div>
</div>
</body>
How should I do that ?

Try to use exit(); like :
session_start();
if(isset($_POST["meno"]) ) {
echo "kokot";
echo $_POST['meno'];
require "pripojenie.php";
$meno = $_POST["meno"];
$priezvisko = $_POST["priezvisko"];
$login = $_POST["login"];
$heslo = $_POST["heslo"];
$hesloZnovu = $_POST["heslo1"];
if(isset($_POST["pohlavie"]))
$pohlavie = $_POST["pohlavie"];
$mail = $_POST['mail'];
$cislo = $_POST['cislo'];
//$id = $_SESSION['id'];
exit();
}
Use exit(); or die(); when ajax processing done otherwise it will return all page content.

Change success function to:
function (data) {
$('#result').empty().html(data);
}

Related

PHP | LDAP | Live search in AD

I am using the live search function for my MySQL database data.
But to go directly to the source I do not want a file or db in between and I went directly to the Active Directory itself.
The searching is working but after you searched for something like username, it gives the correct output, the data resets after 2/3 seconds. So the input type text is still filled in but it's showing all the results.
Does anyone can help me with this or can optimize the code?
INDEX.PHP
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Search</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">Live Data Search Active Directory</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
<div style="clear:both"></div>
<br />
<br />
<br />
<br />
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
My fetch.php file with all the links to AD. Ofcourse crendentials and server are filled in and binding is working.
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<div style="overflow-x:auto;">
</head>
</html>
<?php
$output = "";
$ldap_password = "<username>";
$ldap_username = "<password>";
$ldap_connection = ldap_connect("<ldapserver>");
if (FALSE === $ldap_connection){
echo "Unable to connect to the ldap server";
}
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Unable to set LDAP protocol version");
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password))
{
if (isset($_POST["query"]))
{
$search = $_POST["query"];
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*".$search.")(sAMAccountName=".$search."*)(l=*".$search."*)))";
}
else
{
$search_filter = "(&(objectCategory=person)(|(sAMAccountName=*)))";
}
$output .= '<table id="customers"><tr><th>Username</th><th>Last Name</th><th>First Name</th><th>Company</th><th>Office</th><th>Department</th><th>Mobile</th><th>Telephone</th><th>E-Mail Address</th></tr>';
$ldap_base_dn = "OU=NL,DC=global,DC=com";
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter);
if (FALSE !== $result){
$entries = ldap_get_entries($ldap_connection, $result);
//var_dump($entries);
//For each account returned by the search
for ($x=0; $x<$entries["count"]; $x++){
//Windows Username
$LDAP_samaccountname = "";
if (!empty($entries[$x]["samaccountname"][0])) {
$LDAP_samaccountname = $entries[$x]["samaccountname"][0];
if ($LDAP_samaccountname == "NULL"){
$LDAP_samaccountname= "";
}
} else {
//#There is no samaccountname s0 assume this is an AD contact record so generate a unique username
$LDAP_uSNCreated = $entries[$x]["usncreated"][0];
$LDAP_samaccountname= "CONTACT_" . $LDAP_uSNCreated;
}
//Last Name
$LDAP_LastName = "";
if (!empty($entries[$x]["sn"][0])) {
$LDAP_LastName = $entries[$x]["sn"][0];
if ($LDAP_LastName == "NULL"){
$LDAP_LastName = "";
}
}
//First Name
$LDAP_FirstName = "";
if (!empty($entries[$x]["givenname"][0])) {
$LDAP_FirstName = $entries[$x]["givenname"][0];
if ($LDAP_FirstName == "NULL"){
$LDAP_FirstName = "";
}
}
//Company
$LDAP_CompanyName = "";
if (!empty($entries[$x]["company"][0])) {
$LDAP_CompanyName = $entries[$x]["company"][0];
if ($LDAP_CompanyName == "NULL"){
$LDAP_CompanyName = "";
}
}
//Department
$LDAP_Department = "";
if (!empty($entries[$x]["department"][0])) {
$LDAP_Department = $entries[$x]["department"][0];
if ($LDAP_Department == "NULL"){
$LDAP_Department = "";
}
}
//Office
$LDAP_Office = "";
if (!empty($entries[$x]["l"][0])) {
$LDAP_Office = $entries[$x]["l"][0];
if ($LDAP_Office == "NULL"){
$LDAP_Office = "";
}
}
//Job Title
$LDAP_JobTitle = "";
if (!empty($entries[$x]["title"][0])) {
$LDAP_JobTitle = $entries[$x]["title"][0];
if ($LDAP_JobTitle == "NULL"){
$LDAP_JobTitle = "";
}
}
//Mobile Number
$LDAP_CellPhone = "";
if (!empty($entries[$x]["mobile"][0])) {
$LDAP_CellPhone = $entries[$x]["mobile"][0];
if ($LDAP_CellPhone == "NULL"){
$LDAP_CellPhone = "";
}
}
//Telephone Number
$LDAP_DDI = "";
if (!empty($entries[$x]["telephonenumber"][0])) {
$LDAP_DDI = $entries[$x]["telephonenumber"][0];
if ($LDAP_DDI == "NULL"){
$LDAP_DDI = "";
}
}
//Email address
$LDAP_InternetAddress = "";
if (!empty($entries[$x]["mail"][0])) {
$LDAP_InternetAddress = $entries[$x]["mail"][0];
if ($LDAP_InternetAddress == "NULL"){
$LDAP_InternetAddress = "";
}
}
$output .= '<tr><td><strong>' . $LDAP_samaccountname .'</strong></td><td>' .$LDAP_LastName.'</td><td>'.$LDAP_FirstName.'</td><td>'.$LDAP_CompanyName.'</td><td>'.$LDAP_Office.'</td><td>'.$LDAP_Department.'</td><td>'.$LDAP_CellPhone.'</td><td>'.$LDAP_DDI.'</td><td>'.$LDAP_InternetAddress.'</td></tr>';
} //END for loop
echo $output;
} //END FALSE !== $result
echo("</table>"); //close the table
}
?>
The loop is to display multiple results.
As you can see the result is good, but after 2/3 sec it resets and shows all data instead of the "sbx" value. (data is confidential so not shown, but it's corect)
Greets, Stef

Redirect to PHP script from Image

I need some help with my PHP code. I want to redirect to my PHP script when I view an hidden image.
When I try this:
http://robertsite.org/phpmailer/examples/blank.jpg?http://robertsite.org/phpmailer/phpmailer/examples/send.php?id=71
It will show the image, but it will not redirect to the send.php script with the ID.
Here is the code:
<?php
include('config.php');
require '../PHPMailerAutoload.php';
if (isset($_POST['send'])) {
$from = 'rob#robertsite.org';
$toArr = explode(",",$_POST['to']);
$subject = $_POST['subject'];
$message = $_POST['message'];
$sendDateTime = date("Y-m-d h:i:s");
foreach($toArr as $to)
{
mysql_query("insert into tracker(email, sendDateTime,isRead) values('$to', '$sendDateTime', '0')");
$selSendEmailID = mysql_query("select id from tracker order by id desc");
$rowSendEmailID = mysql_fetch_array($selSendEmailID);
$rowEmailID = $rowSendEmailID['id'];
$message .= "<img src=\"http://robertsite.org/phpmailer/examples/blank.jpg?http://robertsite.org/phpmailer/examples/send.php?id=".$rowEmailID."\" style=\"width:0px; min-height: 0px; height:0px;\" alt=\" \">";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = "mail.robertsite.org";
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Username = 'rob#robertsite.org';
$mail->Password = 'mypassword';
$mail->Port = 465; //25, 465 or 587
$mail->FromName = 'Robert Test Mail';
$mail->From = $from;
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->addAddress($to);
$mail->send();
}
echo "Email has been sent!";
}
?>
I am doing this for email tracker where I can see if someone have read my email or not. I tried to use without blank.jpg, it will show the empty image so I have to use blank.jpg to show as a blank image where it cannot be seen.
Do you know how I can run the send.php script with an ID when I view the blank.jpg image??
EDIT: Here is the send.php script:
<?php
include('config.php');
if($_GET['id'] != ''){
$id = $_GET['id'];
$readDateTime = date("Y-m-d h:i:s");
mysql_query("update tracker set isRead='1', readDateTime='$readDateTime' where id='$id'");
}
if (!empty($_POST['message']))
{
$emails = explode("\n", $_POST['message']); // explode textarea on a line break into an array
$email_str = implode(", ", $emails); // take each of the emails and implode together with the ,
echo '<script> closePopUp(); </script>'; //call javascript function
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Send Email</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script src="jquery-1.12.0.js"></script>
<script>
$(document).ready(function(){
$('#popup').click(function(event) {
event.preventDefault();
var popup = window.open("add_address.php", "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=500, width=400, height=400");
if (popup != null && !popup.closed) {
var element = popup.document.getElementById("thePopupField");
var text = $('#theField').val();
if(text != ''){
var count = (text.match(/,/g) || []).length;
popup.my_count = count+1;
popup.my_special_setting = text.replace(/,/g, '\n');
}
}
});
});
</script>
</head>
<body>
<!---->
<form action="pr_send.php" method="POST" id="theForm">
<table>
<!-- <tr>
<td>From:</td>
<td><input type="text" name="from"></td>
</tr> -->
<tr>
<td><input type="button" name="to" value="" style="height:24px; width:24px; background:url('addressbook.png'); border:none;" id="popup" > To:</td> <!--onClick="Popup()"-->
<td><input type="text" id="theField" name="to" value="<?php if (!empty($email_str)) { echo $email_str; } ?>" style="height:15px; width:650px"> (<span id="noOfEmails">0</span>)</td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" style="height:15px; width:650px"></td>
</tr>
<tr>
<td>Message:</td>
<td><textarea name="message" cols="90" rows="20"></textarea></td>
</tr>
<tr>
<td colspan="2" align="left">
<input type="submit" name="send" value="" style="height:35px; width:100px; background:url('send.png'); border:none">
</td>
</tr>
</table>
</form>
</body>
<!--<script type="text/javascript">
var popup = null;
function Popup()
{
window.open("add_address.php", "_blank", "toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=500, width=400, height=400");
}
function closePopUp()
{
if (popup)
{
popup.close();
}
}
</script>-->
</html>
Instead
$message .= "<img src=\"http://robertsite.org/phpmailer/examples/blank.jpg?http://robertsite.org/phpmailer/examples/send.php?id=".$rowEmailID."\" style=\"width:0px; min-height: 0px; height:0px;\" alt=\" \">";
You have to use
$message .= "<img src=\"http://robertsite.org/phpmailer/examples/send.php?id=".$rowEmailID."&img=".urlencode('http://robertsite.org/phpmailer/examples/blank.jpg')."\" style=\"width:0px; min-height: 0px; height:0px;\" alt=\" \">";
And in the send.php script add couple strings
if($_GET['id'] != ''){
$id = (int)$_GET['id'];
$readDateTime = date("Y-m-d h:i:s");
mysql_query("update tracker set isRead='1', readDateTime='$readDateTime' where id='$id'");
if(!empty($_GET['img'])) {
header('location: '.$_GET['img']);
exit;
}
}

When submit form, page won't refresh with new data from sql server until refresh?

Problem
index.php is a page that displays albums from a server hosted by MAMP using SQL. In grid.php I query the server and displays the albums in a grid. index.php also has a form in addalbum.php that allows the user to add an album to the database.
However, when the user submits the form in addalbum.php although the database gets updated, the page doesn't show the new data even though I do:
<form action="../p3/index.php" method="post">
I have to either refresh the page or click on it again to see the updated data. I'm confused as to why this is happening since I set the form action to index.php so it should refresh the page.
If anyone has some advice on that it would be greatly appreciated!
Code
index.php
<?php
$name = "Albums";
require_once('config.php');
require_once("nav.php");
require_once("php/header.php");
require_once("php/grid.php");
require_once("php/footer.php");
// require_once("../P3_M2/php/header.php");
// require_once("../P3_M2/php/grid.php");
// require_once("../P3_M2/php/footer.php");
require_once('php/login.php');
require_once('php/addalbum.php');
$error_log = addAlbumToDatabase();
foreach($error_log as $error){ //debuggin
echo "<h1>$error</h1>";
}
?>
config.php
<?php
define( 'DB_HOST', 'blahblahblah');
define('DB_NAME', 'blahblahblah');
define('DB_USER', 'blahblahblah');
define('DB_PASS','blahblahblah');
//Set up sqli
$mysqli = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );
if ($mysqli->errno) { //Was there an error connecting to the database?
//The page isn't worth much without a db connection so display the error and quit
print($mysqli->error);
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>
<?php echo "$name" ?>
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Styling-->
<link type="text/css" rel="stylesheet" href="css/main.css" />
<link type="text/css" rel="stylesheet" href="css/grid.css" />
<link type="text/css" rel="stylesheet" href="css/form.css" />
<?php
$nameLowercased = strtolower($name);
echo "<link type='text/css' rel='stylesheet' href='css/$nameLowercased.css'/>";
?>
<!--Custom icon-->
<link href="https://file.myfontastic.com/fNQ9F99nd88vQm96ESUaLW/icons.css" rel="stylesheet" />
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--Javascript-->
<script type="text/javascript" src="js/main.js"></script>
</head>
grid.php
<?php
/*DATA*/
//Query for each page
$queryFor = array(
'Albums' => 'SELECT * FROM Album;',
'Photos' => 'SELECT * FROM Image;',
'Album' => "SELECT * FROM Image WHERE id IN
(SELECT image_id FROM AIDict WHERE album_id = $album_id);"
);
//Loop through the $result rows fetching each one as an associative array
$printGridFor = array(
'Albums'=> function($row){
$albumId = $row['id'];
$albumTitle = $row['title'];
$albumDate = $row['date_created'];
$dateFormatted = date("F d, Y", strtotime($albumDate));
$creator = $row['creator'];
print("<div class='grid-square'>
<a href='album.php?id=$albumId'class='grid-info'>
<h1>$albumTitle</h1>
<h2>$dateFormatted</h2>
<h2>$creator</h2>
</a>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit''><span class='icon-pencil'></span></button>
</div>");
},
'Photos' => function($row){
$imgTitle = $row['title'];
$filename = $row['file_name'];
$filepath = $row['file_path'].$filename;
print("<div class='grid-square'>
<img src='$filepath' alt='$imgTitle ''>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit'><span class='icon-pencil'></span></button>
</div>");
},
'Album' => function($row){ //Same as 'Photos'
$imgTitle = $row['title'];
$filename = $row['file_name'];
$filepath = $row['file_path'].$filename;
print("<div class='grid-square'>
<img src='$filepath' alt='$imgTitle ''>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit'><span class='icon-pencil'></span></button>
</div>");
}
);
/*SQL*/
//Get the data
$query = $queryFor[$name];
$result = $mysqli->query($query);
if (!$result) { //If no result, print the error
print($mysqli->error);
exit();
}
?>
<div class="grid">
<?php
while ($row = $result->fetch_assoc()) {
$printGridFor[$name]($row);
}
?>
</div>
<button class="add"><span class="icon-plus"></span></button>
addalbum.php
<?php
function addAlbumToDatabase(){
$errors = array();
if(isset($_POST['submit'])){
global $mysqli;
$maxIdQuery = "SELECT MAX(id) FROM Album";
$maxIdResult = $mysqli->query($maxIdQuery);
if (!$maxIdResult) { print($mysqli->error); exit();} //If no result, print the error
if($row = $maxIdResult->fetch_row()){
$maxId = $row[0]; //Get max id
//Insert album into database
$stmt = $mysqli->prepare("INSERT INTO Album (id, title, date_created, date_modified, location, creator)
VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $album_id, $title, $date_created, $date_modified, $location, $creator);
$album_id = $maxId + 1;
$title = (isset($_POST['album-title'])) ? $_POST['album-title'] : "Untitled";
date_default_timezone_set('America/New_York');
$todays_date = date('Y-m-d');
$date_created = (!empty($_POST['date-created'])) ? $_POST['date-created'] : $todays_date;
$date_modified = (!empty($_POST['date-modified'])) ? $_POST['date-modified'] : $date_created;
$location = (isset($_POST['location'])) ? $_POST['location'] : NULL;
$creator = (isset($_POST['creator'])) ? $_POST['creator'] : NULL;
$executed = $stmt->execute(); //execute statement
$stmt->close(); //close statement
if(!$executed){ //Add to error log
$errors[] = "Unsucceful when inserting $title into database";
$errors[] = $mysqli->error;
}
return $errors;
}
$errors[] = "$title not inserted into database";
return $errors;
}
$errors[] = "Nothing added b/c submit button not pressed";
return $errors;
}
?>
<div class="form-screen">
<button class="close close-form"><span class="icon-x"></span></button>
<form action="../p3/index.php" method="post">
<div class="form-wrapper">
<h1>Add Album</h1>
<input type="text" name="album-title" placeholder="Album Title*" required>
<input type="text" name="date-created" class="date" placeholder="Date Created">
<input type="text" name="date-modified" class="date" placeholder="Date Modified">
<input type="text" name="location" placeholder="Location">
<input type="text" name="creator" placeholder="Author*" required="">
<button type="submit" class="field submit" name="submit" value="submit">Create Album</button>
</div>
</form>
</div>
main.js
$(document).ready(function () {
//Show/Hide edit & delete buttons
$(".grid").on("mouseenter", ".grid-square", function () {
$(this).find(".delete").fadeIn(100);
$(this).find(".edit").fadeIn(100);
});
$(".grid").on("mouseleave", ".grid-square", function () {
$(this).find(".delete").fadeOut(100);
$(this).find(".edit").fadeOut(100);
});
//Show/Hide nav bar
$(".closeNavBtn").on("click", function () {
$(".sidenav").css("width", "0px");
});
$(".menu").on("click", function () {
$(".sidenav").css("width", "250px");
});
$(window).scroll(function (event) {
if ($(".sidenav").width() === 250) {
$(".sidenav").css("width", "0vw");
}
});
//Show/Hide login screen
$(".login").on("click", function () {
$(".login-screen").fadeIn(300);
});
$(".close-login").on("click", function () {
$(".login-screen").fadeOut(300);
});
//Show/Hide form screen
$(".add").on("click", function(){
$(".form-screen").fadeIn(300);
});
$(".close-form").on("click", function(){
$(".form-screen").fadeOut(300);
});
//Customize input label based on file
var input = document.querySelector('.inputfile');
if(input != null){customizeInputLabel(input);}
//Datepicker
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(".date").datepicker({
inline: true,
showOtherMonths: true, dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
});
});
//customizeInputLabel changes label when select file
function customizeInputLabel(input) {
var label = input.nextElementSibling
, labelVal = label.innerHTML;
input.addEventListener('change', function (e) {
var fileName = '';
if (this.files && this.files.length > 1) fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
else fileName = e.target.value.split('\\').pop();
if (fileName) label.querySelector('span').innerHTML = fileName;
else label.innerHTML = labelVal;
})
}
File directory structure

More than one row does not inserted into database..PHP and jQuery

I have created dynamic table from where I can insert data into database, But problem is that when I try to insert more than 1 row into database, its goes nowhere. As I have tried to insert only 1 row as its inserting successfully which advice me what I'm doing wrong
<?php
include "includes/config.php";
?>
<?php
$error_array = array();
$name = $email = $phone = $name_Error = $email_Error =$phone_Error ="";
if(isset($_POST['save_all']))
{
if($_POST['name'] !="")
{
$name = $_POST['name'];
}
else
{
$name_Error ="Enter name";
array_push($error_array,$name_Error);
}
if($_POST['email'] !="")
{
$email = $_POST['email'];
}
else
{
$email_Error ="Enter email";
array_push($error_array,$email_Error);
}
if($_POST['phone'] !="")
{
$phone = $_POST['phone'];
}
else
{
$phone_Error ="Enter phone";
array_push($error_array,$phone_Error);
}
if(count($error_array) == 0)
{
$insert_user = "INSERT INTO users(user_id,name,email,phone) values(NULL,'$name','$email','$phone')";
$res_users = mysqli_query($link,$insert_user);
if($res_users >0)
{
$success_Message = "record inserted";
array_push($error_array,$success_Message);
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="<?php echo CSS_URL;?>add_more.css">
<script src="<?php echo JS_URL;?>jquery.js"></script>
<title>Add More</title>
<script>
$(document).ready(function()
{
var count = 1;
$(".addmore_Button").click(function()
{
count++;
$(".addmore_Form_Table").append('<tr><td class="serial_num"><span>'+count+'</span></td><td><input type="text" name="name"/></td><td><input type="text" name="email"/></td><td><input type="text" name="phone"/></td><td><img id="delete'+count+'" style="margin-left:35px; margin-right:10px" onclick="deleteRow(this.id);" src="images/delete (1).png" /></tr>');
});
});
function deleteRow(id)
{
confirm("Are you sure you want to delete...?");
$("#"+id).parent().parent().parent().remove();
}
$(document).ready(function()
{
$("#delete_User").on('click',function()
{
alert("Sorry, you cant delete first row...!!");
});
});
</script>
</head>
<body>
<table class="addmore_Table">
<tr>
<th class="heading">Sr.No</th>
<th class="heading">Email</th>
<th class="heading">Name</th>
<th class="heading">Phone</th>
<td><input type="submit" class="addmore_Button" name="addmore_Button" value="Add More" /></td>
</tr>
</table>
<form name="addmore_Form" action="" method="post" class="addmore_Form">
<table class="addmore_Form_Table">
<tr>
<td></td>
<td><?php echo $name_Error;?></td>
<td><?php echo $email_Error;?></td>
<td><?php echo $phone_Error;?></td>
<td></td>
</tr>
<tr>
<td class="serial_num"><span>1</span></td>
<td><input type="text" name="name" value="<?php echo $name;?>" /></td>
<td><input type="text" name="email" value="<?php echo $email;?>" /></td>
<td><input type="text" name="phone" value="<?php echo $phone;?>" /></td>
<td><img id="delete_User" style="margin-left:35px; margin-right:10px" src="images/delete (1).png" /></td>
</tr>
</table>
<input type="submit" class="save_all" name="save_all" value="Save All" />
</form>
</body>
</html>

PHP and AJAX registration form for start page

I am learning to create a social ntwk. I hv used an AJAX framework for the signup page and it wked. Now I am trying to use the same framewk for the start page . Its nt wking. The problems are with the gender conditionals. The submit button does nt click.Hw cn I fix this code so that form submits whn user is either male or female
}
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$gender = $row["gender"];
}
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["f"])){
// CONNECT TO THE DATABASE
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$f = preg_replace('#[^a-z0-9]#i', '', $_POST['f']);
$l = preg_replace('#[^a-z0-9]#i', '', $_POST['l']);
$wt= preg_replace('#[^a-z ]#i', '', $_POST['wt']);
$a= preg_replace('#[^a-z ]#i', '', $_POST['a']);
$ws= preg_replace('#[^a-z ]#i', '', $_POST['ws']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
// FORM DATA ERROR HANDLING
if($f == "" || $l == "" || $wt || $a == "" || $ws || $c == "" ){
echo "The form submission is missing values.";
exit();
} else {
// Add user info into the database table for the main site table
$sql = "UPDATE users SET firstname='$f', lastname ='$l', wagsbooty ='$wt', abs ='$a', wagsboobs ='$ws', crash ='$c' WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
echo "startup_success";
exit();
}
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
<style type="text/css">
#startupform{
margin-top:24px;
}
#startupform > div {
margin-top: 12px;
}
#startupform > input,select {
width: 200px;
padding: 3px;
background: #F3F9DD;
}
#startupbtn {
font-size:18px;
padding: 12px;
}
</style>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function startup(){
var f = _("firstname").value;
var l = _("lastname").value;
var wt = _("wagsbooty").value;
var a = _("abs").value;
var ws = _("wagsboobs").value;
var c = _("crash").value;
var status = _("status");
if(f == "" || l == "" wt || a == "" || ws || c == "" ){
status.innerHTML = "Fill out all of the form data";
} else {
_("startupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "start_page1.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "startup_success"){
status.innerHTML = ajax.responseText;
_("startupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("startupform").innerHTML = "OK!";
}
}
}
ajax.send("f="+f+"&l="+l+"&wt="+wt+"&a="+a+"&ws="+ws+"&c="+c);
}
}
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<h3>Fill in this form to create your profile!</h3>
<form name="startupform" id="startupform" onsubmit="return false;">
<div>Firstname: </div>
<input id="firstname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>Lastname: </div>
<input id="lastname" type="text" onfocus="emptyElement('status')" maxlength="16">
<br /><br />
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest booty :";?></br>
<select id="wagsbooty" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_wags_list.php");
}else{
echo "Star with hottest abs:";?></br>
<select id="abs" onfocus="emptyElement('status')" maxlength="255">
<?php include_once("template_abs_list.php");
}
?>
</select>
</div>
</br>
<div>
<?php
if($gender === 'm'){
echo "WAG with hottest boobs :";?></br>
<select id="wagsboobs" onfocus = "emptyElement('status')" maxlength="255">
<?php include_once("template_boobs_list.php");
}else{
echo "I have a crash on :";?></br>
<select id="crash" onfocus ="emptyElement('status')" maxlength="255">
<?php include_once("template_crash_list.php");
}
?>
</div>
</select>
</br>
</br>
<button id="startupbtn" onclick="startup()">Create Profile</button>
<span id="status"></span>
</form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>
You don't have anywhere on the page for the user to select their gender within the page - you should add either a radio button or a select box to the page and pass that info to the startup() function.

Categories