success:function (data) { console.log(data); 

gives ["name", "price"] ok

 console.log(data[0]); 

gives nothing

  • string because you have an input, not an array - teran
  • How to change to an array? - Dima Rashevskiy

1 answer 1

Probably. the only time this can happen is that data is not an object / array, but a regular string. Apparently the server does not set the content-type headers in applcation/json , and jquery does not know about the data type (based on these headers, a conversion occurs). So, either do it forcibly

 success: function(data){ data = JSON.parse(data); console.log(data[0]); } 

either use $.getJSON instead of $.get or $.ajax with type: "GET" . For POST requests, obviously, only the first option, or configure server headers

PS: judging by your previous question, on the server side you should do so

 $data = array('name' => $name, 'price' => $price); $data = json_encode($data); header("Content-Type: application/json"); print ($data); 
  • data = JSON.parse (data); gives an error. I added all the Ajax code, you can see it - Dima Rashevskiy
  • @DimaRashevskiy what mistake? - teran
  • perhaps pkhp displays something else besides the "array". try to add die() after print - teran
  • VM15774: 3 Uncaught SyntaxError: Unexpected token <in JSON at position 4 - Dima Rashevskiy
  • at JSON.parse (<anonymous>) - Dima Rashevskiy