Solved

Save data of form to database with jquery, ajax and php

Posted on 2012-12-31
7
1,663 Views
Last Modified: 2013-01-14
Hello everyone!

I am working on a website which needs to collect some type of data from the visitors and then send it to a database/file.

I did an example to illustrate:

form_img
So, on the left I have a form so the users can submit their company's name and annual income. Then I have a counter that after processing the data will update the values.

What I need here is instead of the form data goes to an email, I need the data to be sent to a database or file and then the same data will update the values of the number of companies that submited the form and the accumulated annual income of all companies.


What I have so far

-the hmtl page with form and counter:

	<div id="container">


		<div id="form-submit">
			<form action="#" method="get">
				
				<label for="name-of-company">Company Name: </label>
				<input type="text" name="name-of-company" value="" id="name-of-company" /><br>
	
				<label for="annual-income">Annual Income   : </label>
				<input type="text" name="annual-income" value="" id="annual-income" /><br>
				
							
				
				<button type="submit" id="submitBtn">Submit</button>
			</form>

		</div>

		<div id="counter">
			<ul>
				<li><h4>Number of companies</h4></li>
				<li>0</li>
				<li><h4>Accumulated Annual Income</h4></li>
				<li>0</li>

			</ul>

		</div>




	</div><!--end container-->

Open in new window



-Using jquery/ajax to send the submitted data to a php file:

	<script>

	$('form').on('submit', function() {

		$.post('save.php', $(this).serialize(), function() {
			console.log('completed!');

		});


		return false;
	})



	</script>

Open in new window


-the php file(save.php):

<?php

$f = fopen('data.txt', 'w');
fwrite( $f, $_POST['name-of-company']);
fwrite( $f, $_POST['annual-income']);
fclose($f);

Open in new window



So, I have a simple setup (with my limited knowledge of jquery/php), that sends the data from the form to a php file that writes the data to a simple .txt file(data.txt).

I would like to ask if this aproach is relaiable and secure and how would I send the data for a database and then grab the values and update the counters with no manual editing.

Also, I would need the submitted data rendered in an html page so the admin of the site can see the submited companies and have that reference. This page needs to be secure, so only the admin can see it.

This is my first question, not sure if I am following the protocol, and if I am asking too much. Thank you and sorry for my bad english
0
Comment
Question by:joao_c
  • 3
  • 2
  • 2
7 Comments
 
LVL 39

Accepted Solution

by:
Pratima Pharande earned 167 total points
ID: 38733975
0
 
LVL 39

Expert Comment

by:Pratima Pharande
ID: 38733981
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 333 total points
ID: 38734467
There are a lot of moving parts to this -- it's not really a question so much as a requirement for application development, and if you have any time/money value in this exercise, you might be better off hiring a professional developer instead of trying to learn to be a professional developer and then writing the code.  Let's try to deconstruct...

The page needs to be secure.  This article describes PHP client authentication.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

Basics of jQuery and AJAX:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/A_10712-The-Hello-World-Exercise-with-jQuery-and-PHP.html

A good learning tool for simple applications in PHP and MySQL:
http://www.sitepoint.com/books/phpmysql5/

How would I do it?  First I would set aside the jQuery and AJAX part of things and just get the HTML submit correct.  Once I knew that the form was working, I would add the data base part (to replace the current text file).  The general design would have one row for each submission.  The response from the server would count and sum the DB information.

It looks like you have a lot of it together already.  Best of luck with the project, ~Ray
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:joao_c
ID: 38746255
So, let me post my progress:

Jquery

	<script>


	function clearInput() {
		$("#myForm :input").each( function() {
			$(this).val('');
		});
	};



	$("#submitBtn").click( function() {


		var result = $('#result');
		var company = $('#myForm > #name-of-company');
		var ai = $('#myForm > #annual-income');
		var characterReg = /^([a-zA-Z0-9]{2,50})$/; //only letters and numbers
		var aiReg = /^([0-9]{3,15})$/; //only numbers
		var inputVal = ai.val();
		var inputValName = company.val();

		if ( !characterReg.test(inputValName) ){

			result.text('that\'s not a valid name!');
			company.addClass('wrong');
			

		} else if ( !aiReg.test(inputVal) ) {

			result.text('only numbers!');
			ai.addClass('wrong');
			company.removeClass('wrong');



		} else {

			$.post( $("#myForm").attr("action"), 
			$("#myForm :input").serializeArray(), 
			function(info){ result.html(info);
			});
			clearInput();
			company.removeClass('wrong');
			ai.removeClass('wrong');

		};


	});



	$("#myForm").submit( function() {
		return false;	
	});



	</script>

Open in new window


db.php

<?php
	  $conn = mysql_connect('localhost', 'root', '');
	  $db   = mysql_select_db('dados_db');
?>

Open in new window


save.php

<?php
	
	include_once('db.php');


	$name = $_POST['name-of-company'];
	$ai = $_POST['annual-income'];

		if(mysql_query("INSERT INTO empresas VALUES('$name', '$ai')"))
		  echo "Data sent!";
		else
		  echo "Data not sent!";
	
?>

Open in new window



My follow-up questions:

-The code I have so far is working, but should/can I improve it or it's ok like this?
-Also, see the image again:
myform
I need the values of "Number of companies" to be updated with the number of entries in the Database.

And the "Accumulated annual income" to be also updated, adding up all the anual incomes, if I have 2 entries in the database with the annual incomes being 5 in one and 4 in other, the value should be added up and rendered in html as "9", where is 0 now.

Thank you so much.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 333 total points
ID: 38746663
To get the number of result rows from a SELECT query, you might be able to use mysql_num_rows().

To get the sum of values from a column, you can use the MySQL SUM() function.

See also: http://php.net/manual/en/mysqlinfo.api.choosing.php
0
 

Author Comment

by:joao_c
ID: 38766580
Ray_Paseur, thanks for the reply. That is what I needed.

Just to finish this question, consider the following exampe:

-My html and css renders like so:

html
-Html:
	<span id="euro">€</span>
	<span id="number">0</span>
	<span id="separador">.</span>
	<span id="number">0</span>
	<span id="number">0</span>
	<span id="number">0</span>
	<span id="separador">.</span>
	<span id="number">3</span>
	<span id="number">6</span>
	<span id="number">9</span>
	<span id="separador">.</span>
	<span id="number">9</span>
	<span id="number">9</span>
	<span id="number">9</span>
	<li id="text_vendas">accumulated annual income</li>

Open in new window


How would I replace these "dummy" numbers with the number returned from the  MySQL SUM() function?

-Let's say in the beggining the number returned from the mysql sum is "1256"; I need to keep the zeros on the left and only affect the 4 numbers on the right. How would I do that?

Thanks a lot
0
 

Author Closing Comment

by:joao_c
ID: 38776358
Thanks everyone for the help.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
In this tutorial viewers will learn how to embed videos in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <video> tag to insert a video. Define the src as the URL of your video; this is similar to …
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now