0

I need to create a JavaScript variable to compare to another variable.

  • One of those variables comes from a php file. So i created a simple php array and used json_encode($array) to convert it to json.
  • Using ajax/getJSON, how do I grab that value, put it in a variable, and use it for logical testing?

I've been seeing some examples of getJSON but they are all complex arrays where mine is just a single value. Thanks

3
  • What does the JSON data look like that you are returning? Commented Jun 3, 2013 at 17:31
  • use success callback function of $.getJSON method Commented Jun 3, 2013 at 17:31
  • {"0":"abc123","CLIENT":"abc123"} Commented Jun 3, 2013 at 17:32

3 Answers 3

2
$.getJSON('yoururl.php', function(json_data){
   var compare_me = json_data.key // key is the name of the json key name
});
Sign up to request clarification or add additional context in comments.

3 Comments

thanks. I added alert(compare_me); and i got an alert box with "undefined"
@Gio did you add var compare = json_data.CLIENT; ?
Nope... I'm well versed in php/html/css/sql, etc but I'm in the beginning stages of JavaScript and jQuery. Your suggestion worked.. thanks!
0
$.post('url_of_oyu_file.php', function(responseText){
   var json_var = JSON.parse(responseText); //Convert the string into object.
   if(json_var.val = value_to_compare){
     //Do Stuff...
   }
});

Comments

0

PHP

your-file.php

<?php
 echo json_encode(array('value' => 1));
 exit;
?>

Try this

$.get('your-file.php', function(data){
 if (data.value === value_to_compare) {
   // Do stuff
 }
}, 'json');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.