Ajax PHP

My on-going saga of creating my first Ajax function.  I have it all almost working but am stuck at the very end, on returning the data from the Query to the Ajax.

If I run my Query out side of the ajax function it works as it should and returns what it should.  However When it is run by Ajax the return is "NULL".  Not reall sure where to go to next to finish this up...

My PHP:
<?php
    if(!isset($_POST['state'])) {
      exit;
    }

	$pdo = new PDO("mysql:host=localhost;dbname=DB", "USER", "PASS");

	$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	
	$bike_state = $_POST['state'];
	
		$pd_base_liabel = "SELECT liability_25, liability_50, liability_100, liability_300
							FROM exp_state_rates
							WHERE state = :state
							LIMIT = 1";
							
		$rate = $pdo->prepare($pd_base_liabel);

		$rate->bindParam(':state', $bike_state, PDO::PARAM_STR);
	
		try	{

			$rate->execute(array('state' => $bike_state));
			
			$bsl = $rate->fetchAll();	
	
			echo json_encode($bsl);
			
		} catch(PDOException $a) {
   			echo 'ERROR: ' . $a->getMessage();
		}

?>

Open in new window


My Ajax:
<script>
$(document).ready(function() {
var formUpdate_{row_id} = function( e ) { 
	e.preventDefault();
	
	var state_start_a = $('[name*="[location_state]"]').val();
	var state_start_b = $('[name*="[0][location_state]"]').val();
	if(state_start_a != '') {
		state = state_start_a;
	} else {
		state = state_start_b;
	}
	
	alert("STATE:: " + state);
		
		$.ajax({
      	url: "ajax/view_cart_ajax.php",
       	type: "POST",
       	data: state,
       	dataType: 'json',
       	success: function ( data )
       	{
      		console.log(data);
      		alert(data);

   		},
                  error: function ( jqXHR, textStatus, errorThrown  )
                  {
                        alert(textStatus + " " + errorThrown);
                  }
         
    });

Open in new window


http://23.101.151.179/index.php?/store/29
fill out the form. Click submit.
at the bottom of the page click submit.
Next page, change liability and click update.  I have a var_dump at the top of the page that is running the same query as the query in my ajax php file.
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.

Chris StanyonWebDevCommented:
You need to pass the data from your ajax script as key pairs

data: { state : state}

You should also remove the array from the execute method of your pdo statement
rgranlundAuthor Commented:
I made those adjustments and I get an error:
parsererror SyntaxError: Unexpected token F

I'm looking it up.

In addition to that, I'm not 100% sure how to see the return and turn it into a VAR
Chris StanyonWebDevCommented:
In isolation, that error doesn't mean anything - is it a javascript error or a php error?

When you want to get your data from PHP to Javascript, you JSON encode it. In your PHP script, you're running a query which returns a single record. This record is returned as an object, with the field names of the table as properties of the object. You then json_encode this object and echo it out for your javascript to read - this gets passed back as the argument of your success handler - the data variable in your code.

Because the data being passed back to your AJAX is a JSON string, you can access the properties of this to get at the data - the columns names from your query are translated into the properties of the JSON object:

var selectedState = "some value";

$.ajax({
	url: "ajax/view_cart_ajax.php",
	type: "POST",
	data: { state: selectedState },
	dataType: 'json',
	success: function ( data )
	{
		alert( data.liability_25 );
		alert( data.liability_50 );
	},
	error: function ( jqXHR, textStatus, errorThrown  )
	{
		alert(textStatus + " " + errorThrown);
	}
});

Open in new window


It really will make your life a LOT easier if you start of with something VERY simple. A basic HTML page containing 1 element, and a simple PHP script that echoes out that POST array. You can then build up from there. Your approach seems to have too many moving parts for you to be able to focus clearly.

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
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

rgranlundAuthor Commented:
Apparently my server will not take PDO Queries.  So I changed the Query to regular mysql.  I tested the page and it quries fine.
The error I get now is:  SyntaxError: Unexpected token <

Any insight will be helpful.

I have also made it into a simple page, as you suggested:
http://23.101.151.179/index.php?/ajax/
Chris StanyonWebDevCommented:
Right - your ajax request is working fine - but it looks like the response is wrong - you seem to be outputting an entire HTML page - you only need to output the JSON data.

Post your view_cart_ajax.php
rgranlundAuthor Commented:
{embed="includes/header"}
<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

	if(!isset($_POST['state'])) {
		$bike_state = "";
	} else {
 		$bike_state = $_POST['state'];
	}

	
	$pd_base_liabel = ee()->db->select('liability_25, liability_50, liability_100, liability_300')
		->from('exp_state_rates')
		->where('state', $bike_state)
		->limit('1')
		->get();
			
		$bsl = $pd_base_liabel->result_array();
		
		
		echo json_encode($bsl);		

?>	
{embed="includes/footer"}

Open in new window


if I run the query from the page and set the $bike_state to CA this is what the page outputs:
[{"liability_25":"54.00","liability_50":"78.00","liability_100":"95.00","liability_300":"135.00"}]

Open in new window

Chris StanyonWebDevCommented:
We seem to be going round in circles here - in your original code, you had PDO queries, which you said were working fine. Now you've gone back to the ee() methods because you say your server won't accept PDO queries. Which is it?

In the code you've just posted, you have a header and footer embedded - if either of those files contain any HTML at all, then your script won't work. The ONLY output you want from your PHP script is a valid JSON string. Absolutely anything else will not work! It is vitally important that you understand this.

I think you really need to take a step back from this and start to get a solid understanding of the very basics of what you are trying to do. You are making this much more complicated than it needs to be by having a lot of moving parts that are completely irrelevant to what you need.

Forget about the AJAX request until you know your PHP script is working.
rgranlundAuthor Commented:
Sorry, I have been changing it as I go.  The code that I posted was a version back and incorrect.  My apologizes for wasting your time on that.

The script seems to be working now however, all of my 4 success alerts all come back "undefined" So I added data[0].liability_25 and it worked!
 [0] to indicate the array.
Chris StanyonWebDevCommented:
Right - we're slowly getting somewhere.

It looks like you're still retrieving a single record from your database and wrapping it in an array.

In your jQuery, you'll need to access the first element on the array (zero based):

alert( data[0].liability_25 );

Open in new window

rgranlundAuthor Commented:
@Chris.  I have it working now!  Thanks for taking the time and having patience.  This is pretty cool. I can see it now.

I don't know which answer to give you the points on!
Chris StanyonWebDevCommented:
Excellent - knew we'd get there in the end.

In the future when you're trying to learn these things, it really does make it easier to get rid of absolutely everything that can get in the way - focus on the very simple moving parts and once you know that's working, you can build up the features.

It's up to you to accept whichever answer(s) you felt helped you out the most.
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.