简体   繁体   中英

json_decode returning NULL with valid json

so...here's the issue:

I got this on my javascript file:

this.fields = {
  'zone': ['DouroMinho','TrasosMontes', 'BeiraLitoral', 'BeiraInterior'],
  'flower': ['Milho Grao', 'Milho', 'Prado', 'Batata', 'Couve', 'Tomateiro', 'Pessegueiro', 'Pomoideas', 'Vinha'],
  'Months': ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
}

var sendDataToText = $.ajax({
    url: "http://localhost:4000/process-data.php",
    type: "POST",
    data: { 'input-data': JSON.stringify(this.fields) },
    cache: false,
    dataType: json,
    success: function(data){
      console.log('call to process-data successful');
      return;
    },
    error: function() { console.log("process-data falhou"); return; }
  });

and on my php i got this:

if(get_magic_quotes_gpc()){
$d = stripslashes($_POST['input-data']);
}else{
$d = $_POST['input-data'];
}
$d = json_decode($d,true);

echo var_dump($d);

I have MAMP running my server and gulp running the wep app on port 3000. When i go to localhost:4000 to test my process-data.php it only shows NULL.

What's wrong? the json_decode error returns 0, which means the json_decode is not the problem. The json is also valid and turned into string before the ajax call. Help please, lol. Thank you

use a variable to save the context (scope) when the data from the success comes in:

var something;

$.ajax({
    ...,
    success: function(data){
        console.log('call to process-data successful');
        something = data;
    },
...
console.log(something);

I think the problem is that you are losing the fields json to improper usage of scope.

In the OP code you are assigning fields to this which is most likely the window object. When you are accessing it in the $.ajax object you are still using this which no longer has window scope, but rather the scope of the ajax object.

Try this:

window.fields = {
  'zone': ['DouroMinho','TrasosMontes', 'BeiraLitoral', 'BeiraInterior'],
  'flower': ['Milho Grao', 'Milho', 'Prado', 'Batata', 'Couve', 'Tomateiro', 'Pessegueiro', 'Pomoideas', 'Vinha'],
  'Months': ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
}

var sendDataToText = $.ajax({
    url: "http://localhost:4000/process-data.php",
    type: "POST",
    data: { 'input-data': JSON.stringify(window.fields) },
    cache: false,
    dataType: 'json',
    success: function(data){
      console.log('call to process-data successful');
      return;
    },
    error: function() { 
      console.log("process-data falhou"); 
      return; 
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM