Why is the Json_encode() PHP function not returning data in Json format?

Asked

Viewed 584 times

-1

Good Morning. After 2 full days researching I post my question: Why does the command

echo json_encode($a);

is returning an HTML page ? It is a registration where I have 1 foreign key, but the user will not enter the foreign key ( logical ) but 3 data that will be searched in Mysql to know if the CLASS exists or not. With this, I have to use Javascript.

I am using CODEIGNITER. So on the footer I have the code:

 <script type="text/javascript">
 $(document).ready(function(){
      $("#btgravar").click(function(){

        var nturma = $("#nturma").val();
        var cletivo = $("#cletivo").val();
        var csemestre = $("#csemestre").val();
        alert(nturma);
        $.ajax({
           url: 'Planodeaula/ajaxrequestpost',
           type: 'POST',
           data: {nturma: nturma, cletivo: cletivo, csemestre:csemestre},
           contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
           accepts: {json: "json"},
           //dataType: 'json',
           success: function(a) {
               //console.log(retorno);
               alert(a);
                //var resposta = jQuery.parseJSON(retorno);
                var resposta = JSON.parse(a);
                alert(resposta);
                if(resposta === 'true')
                {
                    alert("tudo funcionando 100%.");
                }else{
                    alert("NÃO funcionando !!!!!!!!!!!");
                }
           },
           error:function( jqXHR , textStatus, errorThrown )
            {
              alert("Erro: "+textStatus);
              //alert(jqXHR);
              alert("Detalhes do erro: "+errorThrown);
           }
        });
    });
});


</script>

If I put the command in the javascript dataType: 'json'; returns that "famous" error "Syntaxerror: Unexpected token < in JSON at position 0"" when removing it returns the whole page in HTML. In Controller ( I invented, after 1,000,000 attempts, a false array to turn into Json ).The right is to go to MODEL this->dia->check_turma(), check if it exists in the database and return to the Controller:

public function ajaxrequestpost() 
{    
    $this->load->library('form_validation');
    $this->form_validation->set_rules('nturma','trim|required');
    $this->form_validation->set_rules('cletivo','trim|required');
    $this->form_validation->set_rules('csemestre','trim|required');
    header('Access-Control-Allow-Origin: *');
    if ($this->form_validation->run() === FALSE) {
        header('Content-type: application/json');
        $a = array("tipo"=>$tipo, "rua"=>$rua, "bairro"=>$bairro, "cidade"=>$cidade, "cep"=>$cep, "uf"=>$uf);
        $a = utf8_encode($a);
        echo json_encode($a);
        exit;
        //return $a;
    }
    else{
        //show_error('Dados válidos!');
        //$retorno=$this->dia->check_turma();
        header('Content-type: application/json');
       $a = array("tipo"=>$tipo, "rua"=>$rua, "bairro"=>$bairro, "cidade"=>$cidade, "cep"=>$cep, "uf"=>$uf);
       $a = utf8_encode($a);
       echo json_encode($a);
       exit;


    }
}

I already tested the Javascript code:

dataType: 'json'

accepts: {json: "json"},

And in PHP : header('Content-type: application/json');

Content-type: application/json; charset=utf-8

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

$date = utf8_encode($date);

Exit;

I researched : Request ajax is not working

https://stackoverflow.com/questions/9254891/what-does-content-type-application-json-charset-utf-8-really-mean

https://stackoverflow.com/questions/37280274/syntaxerror-unexpected-token-in-json-at-position-0

Request ajax is not working

https://stackoverflow.com/questions/21572721/ajax-call-returning-data-but-failing

Array is not converted to JSON

Why can’t I get the data from the ajax request? (json)

https://makitweb.com/send-ajax-request-codeigniter/

https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script

https://www.itsolutionstuff.com/post/jquery-ajax-request-example-in-codeigniterexample.html

/posts/154095/revisions

  • If requested page ajaxrequestpost has HTML tags will return tb along with echo’s JSON, and this will result in error. The only thing that should return from the page is what echo prints.

  • Thanks I will test. This ajaxrequestpost method is inside a Controller. And in the index of the Controller I have the call to 3 views. Header, side menu_and Footer. Then, I have to take this method out of this Controller and create another Controller to include it. Correct ?

  • The requested file cannot be a normal page (with tags and everything). If you need to create a file . php only with PHP code and echo.

  • The function json_encode() not the problem, the problem is the data you are passing for it encode, you should not user utf8_encode() in an array? The parameter for utf8_encode must be string.

  • Honestly, I , after 2 days , I put this function utf8_encode(), reading some tips. But the problem is that it returns HTML ( as Sam , I can’t have tags in the file where echo json_encode is). So, I created a . php neat and I’ll insert the Function ( method ) to see the result. Note that the array is "fake", already in the despair of forcing a return a json and not an HTML. I will also follow your hint and remove it.

2 answers

0

You are passing an array to the utf8_encode($data), that’s a mistake: expects parameter 1 to be string, it will not return the converted array, and in this case also will not arrive in the json_encode($data).

If you need to convert to utf8_encode your array, use an auxiliary function, example: $data = array_map('utf8_encode',$data);

The function utf8_encode() only takes string as parameter, more information here.

In the case of Codeigniter you need to use the framework rules, example:

return $this->output->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode($data)); 
  • Yes Ivan, I will remove it. I have created a new php file. In the browser calling this file, I have the response ( that array I created just to check the return {"type":"APARTMENT","street":"BAR u00c3O DE MIRACEMA","neighborhood":"CENTER","city":"CAMPOS DOS GOYTACAZES"}). But there is something wrong because within the site ( with structure MVC - CODEIGNITER) is still returning html.

  • Edit your question with the new modifications you made so we understand what the problem is.

  • Sometimes the problem is that you are trying to send this to a view, which is not the case.

  • Good Morning @Ivan Ferrer. I answered yesterday how I solved the problem. The answer is just below.I just can’t dial "SOLVED"

0


1- I created a PHP as you quoted @Sam.
2-Remove utf8_encode() function@Ivan Ferrer from PHP code.
3- I inserted the stringfy var response function = JSON.parse(JSON.stringify(date)).
4- I formatted the date parameter correctly :

data: {'nturma': nturma ,'csemestre':csemestre ,'cletivo':cletivo}

5- I think it’s irrelevant that I switched the object and the event that fires javascript to :

$("#csemestre"). change(Function()

Javascript:

<script type="text/javascript">
 $(document).ready(function(){
      $("#csemestre").change(function(){
        var base_url = '<?php echo base_url()?>';   
        var nturma = $("#nturma").val();
        var cletivo = $("#cletivo").val();
        var csemestre = $("#csemestre").val();
        console.log(nturma);
        console.log(csemestre);
        console.log(cletivo);
        $.ajax({
           url: base_url+'Requisicoes/ajaxrequestpost',
           type: 'POST',
           contentType: "application/x-www-form-urlencoded",
           accepts: {json: "json"},
           dataType: 'json',
           data: {'nturma': nturma  ,'csemestre':csemestre ,'cletivo':cletivo},
           success: function(data) {
               console.log(data);
                //var resposta = jQuery.parseJSON(data);
                var resposta = JSON.parse(JSON.stringify(data));
                console.log(resposta);
                if(resposta === 'true')
                {
                    alert("tudo funcionando 100%.");
                }else{
                    alert("NÃO funcionando !!!!!!!!!!!");
                }
           },
           error:function( jqXHR , textStatus, errorThrown )
            {
              alert("Erro: "+textStatus);
              console.log(arguments);
              //alert(jqXHR);
              alert("Detalhes do erro: "+errorThrown);
           }
        });
    });
});


</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.