I currently have a page titled news.php, this page displays my news articles. I am now planning to allow my users to search through the database preventing constant scrolling. In doing so I have created a second file called search.php. My intention with this page is to load in articles 'LIKE' the submission from my form in news.php on this page. I have no errors in my error.log and I am having trouble submitting the information and loading search.php displaying my results. I have found tones of information on mysqli but nothing for PDO. So in short, how do I take the user to search.php and displaying similar information to their submission in my form on news.php?
php on search.php html of form on news.php is displayed bellow
<div id="news">
<?php
if(isset($_POST['submit-search'])){
$search = $_POST['search'];
$q = $handler->prepare("SELECT * FROM articles WHERE headline LIKE '%$search%' OR dateTime LIKE '%$ search%' OR text LIKE '%$search%'");
$q->execute(array($search));
if ($q->rowCount() > 0){
while ($result = $q -> fetch(PDO::FETCH_ASSOC)); {
echo '<div class="col-md-4 col-xs-12 col-sm-12 height-news">';
echo '<p class="news-title">'.$results[$i]['headline'].'<br>'.'</p>';
echo '<img class="news-img" src="data:image/png;base64,'.base64_encode( $results[$i]['logo']). '"/>';
echo '<p class="news-time">'.$results[$i]['dateTime'].'<br>'.'</p>';
echo '<p class="news-body">'.$results[$i]['text'].'</p>';
echo '<button class="news-btn" id="myBtn" onclick="showFull(this)">Read More</button>'.'</div> ';
}
if ($result == 0) {
echo '<p class="error-message3">Sorry there is no results!</p>';
}
}
}
?>
<div class="searchPanel">
<div id="x-gon">
<i class="fa fa-close"></i>
</div>
<form action="search.php" id="content" method="POST">
<input type="text" name="search" type="text" class="input420"></input>
<submit id="CupidsArrow" class="fa fa-chevron-right fa-4x" type="submit" name="submit-search" value="Submit"></submit>
</form>
</div>
The issue is here:
<i id="CupidsArrow" class="fa fa-chevron-right fa-4x" name="submit-search"></i></a>
here you are using a i tag to submit the form with an a tag. And also </a> is there but its opening tag is missing. So instead of this, try:
<input type="submit" name="submit-search" value="Submit" />
input type submit will submit the form to the url specified in the form action.
Ex:
<form action="search.php" id="content" method="POST">
<input />
<input type="submit" value="Submit" />
</form>
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
function showFull(button) {
modal.style.display = "block";
$('.dimmer').show();
var newsText = $(button).parent().find(".news-title")[0];
$(".news-title2").text(newsText.textContent);
var newsDate = $(button).parent().find(".news-time")[0];
$(".news-time2").text(newsDate.textContent);
var newsBody = $(button).parent().find(".news-body")[0];
$(".news-body2").text(newsBody.textContent);
var newsImg = $(button).parent().find(".news-img")[0].src;
$('.news-img2').attr("src", newsImg);
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
<div class="searchPanel animated bounceInLeft">
<div id="x-gon">
<i class="fa fa-close"></i>
</div>
<form action="search.php" id="content" method="POST">
<input type="text" name="search" type="text" class="input420"></input>
<input type="submit" name="submit-search" value="Submit" id="CupidsArrow" class="fa fa-chevron-right fa-4x"></input>
</form>
</div>
Related
I'm doing a form validation in my php script, take one column as an example, if the username is not filled, an alert window will pop up and say "please enter your username", after user click "ok", the whole page refresh but the information on the form will be reset too.
So I would like to keep what the user has input after refreshing the page, how can I embed the code in php using AJAX?
//username validation
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
the website is in php file, html code is embedded under the php stuff, and this is the form in the html
<div id="account">
<form method="POST">
<p><span class="error">* required field.</span></p>
Username:
<input type="text" name="Username">
<span class="error">* </span><br>
<!--other fields..-->
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="signup_button">
</form>
</div>
<?php
if(isset($_POST['signup_button'])){
$Username = $_POST['Username'];
}
?>
or...
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
/* save the value in the browser */
echo 'window.'+VarYouWantToKeep = $_POST['VarYouWantToKeep'];
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
( or use localStorage, instead of window. https://developer.mozilla.org/en/docs/Web/API/Window/localStorage )
Then, when the page loads, check if('window.'+VarYouWantToKeep)
and if it's there, set it as the value="" of the corresponding form field
try this (This is taking into account you set $username to $_POST["Username"];)
<input type="text" name="Username" value="<?php if(isset($_POST["signup_button"]) && $_POST["signup_button"]=="Submit") {echo $username; ?>"
To store variable data, you will need to use $_SESSION variables in PHP. Make sure that session_start() is at the top of the PHP page.
Here's a basic example:
//this PHP page contains the HTML form
<form>
<input type="text" value="<?php echo $_SESSION['email']; ?>" />
</form>
//ajax
$.ajax({
url:'validate.php',
type:'POST',
data:{name:inputName}
}).done(function(data){
alert(data);
});
//php page
session_start();
if(!isset($_POST['name'])){
//set session variable
$_SESSION['email'] = $_POST['email'];
//this will be sent back to PHP page with HTML
echo 'Please enter username';
}
I coded here, a super cool login page with bootstrap as you expect. Link bootstarp cdn in your html file. This will show the error under the button instead of showing a windows classic alert box. I included ajax request and php response also with some validation.
login.html
<div class="container">
<div class="col-lg-offset-8 col-md-offset-6 col-lg-4 col-md-4 login-bg">
<form class="form-horizontal" role="form" action="#" method="">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="username" type="text" class="form-control" name="username" value="" placeholder="User Name" required tabindex="1" autocomplete="off">
</div>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<input id="password" type="password" class="form-control" name="password" value="" placeholder="Password" required tabindex="2" autocomplete="off">
</div>
<br>
<div class="form-group">
<div class="col-lg-6">
<button class="btn btn-primary-outline btn-block" type="submit" id="login">Login</button>
</div>
<div class="col-lg-6">
<button class="btn btn-success-outline btn-block" type="reset">Clear</button>
</div>
</div>
<br>
<div id="login-feedback" class="btn-block"></div>
</form>
</div>
</div>
myStyle.js
<script type="text/javascript">
$(document).ready(function()
{
$('#login').click(function()
{
var uname=$('#username').val();
var pword=$('#password').val();
if(uname!='' && pword!='')
{
$('#login-feedback').text('validating....');
$.post("login-check.php",{username:uname,password:pword},function(data)
{
if(data=="success")
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','green').fadeTo(1000,1,function()
{
document.location='index.php';
});
});
}
else
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','red').fadeTo(900,1);
//reset form
$('#login').trigger("reset");
});
}
});
return false;
}
else
{
$('#login-feedback').text("Please enter all fields").css('color','purple');
}
});
});
</script>
login-check.php
<?php
//include connextion file;
if(!isset($_SESSION))
session_start();
$username=trim($_POST['username']);
$password=$_POST['password'];
$username=mysqli_real_escape_string($con,$username);
$password=mysqli_real_escape_string($con,md5($password));
if(($username) && ($password))
{
$query = mysqli_query($con,"select * from login where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows>= 1)
{
$fetch_result = mysqli_fetch_array($query);
session_regenerate_id(true);
$_SESSION['username']=$fetch_result['username'];
$_SESSION['status']=$fetch_result['status'];
// Close session variable assigns
session_write_close();
echo "success";
}
else
{
echo 'Login failed';
}
mysqli_close($con);
}
?>
I need one help.I need to totally remove the submit button after submit the form and when it will be submitted the button will display to user.I am explaining my code below.
<form name="billdata" id="billdata" enctype="multipart/form-data" method="POST" onSubmit="javascript:return checkForm();" action="complain.php">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px"> Name :</span>
<input type="text" name="u_name" id="name" class="form-control" placeholder="Add Name" onKeyPress="clearField('name');">
</div>
<input type="submit" class="btn btn-success" name="complainSubmit" id="addProfileData" value="Submit"/>
</form>
complain.php:
require_once("./include/dbconfig.php");
if(isset($_REQUEST['complainSubmit']))
{
// ......data is collecting here....
}
when data are submitted successfully the below part is executing.
<script type="text/javascript">
var phpVar = "<?php echo $_GET['success'];?>";
//console.log('php',phpVar=='');
if(phpVar == 1 && phpVar!=''){
alert('Submitted successfully.');
//var subButton=document.getElementById('addProfileData');
//subButton.disabled=false;
}
else if(phpVar == 0 && phpVar!=''){
alert('Unable to add.\\nTry again.');
}
else{
// nothing
}
</script>
<script>
function checkForm(){
var s=document.billdata;
if(s.u_name.value==''){
alert('Please enter name');
s.u_name.focus();
s.u_name.style.borderColor = "red";
return false;
}
}
</script>
Here i need to button hide when the data is going to submit and it will again display after the submit.Please help me.
A javascript code such as:
document.getElementById("your_div").innerHTML = "";
will erase the content of your div.
So, byt tagging the entire form, then erasing its contents, you can "hide" it.
Why you dont add a hide CSS-Selector or remove it by checking via if-statement?
CSS-Version:
<input type="submit" class="btn btn-success <?php ($isSubmitted ? ' hideme' : '')?>" name="complainSubmit" id="addProfileData" value="Submit">
Except a new CSS-Selector: .hideme { display:none }
Via PHP/Template:
html...
<?php if(!$isSubmitted) : ?>
<input type="submit" class="btn btn-success" name="complainSubmit" id="addProfileData" value="Submit">
<?php endif; ?>
html...
Dont forget: You dont need close input html-tag: <input/> just <input>
And what is wrong to hide the button via JS?
document.getElementById("addProfileData").style.display = "none";
UPDATE:
Prompt hiding after clicking:
<button onclick="javascript:this.style.display='none'">
Submit Button
</button>
in your example:
<input onclick="javascript:this.style.display='none'" type="submit" class="btn btn-success" name="complainSubmit" id="addProfileData" value="Submit"/>
I have a first page of a form, and then I use jQuery to load the second part of the form. However, after I click submit on the form, nothing happens, the page is just stuck here. Any ideas?
jQuery:
$.ajax({
type: "POST",
url: "join_submit.php",
data: data,
success: function () {
$("#regform").load("submitTranscript.php");
}
});
submitTranscript.php:
<div id="regform>
<form id="uploadTranscript" action="uploadPDF.php" enctype="multipart/form-data" method="post">
<div class="separation">
<h3>Upload Transcripts</h3>
<div class = "row">
<div class="large-6 offset-2 columns">
<label for = "studid">Enter your student ID:</lable>
<input type="text" name="studid" id="studid"
</div>
<p>Please label your transcript with your user id (i.e. 123456.pdf).</p>
<div class="row">
<div class="large-6 offset-2 columns">
<input type="file" name="transcript" id="transcript">
</div>
</div>
<div class="buttonRow">
<div class="button" id="submit">Submit</div>
</div>
</div>
</form>
</div>
uploadPDF.php:
<?php
require_once("included.php"); //server info
$allowedExtensions = array("pdf");
$max_filesize = 20000;
$upload_path = "docs/transcripts/";
$filename = $_FILES["transcript"]["name"];
$filesize = $_FILES["transcript"]["size"];
$extension = $_FILES["transcript"]["type"];
if ($_FILES["transcript"]["error"] > 0) {
echo "Error: " . $_FILES["transcript"]["error"] . "<br />";
}
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) {
move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename);
}
else if($filesize > $max_filesize){
$fileSizeFail = true;
}
else {
$fileTypeFail = true;
}
?>
If I look into submitTranscript.php, You have coded following for submitting your form:
<div class="buttonRow">
<div class="button" id="submit">Submit</div>
</div>
But, you haven't inserted any submit button to submit the form. Div element cannot post or submit any form. So, I would suggest to put an input type submit button then try to submit your form via that button.
So the code will be:
<div class="buttonRow">
<div class="button" id="submit">
<input type="submit" name="form_submit" value="Submit" />
</div>
</div>
You are not giving any information about join_submit.php file. You have to check in firebug console present in Firefox browser what is the return value of your join_submit.php file. Whether it is going to success function or not. Then only you can track why it is not loading the second form. In chrome browser you can trace the ajax request by clicking F12 and then Network.
Hope it helps
i have many forms in a single page, there is a button that opens up a text editor that was hidden with the purpose of updating a text file accordingly to a user_id
so i iterate through all users and get many of these:
<form action="admin/edittoken.php" method="POST">
<td><a id="'.$result[0]['user_id'].'" onclick="toggle_visibility(\'feedDiv\');">
<button onclick="toggle_visibility(\'feed\');" type="button">Feed
</button><a/></td>
<td><button class="btn btn-default" type="submit" name="password" >Apply Changes</button></td>
<td><input name="first_name" class="smallInput" value="'.$result[0]['first_name'].'" type="text" /></td>
</form>
as you can see when i click this link and there is one per each form i show a div with id = feedDiv
<a id="'.$result[0]['user_id'].'" onclick="toggle_visibility(\'feedDiv\');">
the id of the <a> is the user id and with that data i can pull up the right txt file to edit
SO MY GOAL IS:
get the id of the link that was clicked when requesting to show the div ( the user_id)
place that id in between php for PDO to query and display the right txt file
this is the php
<div id="feedDiv">
<form method="POST" action="admin/edittoken.php">
<textarea id="feed" name="information">
<?php $user=/ /the a Link Clicked Id Value is the user_id //need help
here $filename=/ /equal to the PDO Result to get the right text file $handle=f
open($filename, "r"); $contents=f read($handle, filesize($filename)); fclose($handle);
echo $contents; ?>
</textarea>
<button class="btn btn-primary yellow" type="submit" name="feed">Send Feed</button>
</form>
</div>
Javascript so far...
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block') e.style.display = 'none';
else e.style.display = 'block';
}
JSFIDDLE: http://jsfiddle.net/EC6b4/1/
<a id="'.$result[0]['user_id'].'" onclick="toggle_visibility(\'feedDiv\', this.id);">
function toggle_visibility(id, user_id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
$.post("userdetail.php", { userid: user_id },
function(data){
$('#'+id).html(data);
});
}
userdetail.php contails :
<form method="POST" action="admin/edittoken.php">
<textarea id="feed" name="information">
<?php
$user = $_POST['userid']//the a Link Clicked Id Value is the user_id //need help here
$filename = //equal to the PDO Result to get the right text file
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
echo $contents;
?>
</textarea>
<button class="btn btn-primary yellow" type="submit" name="feed" >Send Feed</button>
</form>
/////
and your placeholder will be like
<div id="feedDiv" ></div>
<div class="accordion" id="accordion2">
<?php $info= mysql_query("SELECT id, title, description FROM event"); ?>
<?php while ($row = mysql_fetch_array($info, MYSQL_NUM)): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse<?php print $row[0]; ?>"><?php print $row[1]; ?></a><span class="delete" id="<?php print $row[0]; ?>">×</span>
</div>
<div id="collapse<?php print $row[0]; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<div class="row-fluid">
<div class="span6">
<?php print $row[2]; ?>
</div>
<div class="span6 ppl">
<ul>
</ul>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
I have a pretty simple way of printing out my twitter bootstrap accordion.
I have this displayed on my page and I also have a form on top of the accordion itself from where I can submit another one into the database using ajax. Here is the form:
<form class="form">
<fieldset>
<legend>Stuff</legend>
<input class="class1" type="text" placeholder="xx">
<input class="class2" type="text" placeholder="xx">
<input class="class3" type="password" placeholder="xx">
<textarea maxlength="320" rows="5" class="class4" placeholder="xx"></textarea>
<div class="submit btn">Add</div>
</fieldset>
</form>
Here is the jQuery:
$(".form .submit").bind("click", function() {
var title = $(".form input.class1").val();
var email = $(".form input.class2").val();
var stuff1 = $('.form input.class3').val();
var stuff2 = $('.form textarea.class4').val();
if (title && email) {
var data = {title: title, email: email, stuff1: stuff1, stuff2: stuff2};
$.post("action.php", data, function() {
$(".form input, .form textarea").val("");
alert('done');
});
}
else {
alert('something went wrong');
}
});
And finally my action.php file:
<?php require('access.php');
if ($_POST['title'] && $_POST['email']) {
$title = $_POST['title'];
$email = $_POST['email'];
$stuff1 = $_POST['stuff1'];
$stuff2 = $_POST['stuff2'];
mysql_query("INSERT INTO events (title, email, stuff1, stuff2) VALUES('$title', '$email', '$stuff1', '$stuff2')");
}
Everything works, but like the title says, I want the information entered to be prepended to the accordion div as a new accordion group (without refreshing the page). My brain refuses to work with me on this, since to me it seems that if I submit the values, I have to make another request to the database to get the freshly generated id of the new event to have my accordion layout working.
Wat do?
And sorry for using a deprecated way of using mysql :O
So mysql functions aside, all you are looking to do is to prepend some html to an element. You already have a callback function on your post and so all you need to do is to make it actually do something i.e.
$.post('action.php', data, function() {
var newID = 123; // get this from the response text
$('div.accordion-inner').prepend('<div class="row-fluid"><div class="span6">'+newID +'</div><div class="span6 ppl"><ul></ul></div></div>');
});
This will attempt to prepend the div as specified to div.accordion-inner
Just replace the prepended with whichever html you are looking for.
And as an additional note, http://php.net/manual/en/function.mysql-insert-id.php will get you the PRIMARY KEY value for the last INSERT performed on your MySQL connection