I'm trying to create a html form in the file index.html from where I can query a text file for a line of characters through PHP via the file searchFile.php, get the specific line and display it in said form in index.html.
My problem is that I nothing is displayed in my Search Results field, neither the error message or a search result.
Update! I've investigated my problem further and I realized that the way I'm using the Search button doesn't allow for any echoes to stay displayed on the page before the page is updated again and the echocontent is removed. Still, I don't know how I should solve this issue without using two buttons, one for searching and one for getting the result of the search.
This is what I've come up with so far:
index.html
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
$(function() {
// getting the search term
var searchString = $("#search_box").val();
// forming the searchString
var data = 'search='+ searchString;
//if searchString is not empty
if(searchString) {
// call ajax
$.ajax({
type: "POST",
url: "searchFile.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
</script>
<form name="theForm" method="post">
Name: <input type='text' onclick="ajaxFunction();" name='search' class='search_box' id='search_box'/> <br />
<input type='submit' value='Search' class="search_button" ><br />
</form>
<div id="searchresults">Result: <span id="results" class="update"></span></div>
</body>
</html>
searchFile.php
<?php
$search = explode(' ', $_REQUEST["search"]);
$lines = file('file-export.txt');
foreach($lines as $line)
{
if(strpos($line, $search[0]) !== false && strpos($line, $search[1] !== false)) {
echo '<div id="searchresults">' . $search . '</div>';
}else{
echo '<div id="searchresults">' . "No match" . '</div>';
}
}
?>
Edit: updated the button field with action="searchFile.php"
Edit 2: Functioning Search button
Edit 3: Minor changes
You are trying to find a search string in the block that doesn't exist
var searchString = $("#search_box").val();
You have no block with id search_box, only with class search_box, that is $(".search_box") or
<input type='text' onclick="ajaxFunction();" name='search' class='search_box' id='search_box'/>
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I made a script to open all image on folder include form on it. Every time I post submit, page refreshes to the top of the page. How can I prevent it from refreshing after I hit submit?
<?php
$folder = ".."; //folder tempat gambar disimpan
$handle = opendir($folder);
echo '<table cellspacing="5" cellpadding="1" width="100%" >';
echo '<tr>';
$i = 1;
$fileGambar = array('JPG', 'jpg');
while(false !== ($file = readdir($handle))){
$fileAndExt = explode('.', $file);
if(in_array(end($fileAndExt), $fileGambar)){
echo '<td style="border:1px solid #000000;" align="center" >
<div class="hvrbox">
<img src="../'.$file.'" alt="Mountains" class="hvrbox-layer_bottom"
width="100%" />
<div class="hvrbox-layer_top">
<div class="hvrbox-text">'.$file.'</div>
</div>
</div> <br></br>
<form method="post" name="f1">
<b><u>'.$file.'</u>:</b>
<input type="hidden" name="namafoto1" value="'.$file.'">
<input type="submit" name="upload" value="UPLOAD" />  
</form>
<form method="post" name="f2">
<input type="hidden" name="namafoto" value="'.$file.'">
<input type="number" min="1" max="10" value="1" name="jumlah"
maxlength="3" size="3" >
<input type="submit" name="submitcetak" value="CETAK">  
<input type="submit" name="delete" value="HAPUS CETAK" />
</form
<script type="text/javascript" src="js/jquery-1.11.3.min.js">
</script>
<script type="text/javascript" src="js/hover-box.js"></script>
</select>
</td>';
if(($i % 1) == 0){
echo '</tr><tr>';
}
$i++;
}
}
echo '</tr>';
echo '</table>';
?>
and submit script is
<?php
// Turn off all error reporting
error_reporting(0);
$txtx = "../upload.txt";
if (isset($_POST['upload']) && isset($_POST['namafoto1'])) {
$fh = fopen($txtx, 'a++');
$txtx=$_POST['namafoto1'].PHP_EOL;
fwrite($fh,$txtx); // Write information to the file
fclose($fh); // Close the file
}
// $txt = "../cetak.txt";
// if (isset($_POST['submitcetak']) && isset($_POST['namafoto'])) {
// $fh = fopen($txt, 'a++');
// $txt=$_POST['namafoto'].PHP_EOL;
// fwrite($fh,$txt); // Write information to the file
// fclose($fh); // Close the file
if (isset($_POST['delete']) && isset($_POST['namafoto'])) {
rename('../print/'.$_POST['namafoto'], '../'.$_POST['namafoto']);
delLineFromFile ();
//echo "<meta http-equiv='refresh' content='1'>";
}
?>
Every time I press submit button, page refreshes and scrolls to the top of the page. Help me make it not refresh to the top of the page.
It is hard to write answer in code as the question is too broad and general but here are some links to get you started. If I understand correctly, you want to submit the form without page refresh. For that, use ajax. Serialize your form and post it using ajax so it won’t reload. Something like this:
//Serialize your form here
var formData = $("#yourFormID").serialize();
$.ajax({
type: "POST", //You are posting data so this is a post method
url: "post_data.php", //Your URL or link to php file which posts data
data: formData, //The data passed, which is the variable of serialized form
dataType: "json", //Data type json
success: function(data) {
//var parse = jQuery.parseJSON(data);
//if successful parse the data and display here
//use console.log(data) to see if you have data
},
error: function() {
alert('error handling here');
//use console.log(“error occurred”) to see if it failed
}
});
Link to Jquery Ajax
And additionally, if you want the page to refresh but scroll to a specific part of the page, try something like this:
//This is your HTML
<div id="bottom"></div>
//After posting in your php, use the code below
header('Location: contact.php#bottom');
As mentioned HERE
Hope this helps. Happy coding :)
Looking at you question, it seems you have alot of forms,
NOTE: am using jQuery
$("#id_of_the_form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form which will reload the page
var form = $(this);//get the form
$.ajax({
type: "POST",
url: "The php script posting the form to",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
// show response from the php script.
}
});
});
I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)
Looking for a solution to search through a list of Zip Codes. I have a text file with a bunch of zip codes that we service. Would like to have a form on the website asking for the user to input their zip code to see if we service that area. If it does, display a message saying that we do, if not, saying that we don't. Thought PHP would be the best solution for my problem, but I'm a total noob when it comes to that.
I have my form set up, I'm just not sure how to search the text file and display the answer in another div?
<form action="zipcode.php" method="post">
<input type="text" name="search" />
<input type="submit" />
</form>
UPDATE: Preferably an AJAX solution!
AJAX method (tested)
PHP handler
(find_in_file_ajax.php)
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found";
}else{
echo "ZIP code does not exist";
}
?>
HTML form
<!DOCTYPE html>
<html>
<head>
<style>
.update {
font-family:Georgia;
color:#0000FF;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "find_in_file_ajax.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="container">
<div>
<form method="post" action="">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults">Search results: <span id="results" class="update"></span>
</div>
</div>
</div>
</body>
</html>
Original answer
Tested
First the file needs to be accessed via file_get_contents, then explode each entry and extract the zip code search in question.
Assuming the zipcodes.txt file is in the following format:
43505
43517
43518
43526
43543
NOTE: If 43505 is queried, it will be found. Unlike 4350 or 3505 will not be found, so it's a unique query.
Consider the following:
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found.";
}else{
echo "ZIP code does not exist";
}
?>
Saw your edit...the below is PHP.
I would do something like
$lines = file("/path/to/file.txt", FILE_IGNORE_NEW_LINES); //reads all values into array
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "found zip code";
}else{
echo "zip code does not exist";
}
As long as there isn't a VERY LARGE amount of zip codes...this should be fine. Also, what is the format of your file? This may not work.
I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information
i'm trying to send the value of the search textbox via jquery on keydown to the php page so that it can display the results containing the search keyword. however, the php page is not reading $_POST of the input textbox [not button].
html:
.keydown(function() {
//create post data
var postData = {
"bsearch" : $(this).val()
};
//make the call
$.ajax({
type: "POST",
url: "quotes_in.php",
data: postData, //send it along with your call
success: function(response){
$("#bquote").html(response);
}
});
})
. . .
<!-- Begin Search -->
<div id="search" style="display:none;">
<input type="text" class="bsearch" name="search" value="Search" />
</div>
<!-- End Search -->
php:
include_once "inc/class.quotes.inc.php";
$quotes = new Quotes($db);
if (isset($_POST['search']))
//$quotes->searchQuotes();
echo 'Searching. . ';
else
$quotes->displayQuotes();
it seems it is not reading the $_POST['search'] because it does not echo the text 'Searching. .' but instead goes to the else part and displays the quotes.
i tried this code to find out what is happening:
echo "<pre>";
print_r($_POST);
echo "</pre>";
this displays an empty array. what am i doing wrong?
either change postData object key to "search" or check for $_POST['bsearch']
var postData = {
"search" : $(this).val()
};