3

I would like to know if it is possible to return the ajax call into a javascript array, rather than a DOM object. The ajax call is returning something like n-tuples of value1-value2, and I would like to iterate over that.

Thanks.

$(function () {
    $("#categoria").change(function() {
        var id = $(this).val();
        alert(id);
        vars = load("getcategoria.php", "q="+id); // can I do something like this? how?
    });
});

3 Answers 3

2

Yes you can do this, but .load() is the wrong method for the job. .load() is used to load HTML into a specific DOM element.

I suggest you have your getcategoria.php return a JSON object (use PHP's json_encode), and then use $.getJSON() to get it, parse it, and use it how you wish.

$.getJSON("getcategoria.php", "q="+id, function(data){
  // data is your JSON object, use it how you wish
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the jQuery getJSON() method to return a JSON String which you can then iterate over.

This example from the linked page shows how on retrieving a JSON string you then iterate over it and generate a list. YOu can modify this to perform your own iteration and behaviour.

  $.getJSON('ajax/test.json', function(data) {
  var items = [];

 $.each(data, function(key, val) {
   items.push('<li id="' + key + '">' + val + '</li>');
 });

  $('<ul/>', {
   'class': 'my-new-list',
   html: items.join('')
  }).appendTo('body');
});

Comments

0

And dont forget to have set header('content-type: application/json') in your getcategoria.php file

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.