Jump to content
Larry Ullman's Book Forums

Recommended Posts

I have file "phone.csv" for Phone number details and want to get the required phone though forms. Please help me.

"phone.csv" contains four columns without header name: like - "James", "Cat", "26", " 99556745" . The list contains around 60 rows.

 

<html><head></head><body>
<?php
$file = fopen("phone.csv","r");
while(! feof($file))
 {
 print_r(fgetcsv($file));
 }
fclose($file);
?>
<form action="check.php" method="post">
<p>Enter Name: <br>
<input type="text" name="username" size="10" />
<input type="submit" name="submit" value="Enter" /></p>

NAME: $col1  <br>
NICK NMAE:  $col2  <br>
AGE: $col3 <br>
PHONE: $col4
</form></body></html>

 

I am unable to write the php code for the "check.php" and link to the form. Kindly help me out.

Share this post


Link to post
Share on other sites

To be clear, are you wanting to use Ajax or not? Your subject includes Ajax but you don't mention it in the post.

Share this post


Link to post
Share on other sites

guruje, we want to help you, but it's not clear what you want to do.

Please better explain what you want to do.

 

From what I can tell, you have a CSV file (not an SCV file, right?) with phone number data in it, and you want to be able to compare the data in the file to data entered by the user, yes?

If that is not the case, please explain what you want to do.

 

Also, what are the four categories in your phone.csv file?

 

Lastly, do you need to use Ajax or JavaScript at all for this? It seems like PHP alone would be enough.

Please let us know, and we'll try to help.

Thank you.

  • Upvote 1

Share this post


Link to post
Share on other sites

Thank you Mr. Hartley. I have a CSV (coma separated value file )- "phone.csv" which stores the phone number details form a html file thorugh php file. There is no header for this file and it is append mode. The values looks -

 

James Cat 26 99556745

Jhony Micy 32 8767565

Albert Major 44 6767656

The first value is for Name; second for Nick name, third for age and last value for phone number.

Like that "phone.csv file have four columns and arround 60 rows - which is daily getting appended.

 

Now I want to get the phone number & age details though another HTML Form by creating another php file "check.php" and for that JSON /AJAX code to be created so that the result to be appeared below the HTML form. If PHP is sufficient then well & good but I am unable to codify..

Share this post


Link to post
Share on other sites

I would start by learning JavaScript and Ajax. Someone here might be able to provide you with the right code, but that's only if you do everything else right and don't have problems. By learning JavaScript and Ajax, you can not only get this working but know why it works.

Share this post


Link to post
Share on other sites

With a couple of lines of code in PHP, you can neatly display the contents of the phone.csv file, if that's what you want.

If you want to be able to actually search for phone numbers and ages, that will require an HTML form and a few more lines of code.

You do not need JavaScript/Ajax for any of this. The only thing JavaScript/Ajax will give you is the ability to avoid reloading the page when you submit the form (assuming you even need a form in the first place).

Again, I apologize, as I'm still not sure what you want. If you could please answer the following questions, we might be able to better help you:

 

1) Do you only want to be able to view the contents of the file (in, for example, a table)? If not, do you want to also be able to search for data in the file? What about inserting data into the file? Are you doing that manually, or do you want to be able to do that via a Web interface/PHP script?

2) Have you considered using a database instead of a file? That would probably be easier to maintain and more efficient?

3) Is JavaScript/Ajax essential? Truth be told, PHP by itself should suffice. If you're new to all this, I would recommend not dealing with Ajax yet, as it will complicate the code.

 

Please let us know. Thanks.

Share this post


Link to post
Share on other sites

I really appreciate all the forum members including Mr.Larry for the cool & timely support for the newbie. That shows the effectiveness of the forum which I never seen any where.

Then coming to the point, as asked by Mr. Hartley, I use the available of data of "phone.csv" in another HTML form where in the details will be shown on click and the HTML code for the search will be:

 

 

<HTML>
<HEAD>
<TITLE>PHONE NUMBER FINDER</TITLE>
</HEAD>
<BODY>
<div style="text-align=center; background-color: #C0C0C0; width:300px; height:350px; border:2px double blue;"> 
<P><FONT SIZE="+1">FPHONE NUMBER FINDER</FONT><hr color="#0099FF"> </P>
<FORM NAME="phone" METHOD="post"> <!-- How to linck search.php file" -->

<P>Enter Name: 
<select name="$name"  >
<option>    <!-- the name list shall fetch from "phone.csv" -->
<option>
</select></p>

<P><INPUT TYPE="button" VALUE="SUBMIT" name="AddButton" onClick="get(this.form.input_A.value)">
 <input type="Reset"  name="reset" value ="RESET" onClick ="(this.form);" /></P>
<hr color="#0099FF">

<P>Name: <INPUT TYPE=TEXT NAME="Ans1" SIZE=10></P>
<P>Nick Name: <INPUT TYPE=TEXT NAME="Ans2" SIZE=10></P>
<P>Age: <INPUT TYPE=TEXT NAME="Ans3" SIZE=10></P>
<P>Phone: <INPUT TYPE=TEXT NAME="Ans4" SIZE=10></P>
</FORM>
</div>
</BODY>
</HTML>

  1. Yes I want the result in side the web HTML form.
  2. For these 60 rows & 4 column, I feel database may not require.
  3. I want the result either in PHP /AJAX /J SON /JAVA SCRIPT - Which ever is acceptable.

.

Share this post


Link to post
Share on other sites

guruje, we're more than happy to help, and we understand that English is not your native language, so things can be difficult, but with that said, we still cannot understand what you want.

Please do us a favor, and without using any technical terms (like "HTML form", "JavaScript", "PHP", "CSV file", etc.), please just tell us what you want.

In other words, please tell us exactly what you want your site to do, and then we can hopefully help you.

Thank you.

  • Upvote 2

Share this post


Link to post
Share on other sites

Thank you Mr. Hartley,

 

First of all I apologize for not presenting the question in a proper and readable manner.

In a layman language, i furnish below the problem once again.

 

I have a webpage that collects details of phone numbers and stores in a excel sheet file -"phone.csv".

Now i like to put another UI webpage linking that excel sheet for searching the Phone numbers by submitting name so that the phone & other details will be appeared in that form it-self.

 

with regards, GURUJE

Share this post


Link to post
Share on other sites

The way of saving data does not really matter for what you try to achieve. CVS, JSON, or a database will all work if done correctly. However, The database solution will generally perform best of these solutions. It will also be easier to maintain.

 

I'm getting this is pretty much what you are looking for:

1. Ajax search for name

2. If a match is found and selected in the select element, you want to display the information below that?

 

Look at autocomplete script with Ajax for PHP. That will give you some clues about how this can be done.

Share this post


Link to post
Share on other sites

guruje, there are a lot of ways you can deal with this, but all of the solutions can be broken up into two basic groups:

1) Read the CSV file contents from PHP, and then use PHP to handle everything.

2) Make an Ajax call from JavaScript to a PHP script, which will return the contents of the CSV file to the JavaScript, at which point, you no longer need to call a PHP script, and everything can be handled client-side, which will make things more responsive.

 

I should mention that there's actually a third in-between solution:

3) Use PHP at the beginning of your script to get the CSV file contents, and then echo the contents into a JavaScript variable, at which point, you can handle everything client-side with JavaScript, and you won't have to use Ajax at all, which can be confusing at first.

 

Given your situation and experience with the various Web technologies, I recommend the third option, which is what I will demonstrate below. The first thing we need to do is properly get the CSV file contents. The easiest way to do this is with the file_get_contents PHP command. As a side note, I should mention that CSV is not a Microsoft Excel-proprietary format; far from it. CSV is simply a comma-separated list of values, which Excel is also able to interpret and properly parse. A CSV file is really nothing more than a text file with commas being used at the delimiters.

 

Anyway, for the sake of this demonstration, I made a phone.csv file with the following contents:

 

James,Cat,26,99556745
Jhony,Micy,32,8767565
Albert,Major,44,6767656
John,Walrus,60,7983412
Paul,Whale,62,2879123
George,Ravi,61,1287912
Ringo,Boy,63,1238899

 

Just as a simple test to make sure you can get the file contents all right, please put the phone.csv file in the same directory as the following index.php script, which you then need to execute from your server or virtual server:

 

<?php

 echo file_get_contents('phone.csv');

?>

 

The contents of the phone.csv file should be echoed to the screen.

 

Next, let's write a script that will actually store the contents of the file in a JavaScript variable. This is a bit tricky, but the key is to declare a JavaScript variable, and for the value being stored in the variable, you must echo the contents of the phone.csv file using PHP.

 

The following is an example of how to do this with all the other necessary HTML tags as well:

 

<!DOCTYPE html>

<html lang="en">

 <head>

   <meta charset="UTF-8">

   <title>Searching for phone number details</title>

 </head>

 <body>

   <script>

     var phone_data = '<?php echo str_replace("\r\n", '|||', file_get_contents('phone.csv')); ?>';

     alert(phone_data);

   </script>

 </body>

</html>

 

A few things to note with this code:

1) The str_replace function needs to be used to convert the newlines in the phone.csv file to non-newline characters. If you don't do this, then the JS string variable phone_data will not be properly declared and an error will occur.

2) You can choose any delimiter to replace the newline character(s), but I chose three vertical bars (|||) because I'm assuming that no such combination of characters would ever show up in the actual data.

3) My phone.csv file uses a carriage return (\r) followed by a newline (\n) for newlines, which is why I ran the string replace on "\r\n". Note that double quotes must be used (instead of single quotes) in PHP to interpret the \r and \n newline metacharacters as characters with special meaning.

 

Now that our script above is properly receiving the data in a JS variable and alerting that data to the screen (for confirmation purposes), we need to actually do something with that data. There are a variety of ways we could organize the data, but for this demo, we'll simply create a multidimensional array in which each row in the phone.csv file is a row in the array, and each of those rows is then further separated into subelements on the commas.

 

The following code, which goes where the alert statement above was, will do the job for us:

 

var temp_arr = phone_data.split('|||');

var i = 0;

var len = temp_arr.length;

var phone_data_arr = [];

for (i; i < len; i++) {

 phone_data_arr.push(temp_arr[i].split(','));

}

 

At this point, all the data we need is organized in the phone_data_arr multidimensional array variable in JS. Now, we're ready to write the HTML form and the JS logic to handle the search.

 

First, put the following basic HTML form in the body element above the script element:

 

<form>

 <label for="phone_num">Phone number:</label>

 <input type="text" id="phone_num" name="phone_num">

 <input type="submit" value="Submit">

</form>

 

Note that it would probably be best to include the action and method attributes to the form element, but for this demonstration, I'm neglecting those.

 

The next thing to do is connect a JS event handler to the form submit action so we can perform a search on the JS side. Please put the following event handler below the for loop written above in the JS:

 

document.forms[0].onsubmit = function () {

 return false;

};

 

Just be sure to return false at the end of the anonymous function assigned to the onsubmit event handler in order to suppress the default form behavior.

 

The last thing to do is search through the phone_data_arr variable for the entered phone number, and if it exists, output the associated data, and if not, output some sort of message telling the user that no such data exists.

 

The following code in the anonymous function will handle this:

 

var output = document.getElementById('output');

document.forms[0].onsubmit = function () {

 var input = parseInt(this.elements[0].value);

 var phone_num_exists = false;

 for (i = 0; i < len; i++) {

   if (input == phone_data_arr[i][3]) {

     output.innerHTML = 'Phone number: ' + input + '<br>Name: ' + phone_data_arr[i][0] + '<br>Nickname: ' + phone_data_arr[i][1] + '<br>Age: ' + phone_data_arr[i][2];

     phone_num_exists = true;

     break;

   }

 }

 if (!phone_num_exists) {

   output.innerHTML = 'Nobody with that phone number exists.';

 }

 return false;

};

 

Note that in order to make the above code work, you also need to add the following div below your form in the HTML:

 

<div id="output"></div>

 

That should be all you need. A few things to note:

1) You may want to add some CSS styles to jazz things up.

2) This demo assumes that the user has JS enabled. If JS is not enabled in the browser, this will not work.

3) You may need to do some parsing of the possible values that users can input. For example, you may need to account for hyphens and/or spaces in the number, etc. The alternative would be to instruct the user of the exact format they need to use for inputting formatting.

 

To finish things off, here's the final code as styled the way I prefer to write JS, which more or less follows the format outlined by jslint.com:

 

<!DOCTYPE html>

<html lang="en">

 <head>

   <meta charset="UTF-8">

   <title>Searching for phone number details</title>

 </head>

 <body>

   <form>

     <label for="phone_num">Phone number:</label>

     <input type="text" id="phone_num" name="phone_num">

     <input type="submit" value="Submit">

   </form>

   <div id="output"></div>

   <script>

     (function () {

       'use strict';

       var init;

       init = function () {

         var phone_data = '<?php echo str_replace("\r\n", '|||', file_get_contents('phone.csv')); ?>',
           temp_arr = phone_data.split('|||'),
           i = 0,
           len = temp_arr.length,
           phone_data_arr = [],
           output = document.getElementById('output');

         for (i; i < len; i += 1) {

           phone_data_arr.push(temp_arr[i].split(','));

         }

         document.forms[0].onsubmit = function () {

           var input = parseInt(this.elements[0].value, 10),
             phone_num_exists = false;

           for (i = 0; i < len; i += 1) {

             if (input === parseInt(phone_data_arr[i][3], 10)) {

               output.innerHTML = 'Phone number: ' + input + '<br>Name: ' + phone_data_arr[i][0] + '<br>Nickname: ' + phone_data_arr[i][1] + '<br>Age: ' + phone_data_arr[i][2];

               phone_num_exists = true;

               break;

             }

           }

           if (!phone_num_exists) {

             output.innerHTML = 'Nobody with that phone number exists.';

           }

           return false;

         };

       };

       window.onload = init;

     }());

   </script>

 </body>

</html>

 

Well, this turned into a way longer answer than I expected. I suppose you're lucky in that I had some extra time and was feeling generous. I wouldn't expect this kind of answer in the future. In the future, you really need to better read Larry's books and the Internet to get your information, play around with things yourself, and figure things out on your own. If there's a particular point you're stuck on, we're more than happy to help, but in this case, it was more than clear that you have little to no clue about any of the technologies you're hoping to use. When that's the case, you need to start doing more reading on your own, and relying less on other people to do all the work for you (for free).

 

Anyway, I hope that helped, and good luck with your project. If there's a part of my code you don't understand, please ask. Thanks.

  • Upvote 2

Share this post


Link to post
Share on other sites

I guess too much free time is underrated.

 

After re-reading my above comment, it came across as a bit snide, so please just disregard it.

All I really wanted to say was that my post wasn't anything special.

More than anything, I just had a bit of free time and the motivation to help solve the problem.

Share this post


Link to post
Share on other sites

Thank you very much Mr.HartleySan and Mr. Conte for providing the code with explanatory notes. I am not a programmer but by studding the books and searching the net, little bit knowledge gained in HTML,CSS,JS & PHP. Due to the reason only, my questions seems silly in the codification part.

 

The following part of code executed well:

 

<?php

 

echo file_get_contents('my_phone.csv');

 

?>

And the result:

"james", cat, 26, 99567 "jhony", micy, 32, 986745 "albert" ,major,36,785665 "john" ,walrus,45,56565

 

Then coming to the PHP inside JavaScript of HTML; it is not working:

 

 

<script>

 

var phone_data = '<?php echo str_replace("\r\n", '|||', file_get_contents('my_phone.csv')); ?>';

 

alert(phone_data);

 

</script>

 

 

Kindly guide me sir.

 

With regards, GURUJE

Share this post


Link to post
Share on other sites

Are your script tags surrounded by the other required HTML that I provided?

If not, you need that.

If you have included all the necessary HTML but it's still not working, then either your PHP server is not working or JS is disable (or there is some other problem with your environment).

I tested all my code thoroughly before posting it, and it should work fine.

 

If you're still getting an error, please use a browser like Chrome that reports errors, and tell us what that error is.

Thank you.

  • Upvote 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...