Problems with JSON on the server

1

Hello

I'm having problems with JSON when I upload it to the server ..

Example of one of my code that uses JSON :

        $("input[name=people]").keyup(function(){
            if($(this).val() != ''){
                $.ajax({
                    url: "<?php echo site_url('/StockController/searchPeople')?>",
                    type: "POST",
                    cache: false,
                    data: {name_people: $(this).val()},
                    success: function(data){
                        $('#loadPeople').html("");
                        var obj = JSON.parse(data);
                        if(obj.length>0){
                            try{
                                var items=[];   
                                $.each(obj, function(i,val){                                            
                                    items.push($("<option  id="+ val.id_people +">"+ val.name +"</option>"));
                                }); 
                                $('#loadPeople').append.apply($('#loadPeople'), items);
                            }catch(e) {     
                                alert('Ocorreu algum erro ao carregar os Fornecedores!');
                            }       
                        }else{
                            $('#loadPeople').html($('<span/>').text("Nenhum Fornecedor encontrado!"));      
                        }       
                    },
                    error: function(data){
                        alert("Ocorreu algum erro ao carregar os Fornecedores");
                    }
                });
            }else{
                $('#loadPeople').html(" ");
            }
        });

On the local server it runs smoothly, but when I upload it to an online one the code stops working, and returns the following error in the console:

  

Uncaught SyntaxError: Unexpected token in JSON at position 0

Does anyone know what might be happening?

    
asked by anonymous 08.05.2016 / 01:33

2 answers

1

Try changing from:

url: "<?php echo site_url('/StockController/searchPeople')?>",

To:

url: "<?php echo base_url('StockController/searchPeople')?>",

If the searchPeople () method does not work,

    
13.05.2016 / 19:45
1

Your server problem may be an access restriction to JSON output. In php, you can do this to release the request:

header("Access-Control-Allow-Origin: *");

Although the most appropriate and safe way to do this is by passing only domains that have valid permission to the request:

$request = $_SERVER['SERVER_NAME'];
if (in_array($request, array('siteA.com.br', 'siteB.com.br'))) {
    header("Access-Control-Allow-Origin: $request");
}
    
13.05.2016 / 20:06