jQuery Ajax PHP

I am trying to create my first Ajax Function.  I think I am going in the correct direction.

I have a page that contains a form.  You can change a <select> option and click update and the form updates.  However, I have to pass a javascript variable to the PHP via Ajax.

All of the code is on the same page I conveniently name "ajax".  My CMS does not place ".php" or ".html" on the end of the file name.

Here is my code.  Please let me know what I need to adjust / change to make it work.  Thanks in advance.
<?php
	$state = $_POST['state'];
	
	$base = ee()->db->select('*')
		->from('rates')
		->where('state', $state)
		->limit('1')
		->get();
		
		$bsl = $base->result_array();
		
		$base->free_result();	
	
		 foreach($bsl as $row) {
			$one = $row['one'];
			$two = $row['two'];
			$three = $row['three'];
		  }
?>	


<script>		 
	function ajaxCallback() {
		var state = $('select[name="state"]').find(':selected').val();
	
		$.ajax({
      	url: "ajax",
       	type: "POST",
       	data: state,
    	});
	};
	
	$(document).ready(function () {
		$("form").on("submit", ajaxCallback);          //Your "#" is not a valid selector
    });
</script>
 
<html>
<form method="POST" action="" >
 	<select name="state">
		<option value="one">$100</option>
		<option valoe="two">$200 </option>
		<option valoe="three">$300 </option>
	</select>
</form>	
</html>
 

Open in new window

LVL 8
rgranlundAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
The 'ajax' php file must be a stand-alone file on the server.  You can't include it in the HTML file because the 'ajax' call goes back to the server.  And what you are showing is for jQuery so it must be included before the 'ajax' call or the 'ajax' call won't work.
rgranlundAuthor Commented:
@Dave.  I don't really understand this line: And what you are showing is for jQuery so it must be included before the 'ajax' call or the 'ajax' call won't work.

Also, is it written correctly?
Dave BaldwinFixer of ProblemsCommented:
It looks familiar except that the 'url' would normally be 'ajax.php'.  It is Not simple javascript.  Your HTML part should have these elements in this order:  You can link to jQuery on their web site if you want, I normally keep a copy locally.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Untitled</title>
<script src="jquery-1.11.0.min.js"></script>
<script>		 
	function ajaxCallback() {
		var state = $('select[name="state"]').find(':selected').val();
	
		$.ajax({
      	url: "ajax",
       	type: "POST",
       	data: state,
    	});
	};
	
	$(document).ready(function () {
		$("form").on("submit", ajaxCallback);          //Your "#" is not a valid selector
    });
</script>
</head>
<body>
html body....
</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

Dave BaldwinFixer of ProblemsCommented:
Look at the CDN links on this page: http://jquery.com/download/
Marco GasiFreelancerCommented:
In addition, I usually give a name to values:

data: {state: state},

Open in new window

Chris StanyonWebDevCommented:
Just to add to what's already been said. In your code you're binding to the submit() event of the form. There's no Submit button. You're probably better off binding to the change() event of the <select>:

$('select[name="state"]').on("change", ajaxCallback);

Open in new window

Marco GasiFreelancerCommented:
I pot here an example you can see in action here: http://www.webintenerife.com/testing_script/index.php
Selecting a value from the first select fills the second select: Maybe it is not exactly what you want but it can give you a good idea about how you can implement the feature:

index.html is the actual page where you can do your selection and get your results
<!DOCTYPE html>
<html>
	<head>
		<title>test</title>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<meta name="MSSmartTagsPreventParsing" content="TRUE" />
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
		<script type="text/javascript">
			$( document ).ready( function() {
			 $('#category').on('change', function(){  //on change event of the select for Companies
            var category_id = $('#category option:selected').val();
            $.ajax( {
                  type: 'post',
                  url: 'script.php',  
                  data: {cid: category_id},
                  dataType: 'json',
                  success: function ( resultArray )
                  {
                    $('#products').children().remove();
                    $( resultArray ).each( function ( k, v )
                    {
                      $('#products').append( "<option value='" + v['prod_code'] + "'>" + v['prod_name'] + "</option>" );
                    });
                  },
                  error: function ( jqXHR, textStatus, errorThrown  )
                  {
                        console.log(textStatus + " " + errorThrown);
                  }
            } );
      });			} );
		</script>
		<style type="text/css">
			/*<![CDATA[*/

			/*]]>*/
		</style>
	</head>

	<body>
		
		<select id='category'>
			<option valur='1'>1</option>
			<option valur='2'>2</option>
			<option valur='3'>3</option>
		</select>
		<select id='products'>
		</select>
		
	</body>
</html>

Open in new window


script.php is the script which get data from database and retunrs them to jquery function
<?php
$conn = mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());

$category_id = $_POST['cid'];
$sql = "SELECT * FROM products WHERE category='$category_id'";
$result =  mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
	$resultArray[] = $row;
}
echo json_encode($resultArray);

Open in new window

rgranlundAuthor Commented:
Thanks for these answers and info.  They have me going in the correct direction.  I will end this question and start a new one with additional information added.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
AJAX

From novice to tech pro — start learning today.