• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 113
  • Last Modified:

Ajax PHP return variable

I just asked this question but wanted to start over with clean code so it will be more clear what I am doing and where I am at:

I am querying the DB via ajax.  I need to return the variable to be used in a javascript function.

The Ajax:
<script>
$(document).ready(function () {	
alert("HELLO");

	var state = $('select[name*="[0][product_liability]"]').find(':selected').val();
	
	alert("STATE:: " + state);
		
		$.ajax({
      	url: "view_cart_ajax.php",
       	type: "POST",
       	data: {state: state},
       	dataType: 'json',
       	success: function ( bsl )
                  {
                    $( bsl ).each( function ( liability_option_value )
                    {
                      if(liability_option_value == 'liability_25') {
        		 		liability_rate = 'liability_25';
        		 		}	else if (liability_option_value == 'liability_50' )   {
        		 		liability_rate = 'iability_50';
        		 		}	else if (liability_option_value == 'liability_100' )   {
        		 		liability_rate = 'liability_100';
        		 		}	else if (liability_option_value == 'liability_300')   {
        		 		liability_rate = 'liability_300';
        		 		}	else if (liability_option_value == undefined)   {
        		 		liability_rate = 0;
        		 		}	else {
 							liability_rate = 0;
 						}
                    });
                    alert("AJAX RETURN:: " + liability_rate);	
                  },
                  error: function ( jqXHR, textStatus, errorThrown  )
                  {
                        console.log(textStatus + " " + errorThrown);
                  }
    	});
</script>

Open in new window


It makes it through the first two alerts and the correct info is being passed.  However, I think there is something wrong with the way I am creating the return, or how I am formatting the return in my jQuery.

The PHP:
<?php
	$bike_state = $_POST['state'];
	$pd_base_liabel = ee()->db->select('*')
		->from('exp_state_rates')
		->where('state', $bike_state)
		->limit('1')
		->get();
			
		$bsl = $pd_base_liabel->result_array();
		$pd_base_liabel->free_result();	

		echo json_encode($bsl);

Open in new window

0
rgranlund
Asked:
rgranlund
  • 8
  • 5
  • 2
3 Solutions
 
Ray PaseurCommented:
You can use console.log( bsl) to see what is coming back, if that's what you're looking to understand.  Works well with Google Dev Tools.
https://developer.chrome.com/devtools
0
 
Chris StanyonCommented:
Is there a question in there somewhere? Not really sure what you're asking. If you think there's something wrong, please tell us.

Without knowing what 'bsl' is we can't tell whether that's the correct way to handle it. If it really is loopable, then you seem to loop through it, overwriting a variable each time so when you finally alert out the value, you'll only alert the last one.

I'm guessing this is just a working sample rather than a real world application - as it stands, it doesn't really make sense. You're calling your AJAX as soon as you load the page. All those if statements are redundant. You're just checking a variable and then setting another one to the same value.

Probably easier if you tell us what you're trying to do - we may be able advise a better solution
0
 
rgranlundAuthor Commented:
I'm really new at this and am trying to get my head around how to do it and how to ask the questions.
I am trying to use Ajax to make a query and return a value to javascript.

The form:
<html>
ect name="item_options[0][product_liability]" data-dpmaxz-eid="3">
<option value="">Select a Value</option>
<option value="liability_25"> $25,000 </option>
<option value="liability_50"> $50,000 </option>
<option value="liability_100"> $100,000 </option>
<option value="liability_300"> $300,000 </option>
</selec
</html>

Open in new window

When a selection is made and the submit buttun is clicked it will grab the select value fire the Ajax
<script>
$(document).ready(function () {	

	var state = $('select[name*="[0][product_liability]"]').find(':selected').val();
	
	alert("STATE:: " + state);
		
		$.ajax({
      	url: "view_cart_ajax.php",
       	type: "POST",
       	data: {state: state},
       	dataType: 'json',
</script>

Open in new window

Pass the variable to the PHP:
<?php
	$bike_state = $_POST['state'];
	$pd_base_liabel = ee()->db->select('*')
		->from('exp_state_rates')
		->where('state', $bike_state)
		->limit('1')
		->get();
			
	$bsl = $pd_base_liabel->result_array();
		
		$pd_base_liabel->free_result();	
	
		  foreach($bsl as $row) {
			$liability_25 = $row['liability_25'];
			$liability_50 = $row['liability_50'];
			$liability_100 = $row['liability_100'];
			$liability_300 = $row['liability_300'];
}
?>

Open in new window

These for returns I need to sent to the "Success" in the Ajax.
The Ajax Success:
<script>
	success: function ()
                  {

                      if( state == 'liability_25') {
        		 		liability_rate = <?php echo $liability_25; ?>;
        		 		}	else if ( state == 'liability_50' )   {
        		 		liability_rate = '<?php $liability_50; ?>';
        		 		}	else if ( state  == 'liability_100' )   {
        		 		liability_rate = '<?php $liability_100; ?>';
        		 		}	else if (state == 'liability_300')   {
        		 		liability_rate = '<?php $liability_300; ?>';
        		 		}	else if ( state == undefined)   {
        		 		liability_rate = 0;
        		 		}	else {
 							liability_rate = 0;
 						}
                    },
                    alert("AJAX RETURN:: " + liability_rate);	
                  error: function ( jqXHR, textStatus, errorThrown  )
                  {
                        console.log(textStatus + " " + errorThrown);
                  }
</script>

Open in new window


This is the complete jQuery / Ajax code that I have.

<script>
$(document).ready(function () {	

	var state = $('select[name*="[0][product_liability]"]').find(':selected').val();
	
	alert("STATE:: " + state);
		
		$.ajax({
      	url: "view_cart_ajax.php",
       	type: "POST",
       	data: {state: state},
       	dataType: 'json',
		success: function ()
                  {

                      if( state == 'liability_25') {
        		 		liability_rate = <?php echo $liability_25; ?>;
        		 		}	else if ( state == 'liability_50' )   {
        		 		liability_rate = '<?php $liability_50; ?>';
        		 		}	else if ( state  == 'liability_100' )   {
        		 		liability_rate = '<?php $liability_100; ?>';
        		 		}	else if (state == 'liability_300')   {
        		 		liability_rate = '<?php $liability_300; ?>';
        		 		}	else if ( state == undefined)   {
        		 		liability_rate = 0;
        		 		}	else {
 							liability_rate = 0;
 						}
                    },
                    alert("AJAX RETURN:: " + liability_rate);	
                  error: function ( jqXHR, textStatus, errorThrown  )
                  {
                        console.log(textStatus + " " + errorThrown);
                  }
</script>

Open in new window


So, what I am having trouble with is getting the "ForEach" in the PHP back to the jQuery via Ajax.
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Chris StanyonCommented:
Hey rgranlund,

In your PHP script you are limiting the database results to a single record, so there's nothing to loop through - either in PHP or in the AJAX success function. Your PHP will need to encode the database record so that it can be passed back to your AJAX Call. Something like this:

<?php
$bike_state = $_POST['state'];
$pd_base_liabel = ee()->db->select('*')
   ->from('exp_state_rates')
   ->where('state', $bike_state)
   ->limit('1')
   ->get();
			
$bsl = $pd_base_liabel->result_array();
// now encode the record and output it
echo json_encode($bsl);

Open in new window


Now when you receive the JSON back, you will have a property for each database field:

$.ajax({
   url: "view_cart_ajax.php",
   type: "POST",
   data: {state: state},
   dataType: 'json',
   success: function ( data )
   {
      console.log(data);
      alert(data.someFieldName);
   }
});

Open in new window

0
 
rgranlundAuthor Commented:
@Chris, I made those adjustments and when I run it, the console.log(data) - alert, does nothing.
I changed the url in the ajax and it did not throw an error.

I added what I think is an error checker but I'm not sure.
		$.ajax({
      	url: "view_cart_ajax.php",
       	type: "POST",
       	data: {state: state},
       	dataType: 'json',
       	success: function ( data )
       	{
      		console.log(data);
      		alert(data.liability_25);
   		},
                  error: function ( jqXHR, textStatus, errorThrown  )
                  {
                        console.log(textStatus + " " + errorThrown);
                  }
    });

Open in new window


Could there be a n issue with the way I am calling the php file? Is there a way to test to see if I am connecting via ajax?

$.ajax({
      	url: "view_cart_ajax.php",
       	type: "POST",
       	data: {state: state},
       	dataType: 'json',
       	success: function ( data )
       	{
      		console.log(data);
      		alert(data.liability_25);
   		}

Open in new window

0
 
Chris StanyonCommented:
You should be able to see the request happening by using the webdev tools in either chrome or Firefox (firebug). You'll actually see the request happen and see the response comeback.

Your code looks OK, but we're only ever seeing snippets of it, so there's possibly something else going on. Do you have a link to a page where we can see this in action - we'll be able to help you out so much easier if we can see exactly what's going on.
0
 
rgranlundAuthor Commented:
go here: http://23.101.151.179/index.php?/store/29
fill out the form.  submit go to the bottom and submit.  On next page, change Liability and click update, that is when the ajax should do it's thing?
0
 
rgranlundAuthor Commented:
@chris, the console has helped me get a lot closer.  I'll let you know what I further discover.
0
 
Chris StanyonCommented:
Right - couple of things here. Firstly, your PHP script is not working. It's throwing an error. It does output the error to the console (simply says 'error', but then your page refreshes, so you lose it. Change the console.log in your error handler to an alert:

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

Open in new window


Secondly, if you want to submit your form by ajax, then you have to prevent the submit button from doing it's normal thing. Define you function with an argument, and then call the preventDefault() method on it:

var formUpdate_0 = function (e)
{
   e.preventDefault();
   ... 

Open in new window


I would build a very simply page, containing a tiny form with one input, and then submit that normally to your PHP script. It will allow you to isolate the PHP script and make sure that's working perfectly before complicating the issue with a huge form and an AJAX request.
0
 
rgranlundAuthor Commented:
I'm getting a 500 internal server error.
I needed to change my PHP because it was outside of the CMS framework.  is the following updated Query ok?
	$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 *
							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

0
 
Chris StanyonCommented:
Sort of getting there. Nice to see you using PDO :)

Because you're binding the named parameters, you don't need to pass them into the execute method. Also, once you've executed the query, you only need to call fetch(), not fetchAll() - you've already limited your query to 1 record, so you're never going to get more than one that back. Finally, it's considered best-practice to explicitly select the columns you want, rather than the lazy fetching of *. I know this can be a pain if you have a lot of fields, but it will make your code more robust, readable and future-proof.

$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 column1, column2, column3
	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();
	$bsl = $rate->fetch();	
	echo json_encode($bsl);
}
catch(PDOException $a)
{
	echo 'ERROR: ' . $a->getMessage();
}

Open in new window

0
 
rgranlundAuthor Commented:
I'm getting a NULL response from my query.  That's no t correct.
0
 
Ray PaseurCommented:
Just a note for going forward... I find these things much easier to debug if I do the following:

1. Make the server-side script a GET request
2. Test the server-side script from the browser address bar
3. Completely debug the server-side script before I do any work on the front end.

This is valuable because once I obscure the server activities with an AJAX request, it's nice to know that the server side of things just works without any confusion.

There are plenty of AJAX requests that are inappropriate for GET (data base updates come to mind) but that does not mean that you must start the debugging process with POST; you can use GET and URL parameters until you're ready to release the script "into the wild."  The added visibility into the parameters and return values will save you a lot of time!
0
 
rgranlundAuthor Commented:
I had the query wrong.  Stupid mistake.
0
 
rgranlundAuthor Commented:
I had my query wrong.  Man.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 8
  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now