Pass PHP Variable To JQuery

Hello, this is my php code that I am using, and I think the issue might be lifecycle, but I am not certain on how to remedy.

if (isset($_POST['submit'])) {
	$customer = $_POST['customer'];
	if ($customer == 'All') {
		echo "<strong>Please select a customer!</strong>";
	}else{
		
		if ($conn){
			$result = sqlsrv_query($conn, $stmt, $params);
			
			if ($result === false) {
				echo "Error in execute stored procedure";
			}
			else {
				?>

			}
			sqlsrv_free_stmt($result);
			sqlsrv_close($conn);
		}else{
			echo "can't connect";
		}
	}
}

And I want to pass that variable to this JQuery function, but the echo does not print anything on screen.

<script>
$(document).ready(function () {
	$("#download").click(function(){
		<?php echo $customer ?>;
	});
});
</script>

In theory, yes of course that works… in your implementation though… you have errors:

1.) ?>

  • breaking your if/else routine…

2.) This has NO context… is the js snippet in the same portion/stated (mode) of the form after it submitted?

This work without any problems (trimmed example)

$submit = 1;

if (isset($submit)) {
	$customer = 'somevalue';
}

?>
<script>
	$(document).ready(function () {
		$("#download").click(function(){
			<?php echo $customer ?>;
		});
	});
</script>
Sponsor our Newsletter | Privacy Policy | Terms of Service