-3

When some one clicks the category button an AJAX request send to category.php in this php file i am encoding a JSON response.

Jquery Onclick Function

$('#Category').change(function(){            
    var j;
  $.ajax({
   url:'categories.php',
   success: function(results){
      var obj = JSON.parse(status);
       alert(obj);
   }                
  });            
});

category.php File

<option value="" selected="">Select Sub Category</option>
<option value="Cars">Cars</option>
<option value="Motorbikes & Scooters">Motorbikes & Scooters</option>

    $status = array('type' => 'yes');
    echo json_encode($status);

Now how to assign yes to a JQuery variable on AJAX success? i tried some codes (in Above JQuery codes) but that didn't work please suggest me a solution.

user466061
  • 91
  • 11

2 Answers2

1

According to your, you are getting the response from php page in results not in status and results itself is a jquery variable. So change status to results.

$('#Category').change(function () {
    var j;
    $.ajax({
        url: 'categories.php',
        success: function (results) {
            var obj = JSON.parse(status);
            alert(obj);
        }
    });
});
urfusion
  • 5,528
  • 5
  • 50
  • 87
  • something i didn't mentioned from that category.php page not only encoded JSON response coming, there is some other – user466061 May 06 '16 at 18:01
  • 1
    @user466061: Then fix your server script to only return JSON. – Felix Kling May 06 '16 at 18:02
  • @felixKling i need both encoded JSON and those – user466061 May 06 '16 at 18:04
  • @urfusion this is the error i am getting, VM34325:4 Uncaught SyntaxError: Unexpected token < in JSON at position 46 – user466061 May 06 '16 at 18:04
  • @user466061: Then send the HTML as part of the JSON as well. Or better: Generate the ` – Felix Kling May 06 '16 at 18:06
  • @user466061 : can you paste full code of your `categories.php`? – urfusion May 06 '16 at 18:06
  • @urfusion it contains lots of codes more than 250 lines – user466061 May 06 '16 at 18:11
  • then do as @FelixKling told you. – urfusion May 06 '16 at 18:12
  • @urfusion is it possible to check if the results contains the word 'yes'? if can please give me a code – user466061 May 06 '16 at 18:14
  • @user466061 : if your `category.php` is not attached with any `post` call then you can put a check of `post` like `if($_POST) { $status = array('type' => 'yes'); echo json_encode($status);}` – urfusion May 06 '16 at 18:16
0

Fixed this problem.. thanks for the effort guys..

$('#Category').change(function () {        
    $.ajax({
        url: 'categories.php',
        success: function (results) {
            if (results.indexOf("yes") >= 0) {
              var j = 'yes';
              alert(j);
             }
        }
    });
});
user466061
  • 91
  • 11