I can not succeed in making a request via ajax

0

I get in my JS the month that the user chose in the HTML select, if in case the month value was set it executes the Filtration_Database function according to the value, otherwise I define that the value will be "m" but it does not makes the request and only falls into the error condition. I hoped he would show me "okay".

Code:

ajax.js

$(function(){
  mostraMesSelect();
  var mes = pegaMesSelect();

  if(typeof mes == "undefined"){
    Filtra_data_Banco("m");
  }else{
    Filtra_data_Banco(mes);
  }
});

function Filtra_data_Banco(valor){
  $.ajax({
    type: "POST",
    url: 'ajax-FiltrosDashboard.php',
    data:{
        mesSelect:valor
    }, 
    dataType: "json",
    success:function(data){
        console.log(data);
    },
    error:function(){
        console.log("Erro indesperado "+ valor);
    }
  });
}

function pegaMesSelect(){
  var mesValue = $("#mesSelect");

  mesValue.change(function(){
    console.log(mesValue.val());

    return mesValue;
  });
}

function mostraMesSelect(){
  $("#mesSelect").change(function(){
    var mesText = $("#mesSelect option:selected").text();

    $("#mesSelecionado").html('<h2 class="text-center">'+mesText+'</h2>');
  });
}

ajax-FiltrosDashboard.php

<?php

if($_POST['mesSelect']){
  echo json_encode($_POST['mesSelect']);
}

Console Exit:

    
asked by anonymous 24.08.2017 / 19:24

1 answer

2

First we need to check which error is being generated in the request.

Is URL correct? Is the path correct?

Replace your Ajax function with:

$.ajax({
 type: "POST",
 url: 'ajax-FiltrosDashboard.php',
 data:{ "mesSelect": valor }, 
 dataType: "json",
 success:function(data){
  console.log(data);
 },
    error: function (jqXHR, exception) {
        console.log(jqXHR.status);
    },
});

As already mentioned, in the .php file change to:

<?php

if(isset($_POST['mesSelect'])){
    echo json_encode($_POST['mesSelect']);
}

Notice that your request contains: dataType: "json" .

According to the jQuery documentation:

  

Evaluates the response as JSON and returns a JavaScript object. (...)   The JSON data is parsed in a strict manner; any malformed JSON is   rejected and a parse error is thrown.

What does this mean? Your request is returning invalid JSON.

Solution : Make sure the server code (PHP) is returning a valid JSON.

    
24.08.2017 / 19:44