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.
Related
i'm new in PHP i don't know howto use this function...output is a button but when i click on button function not run. i want to get data from database.
<?php include('config.php');
if (isset($_POST['submit'])) {
$sql = "SELECT book_name from books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "book name: " . $row["book_name"]. "<br>";
}
} else {
echo "0 results";
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<form action="check.php" method="post">
<input type="submit" name="btn">
</form>
</body>
</html>
Just change isset($_POST['submit']) by isset($_POST['btn']).
When you submit your form, you send all the input name with $_POST method.
Here you have only ONE input with name = 'btn'.
I do this test :
<?php
if (isset($_POST['btn'])) {
echo 'IT WORKS !';
}
?>
And it works for me, after clicking on "Valider" I got my echo :
Here is an example of how you can try to do it using jQuery and Ajax. I tried to explain how it works and made an example that edit your book list without reloading the page on submit. Hope it helps !
$(document).ready(function() {
// When the form with id 'get_book_list' is sumbit, I will do something :
$("#get_book_list").on('submit', function(e) {
e.preventDefault();
// This is how an ajax call looks like (one example) :
// $.ajax({
// type: "POST", // the method you will use to send the data
// url: "yourfile.php", // the php file you want to call
// data : /* the data you want to send in your php file */,
// dataType: "json", // the data type you want to receive from the php file
// success: function(response){
// // Do something if the ajax call works : here you will edit your book list
// // 'response' is what the php will return, here imagine it's a JSON (dataType = 'json')
// },
// error: function(x,e,t){
// // Do something if the ajax call return error
// }
// });
//I will do the same but without the Ajax :
// 1/ Imagine you are in the success part of the ajax call
// 2/ This is the "response" you get from the php after the select :
var response = [{"book_name" : "title1"}, {"book_name" : "title2"}, {"book_name" : "title3"}];
// 3/ Now just edit your book_list to get what you want :
// I will build a list with each title
var book_list = "<ul>";
$.each(response, function(key, book) {
book_list += "<li>"+book.book_name+"</li>";
});
book_list += "</ul>";
// I add my list in my div
$('.book-list').html(book_list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="book-list">
<!-- here you will update the list of book -->
</div>
<form action="" method="post" id="get_book_list">
<input type="submit" name="btn">
</form>
</body>
</html>
your form actions says "check.php". As a result, when you hit the submit button, you get redirected to check.php page.
your form should simply be like
<form action="" method="post">
<input type="submit" name="btn">
</form>
when action="", the if part of your php will get executed for your current case
isset($_POST['submit']) is false, you should submit some info. you can add <input type="text" name="submit" value="1" />, lets your form have info.
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'/>
i have created a simple html form with one field and it post to the server side php and the value of the field is saved to a text file.
This is the parts of the code:
Html:
<form action="videorefresh.php" method="POST">
<input name="videolink" type="text" size="70" />
<input type="submit" name="submit" value="Save Data">
</form>
php:
<?php
$open = fopen("video.txt","w+");
$txt = "video.txt";
if (isset($_POST['videolink'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['videolink'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
here everythink works fine!
I want to drive all this through Ajax so the main html form wont refresh.
so here is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./JS/videolink.js"></script>
</head>
<body>
<div id="mainform">
<div id="form">
<div>
<input name="videolink" type="text" id="videolink" size="70">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
And here is the js:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#videolink").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'videolink1='+ videolink ;
if(videolink=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "./videorefresh.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
What i do wrong here and it doesnt work?
Please help
I think you want to do is:
var dataString = '?videolink='+ name;//typo videolink
// or better put an id on the form and use serialize()
// var dataString = $('#myform).serialize();
NOT
var dataString = 'videolink1='+ videolink ;
You have the value of the input in name, videolink is undefined
this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
I know a bit php, ajax & javascript (and jQuery) - but since I am a bit of a begginer I need a little help to connect the dots for this easy task:
I want to let the user enter sometext (lets say: "I saw the sun, the sun is so nice and shiny") and I want to send this text to the server and then replace the word "sun" with "moon") - send it back to the user and write to him: "I saw the moon, the moon is so nice and shiny").
I just need help with understanding:
How do I send the text to the server using php.
How do I manipulate it and sends it back to the user.
I am sure there is a tutorial for it - I just didn't know how to look for it so I am asking here - to get a good start.
<?php
if (isset($_POST['text'])) //only execute if some text were sent to this script
{
echo str_replace('sun','moon',$_POST['text']); //manipulate the text and print it
die(); // stop script execution
}
?>
<html>
<head>
<script>
$(document).ready(function(){//when document finished to load
$('#send').click(function(){//when user clicked on send button
var text = $('#text').val();//get the text from input field
$.post('',{text:text},function(data){ // send the text to the current script as a post variable called text
alert(data); // when we received the response display it in alert window
});
});
});
</script>
</head>
<body>
<input type="text" id="text" />
<input type="button" value="send" id="send" />
</body>
</html>
no ajax needed
<?php
if ($_POST){
if ($_POST['name']){
echo str_replace('sun', 'moon', $_POST['name']);
}
}
?>
<form method="post" action="">
<input type="text" name="text" />
<input type="submit" />
</form>
if you want ajax, do this
<?php
if ($_POST){
if ($_POST['name']){
echo str_replace('sun', 'moon', $_POST['name']);
}
}else{
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$("form").submit(function(){
$.post('<?php echo $_SERVER['PHP_SELF']; ?>', {name:$("#name").val()},
function(html){
$("body").append(html);
}
);
return false;
</script>
<body>
<form method="post" action="">
<input type="text" id="name" name="name" />
<input type="submit" />
</form>
</body>
<?php
}
?>
Google is your friend. I searched for "ajax for beginners jquery php". There are hundreds, thousands of resources to walk you through this very thing. Here's one tutorial that I found:
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Try to google for ajax and jquery tutorials. Basically it would work something like this:
Get user text input and call a javascript function that will send that text to process.php page
//input page
function getAjax(text){
var $data = "sentText="+ text +";
$.ajax({
type: "GET",
dataType: 'text',
url: "process.php",
data: $data,
success: function(output){
$('#responseDiv').html(output); //output is the text echoed from the php page
}
});
}
on the process.php page you take that text from a $_GET variable
//process.php
$sentText = $_GET['sentText'];
echo $sentText.' - some new text added';