Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

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.
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

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
Avatar of Robert Granlund

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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/
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
{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

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.
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.
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

@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!
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.