Link to home
Start Free TrialLog in
Avatar of EICT
EICTFlag for United Kingdom of Great Britain and Northern Ireland

asked on

passing string from PHP to Javascript using JSON

Hi,
I'm having problems passing a php string variable to javascript using JSON.  
I want to check the value of the JSON response in javascript and respond accordingly.
Snippets of my code are as follows:


"close_pdp_process_check" PHP Page
$output =  "yes";

echo json_encode($output,JSON_FORCE_OBJECT);

Open in new window


receiving Page


$.ajax({
    type: "GET",
    url: "close_pdp_process_check.php",
    dataType: "json",
    success: function(response){
    
    if(response == "yes")
    {
      alert(" The answer was yes");
    }
    return false;
    }

Open in new window


Is the problem with the IF statement because response would be a JSON object? If so how to I return its value.

Thank you
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America 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
SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe 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
What is the problem - code runs correctly - see below. Agree with Ray - pointless doing a JSON request for a single string return but I suspect this is just test code and you are probably going to expand to include more complex data.
Either way the code below runs fine for me - what problems are you having?
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function() {
	$.ajax({
		type: "GET",
		url: "close_pdp_process_check.php",
		dataType: "json",
		success: function(response){
			if(response == "yes") {
				console.log(" The answer was yes");
			}
			return false;
		}                                  
	});
});
</script>
</head>
<body>
Testing
</body>
</html>

Open in new window

Avatar of EICT

ASKER

Thank you Ray for your very helpful article. JSON encoding the string on the PHP page was the problem.   Thanks also Leakim971  your suggestion about echoing an array also worked. Thanks for the specific example.
Thanks for the points.  It's a great question, ~Ray
echoing an array
Perhaps just misspoken, but that is an object, not an array in leakim's post. Arrays in Javascript use square brackets  = )
JSON syntax is in the right sidebar here:
http://json.org/