search result not showing in the same window - javascript

my search result does not show on the same window, i would want the result to be displayed on the same window. i have found the same question but the code is different from what I'm using so i cant relate to it: Search wont show on same page
scenario 1:
if I put in the action="search_result2.php" - it will redirect the result on the other page
scenario 2:
if i used action="" in this code below, its not doing anything
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
$(document).ready(function(){
$("#results").show();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#search").on('click',function() {
var find = $('#find').val();
var field = $('#field').val();
$.post('search_result2.php',{find:find, field:field}, function(data){
$("#results").html(data);
});
return false;
});
});
</script>
</head>
<body>
<div id="container" style="width:auto">
<div id="mainContent">
<h2>Search</h2>
<form name="search" method="post" action="">
Seach for: <input type="text" name="find" id="find" /> in
<Select NAME="field" id="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" id="search" value="Search" />
</form>
<div id="results">
</div>
</div>
</div>
</body>
</html>
here is my search_result2.php:
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field']);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['testA'];
echo " ";
echo $result['testB'];
echo "<br>";
echo $result['testC'];
echo "<br>";
echo $result['testD'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>

If you want to load in the same page, without refreshing the page, you'll need to make an ajax request.
If you can reload the page, the php part must be in the same "location" as your original link.
For example if you put that code on the top of the same file with the form (and rename it with a .php extension), it should work (if the php can interpret in that folder).

Related

redirect to html with custom messagenafter php form form submission

I am using Php for the first time and trying to make a contact us form. I have made the form with inline php inside html code and saved the file as .php and it worked. Now that looked really ugly and my nodejs server doesn't serve my php files so I have tried to take out the php code into a separate file.
So now I have two files -
index.html which has form
mail.php
index.html
<h2>PHP FORM </h2>
<form action="mail.php" method="POST">
<label for="user">Name</label>
<input type="text" id="user" name="users-name"><br>
<label for="email">Email</label>
<input type="email" id="email" name="users-email"><br>
<label for="cars">Category</label>
<select name="users-cat" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select><br>
<label for="subject">Subject</label>
<input type="text" id="subject" name="users-subject"><br>
<label for="msg">Message</label>
<input type="text" id="msg" name="users-message"><br>
<input type="submit">
</form>
mail.php is like this -
<?php
if (isset($_POST['users-name']) ||
isset($_POST['users-email']) ||
isset($_POST['users-subject'])) {
$admin_email = "username#gmail.com";
$name = stripslashes($_POST['users-name']);
$subject = stripslashes($_POST['users-subject']);
$email = stripslashes($_POST['users-email']);
$category = stripslashes($_POST['users-cat']);
$message = stripslashes($_POST['users-message']);
//send email
$maiL_status = mail($admin_email, "$subject", "Contact Email: " . $email . "\n" . "Name: " . $name . "\n" . "Category: " . $category . "\n" . "Message: " . $message);
//Email response
echo '<h4 class="text-center">THANK YOU.</h4>';
echo '<h6 class="text-center">Your message is now being processed.</h6>';
echo '<h6 class="text-center">We will get back to you promptly.</h6>';
header("Location: index.html?message=ThankYou");
}else{
echo '<h4 class="text-center">Problem</h4>';
}
?>
So my question here is - how can I submit my form with from action using mail.php and redirect back to html page with a message. I am open use Jquery or javascript. I wanna send back the echo response to html page and show message in html page.
I have gone through a lot of stackvoerflow post but I couldn't figure out
How do I make a redirect in PHP?
PHP Pass Data with Redirect
Edit:
I have solved this with javascript using -
let msg = window.location.href;
msg = msg.split('=')[1];
console.log(msg);
if(msg!=null){
$('#form_id').hide();
$('#repos').show();
$('#repos').text(msg);
}
I wrote a structure of program that you can refer to. Part of the code is omitted.
<?php
// Process anything about sending mail.
if (isset($_POST['users-name'])) {
// Some codes are omitted
$msg = "";
$hasError = true;
if ($hasError) {
$msg = "xxx";
}
$redirectUrl = "/xxx/contact.php?msg={msg}";
header("Location: {$redirectUrl}");
}
?>
<html>
<script type="text/javascript">
// Process anything about show msg.
<?php
if (isset($_GET['msg']) && $_GET['msg']) {
$msg = $_GET['msg'];
// output html for init js var msg
echo "var msg = \"{$msg}\";";
}
?>
// js code: alert the msg if msg is not empty.
// Some codes are omitted
// other way: show the msg by html element.
</script>
<form action="/xxx/contact.php" method="POST">
<!-- form content -->
</form>
</html>
you have solved it alright. But, I think, the task can be simplified this way by putting this javascript outside the closing php tag in your php file, that is at the end
<script language="javascript">location.href="index.html?msg="<?php echo $msg ?>";</script>

Javascript Uncaught SyntaxError: Unexpected token

I am having issues calling my javascript function which loops through an array calling an external PHP page for each value. I get the following error in my developer console in Chrome:
Uncaught SyntaxError: Unexpected token . CSV.php?reg=1:3
When inspecting my values passing to the script everything is there as it should be:
<script type="text/javascript">
function.csvgen(){
var area = "["22","23","24"]";
var start =""2017-01-30"";
var end = ""2017-02-06"";
var len = area.length;
for (i = 0; i < len; i++) {
$.getScript("CSVGEN.php?area="+area[i]+"&start="+start+"&end="+end);
}
}
</script>
I'm not exactly a good programmer and have used very little Javascript (which required assistance from this wonderful forum as well...). Here is my code for the page. The point of the code is to let the user select a number of areas based on their region as well as a start date and an end date and then generate a CSV from my MS SQL database for each, the code for which is in the called CSVGEN.PHP file. I've tested the CSVGen file with a manually generated link and it works, it does not if I put the static link inside the for loop.
<script type="text/javascript">
function.csvgen(){
var area = "<?php echo json_encode(array_values($_POST['arealist'])); ?>";
var start ="<?php echo json_encode($_POST['start']); ?>";
var end = "<?php echo json_encode($_POST['end']); ?>";
var len = area.length;
for (i = 0; i < len; i++) {
$.getScript("CSVGEN.php?area="+area[i]+"&start="+start+"&end="+end);
}
}
</script>
<?php
$page_title="CSV Generator";
include("\Include\header.inc");
include("\Include\connect-db.php");
include("\Include\CSVGen.php");
$error="";
$start_date=date("Y-m-d");
$end_date=date("Y-m-d", strtotime("+7 days"));
if(isset($_GET['reg']))
{
$reg=$_GET['reg'];
}
else{
$reg='1';
}
if($start_date>$end_date){
$error = 'ERROR: End Date cannot be before Start Date!';
}
if ($error != '')
{
echo '<div class="container">
<div class="row">
<div class="alert alert-danger col-md-12">'.$error.'
</div>
</div>
</div>';
}
$sqlareas="SELECT Area_Name, Region_ID, Area_ID FROM Listings_Areas WHERE region = '$reg'";
$arearesult= sqlsrv_query($conn, $sqlareas, array(), array("Scrollable"=>"buffered"));
$areacount = sqlsrv_num_rows($arearesult);
function renderForm($arearesult, $areacount, $start_date, $end_date){
?>
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<form id="CSV" name="form1" method="post">
<div class="col-md-2 col-md-offset-1">
<p><select name="arealist[]" size="<?php echo $areacount ;?>" multiple="multiple" tabindex="1">
<?php
while($areas=sqlsrv_fetch_array($arearesult)){
echo'<option value="' . $areas['Area_ID'] . '">' . $areas['Area_Name'] . '</option>';
}
?>
</select>
</div>
<div class="col-md-3">
<strong>Start Date: </strong> <input type="date" name="start" value="<?php echo $start_date; ?>" />
</div>
<div class="col-md-3">
<strong> End Date: </strong> <input type="date" name="end" value="<?php echo $end_date; ?>" />
</div>
<div class="col-md-2">
<input type="submit" onclick="csvgen()" name="submit" value="Get CSVs">
</div>
</form>
</div>
</div>
<?php
}
if($_SERVER['REQUEST_METHOD'] === 'POST'){
print_r(array_values($_POST['arealist']));
echo $_POST['start'];
echo $_POST['end'];
}
else{
renderForm($arearesult, $areacount, $start_date, $end_date);
}
?>
I've tried removing all tabbing/spacing and clearing any potential illegal characters that might have snuck in, but it's showing a period, which I can only guess is referring to either my area.length which as far as I can tell from the manual is right and I still get the error if I remove it or $.getscript, but I've used that elsewhere in similar functions with no issue so I don't know why that would be wrong, or how to replace it.
At the very begining of the script you have:
<script type="text/javascript">
function.csvgen(){
//...
which should be:
<script type="text/javascript">
function csvgen(){
//...
with a space instead . between function and csvgen.
NOTE: this area = "["22","23","24"]"; is also wrong. Use diferent quotes (like area = '["22","23","24"]';) or escape the inner quotes (like area = "[\"22\",\"23\",\"24\"]";)
Find a good javascript tutorial and learn more about how to declare function in javascript.

Need an Ajax call to destroy session

I have a script where when a user get verified he/she is brought to Home.php. At the moment Home.php doesn't do much. But in the bottom left hand corner I have a log out button. And as you know when the user clicks on this button he expects his session to be destroyed and for him to be redirected to a log in page. Unfortunately you can't make a click listener in php. I have browsed for an hour looking for a solution but I have not been able to find the right key word or something.
This is my code
EDIT: You only really have to read some code from Home.php the est is only if someoe wants to run the code if they are not sure of their answer
Index.php(Login Page)
<?php
session_start();
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset ($_POST["Username"])&& isset($_POST["Password"]))
{
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$_SESSION["username"] = $Username;
$DB_Check = " SELECT * from users Where username = '".$Username."' and password = '".$Password."' " ;
$result = mysql_query($DB_Check);
if(mysql_fetch_assoc($result) === false){
$error = "invalid username or password";
}else{
header( 'Location: Home.php' ) ;
}
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Index.css"/>
<title>Login</title>
</head>
<body>
<div id="main">
<div class="messages">
<?php
if(isset($error))
echo $error; ?>
</div>
<form action="Index.php" method="post">
<h5>Diary Name:</h5>
<input name="Username" type="text"/>
<h5>Password:</h5>
<input name="Password" type="password"/>
</br>
</br>
</br>
<input name="login" type="submit"/>
</form>
<p>Click HERE to register.</p>
</div>
</body>
</html>
Home.php
<?php
session_start();
echo "Username = " . $_SESSION["username"] . " !";
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$submission = "INSERT INTO `virtualdiary`.`entries` (`entry`) VALUES ('". $entry . "')";
mysql_query($submission);
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Home.css"/>
<title>Home</title>
</head>
<body>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="87">
<?php
if (isset($_POST["entry"])){
echo $entry;
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="LogOut">Log Out</button>
</body>
</html>
From what I have found from searching around I will need a Home.js file with an ajax call. I don't know the first thing about Ajax so I will probably need code to paste or a very blunt tutorial.
Thanks
You could change the logout href to /Logout.php, and in Logout.php have
<?php
session_start();
session_destroy();
header('Location: /Index.php');
?>
That will simply destroy the users current session, then redirect the user back to the Index.php page.
The AJAX way would be (using jQuery, I can't remember the vanilla JS syntax for ajax calls)
$.ajax({
type: 'GET',
url: '/Logout.php',
success: function(msg) {
if (msg == 'loggedOut') {
window.location.href = 'Index.php';
}
}
});
And then you'd need to change Logout.php, instead of the header line, make it echo/die/print loggedOut (or a json string which would probably be better, but this is just an example).

can I get text from html and put it into variable in php without submitting a form?

I have a form in html:
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
and I want to get the value of this input in php without submitting it in a form.
this is my javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
pName= $(this).attr("name");
console.log(pName);
});
});
My php:
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
what I want is. you click on the picture,
1.the value of the name attribute of the picture is going to be saved into the variable pName (javascript),
2.it then goes into the form and changes the value of the form to the variable pName (javascript),
3.php picks up the value of the form (which should now be equal to pName),
4.then stores it into a variable $pName (php).
5.I also want $pName (php) to be globally used throughout all the pages of the website.
edit
this is my index page:
<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
what I want: click on the image then you get sent to the project page where (php) $pName is equal to the value of (javascript) pName
project page:
<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
<?php
echo $newRecord;
?>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
HTML:
do you have more then 1 image on page? its better if you add ID in image. No need for form and hidden fields for what you want done.
make sure your img has ID like <img id="imageID"...
JavaScript:
var pName= null;
$(document).ready(function(){
$('#imageID').click(function(){
pName= $(this).attr("name");
$.post("project.php", { pNameChange: pName },
function(data) {
// do something here.
});
});
});
above code should work as expected. Now in project.php > $_POST['pNameChange'] should receive the value of pName (image's name attr).
I don't understand what you want when you said $pName available globally on all pages. Please elaborate further, may be look into storing it as cookie/session?
EDIT:
Consider using session to pName value... by simple starting/resuming session in start of file:
<?PHP
session_start();
and then...
to set/update value:
if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];
and then use $_SESSION["pName"] instead of $pName on all pages.
Try Ajax method in jQuery , hope it solves your problem
https://api.jquery.com/jQuery.ajax/
or
https://api.jquery.com/jQuery.post/
Actually, you do not need AJAX for this, all your index.php does it passes the image's name to project.php so try:
In index.php:
<form name='form1' method="post" action='project.php'> <!-- form attributes given -->
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
Javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
//onclick of image, we will save the image name into the hidden input
//and submit the form so that it goes to project.php
$('input[name="pNameChange"]').val($(this).attr("name"));
$('form1').submit()
});
});
And in your project.php:
//now project.php can get the posted value of 'pNameChange'
//There is no input field with `name`->`value`, so $_POST['value'] is invalid.
$pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';
And if you need this value across multiple pages, global will not work, use sessions.
ok this "additional" answer is to focus on session only. use the codes for client-end from my previous answer and try this on server-end.
index.php Page:
<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';
project.php Page:
<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
$_SESSION['pNameChange'] = $_POST['pNameChange'];
$pName = $_POST['pNameChange'];
}
hope it helps

Redirect happens before form data is processed

What i'm trying to do here is to sends an email to a salesperson notifying them that their client has viewed a google docs presentation.
The query's Num=val is a serial number that I use to get the actual google doc's url out of a database and stuff it into a form.
My problem is that the page redirects before the data is retrieved, and ends up going to the default for the site, nitrofill.com.index
The gdform.php file has the header redirect, which works fine if I don't try to process the form when the page loads. Heres the code:
<?php
$sn=$_GET['num'];
echo $sn;
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$selectSQL = "select * from `Presentations` where `serialnum` ='" . $sn ."'" ;
$result = mysql_query($selectSQL) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_BOTH);
?>
<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("notice");
frm.submit();
}
window.onload = myfunc;
</script>
<title>Nitrofill Document</title></head>
<body>
<form id="notice" action="http://m3sglobal.com/gdform.php" method="post">
<input type="hidden" name="subject" value="<?php echo (urldecode($row['recipient'])) . " has viewed the document you sent them."; ?>" />
<input type="hidden" name="redirect" value="<?php echo ((urldecode($row['docurl']))); ?>"/>
<label>Email:</label><input type="text" name="email" value="<?php echo (urldecode($row['tracker'])); ?>"/>
<label>Comments:</label><textarea name="comments" cols="40" rows="5">
Document Viewed:<?php echo ((urldecode($row['docurl']))); ?>
When Accessed:<?php echo ((urldecode($row['last_accessed']))); ?>
</textarea>
<input type="submit" name="submit"/>
</form>
The gdform.php does the redirect like this:
while (list ($key, $val) = each ($query_vars)) {
fputs($fp,"<GDFORM_VARIABLE NAME=$key START>\n");
fputs($fp,"$val\n");
fputs($fp,"<GDFORM_VARIABLE NAME=$key END>\n");
if ($key == "redirect") { $landing_page = $val;}
}
fclose($fp);
if ($landing_page != ""){
header("Location: " . $landing_page);
} else {
header("Location: http://".$_SERVER["HTTP_HOST"]."/");
}
Thanks for looking!
Code in HTML is executed top-down. You're submitting as soon as you get to that block of JavaScript, which is before you even render the form on the page.
Move your JS code to the bottom of the page, or execute it after the DOM is ready.

Categories

Resources