Make a query with the return of an Ajax

1

I have a select field and need to query and load the result dynamically with Ajax . I currently have the following code (which does not seem to work or is incomplete) :

$('#formProd select').change(function(){

    $.ajax({
        type : 'POST',
        url  : 'index.php/home',
        data : {id : $('#formProd select option:selected').val()}
    });                     
});

How do I get this id for me to do my query ?

I want, by selecting an option from select , that on that same page it takes the value of select and makes an inquiry in my database to bring me the results.

See example .

When you click on a category, I want you to load a list with the products next to it.

    
asked by anonymous 17.03.2014 / 14:08

2 answers

3

Your ajax does nothing to complete, however you should do an action of which would fill your list with the elements returned in this way for example:

$.ajax({
    type : 'POST',
    url  : 'index.php/home',
    data : {id : $('#formProd select option:selected').val()}
}).done(function() {
  var len = data.id.length; //assumindo que vai retornar um Array.
  var List = []; //lista de elementos retornados
  for(var i=0; i < len; i++){ //percorre a lista de elementos retornados
    List.push("<li>"+data.id[i]+"</li>"); 
  }
  $('#linkList').html(List.join('')); //coloca as li's no ul com os elementos retornados.
});

On the Query you want to do, you can do something like this:

$id = $_POST['id'];
if (is_numeric($id))
  $sql = 'SELECT * FROM sua_tabela WHERE id='.$id;

Note that I checked first if the return of $_POST['id'] is numero, so that a SQL Injection does not happen in your application.

    
17.03.2014 / 14:41
4

If the problem is to send the option ID selected via Ajax, the code below should work without problems:

$('#formProd select').change(function(){
    $.ajax({
        type: 'POST',
        url: 'index.php/home',
        data: { id: $(this).val() },
        //contentType: 'application/json; charset=utf-8',
        //dataType: 'json',
        success: function (data) {
            // utilizar o retorno
        }
    });
});

Note that to fill in the value of the ID you want to send you do not need to access the value this way: $('#formProd select option:selected') , since you already accessed the component via the "change" event, just use $(this).val() to access the value of the selected option ID.

    
17.03.2014 / 14:58