0

I am trying send an array from php to js via ajax but don't it run, no matter what I do. I'm sure it must be simple but I've tried everything.

<!doctype html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Test</title>
  <link type="text/css" rel="stylesheet" href="styles.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="scriptJS.js"></script>
</head>
<body>
<div>
  <div class="tweets-container">
    <p>Loading</p>
  </div>
</div>
</body>
</html>
$(document).ready(function() {
  var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
    '<h1>Welcome!</h1>' +
    '<div class="seeTweets"><select>';
  var count = 0;

  $.get({
      url: 'scriptPHP.php',
      type: 'GET',
      data: {
        usUsers: 'usuarios'
      },
      success: function(response) {
        contPrincipalLastTwitter += '<option value =' + response + '>' + response + '</option>';
        count++;
      },
      error: function(e) {
        console.log(e.responseType);
      );
    }
  });

  console.log(count); contPrincipalLastTwitter += '</select></div></div>'; $(document.body).append(contPrincipalLastTwitter);
});
<?php
  $test = array('uno'=>'uno', 'dos' => 'dos');
  echo json_encode($test);
?>

I reduced it as much as I could, originally this one was sent to a class and this one, having several requests acted according to who have called it.

Aditi Parikh
  • 1,522
  • 3
  • 13
  • 34
Marco Diaz
  • 13
  • 4
  • Does your code get to the `success` part? Also, where is `objt` initialised, if at all? – Nir Tzezana Oct 02 '17 at 15:03
  • I thought It was the succes part. Isn't it? – Marco Diaz Oct 02 '17 at 15:05
  • 2
    You have several syntax issues. Firstly your HTML is missing a `` element. In the JS, `succes` needs to be `success` and you've got mis-matched braces after `error`. Finally, you've not defined `objt` anywhere, and appending the `response` object will just result in `[object Object]` being injected in to the HTML. You need to access the properties of the object. Voting to close as a typo. I'd strongly suggest you use a IDE with syntax highlighting/auto code formattng as it makes it almost impossible to miss errors like this. – Rory McCrossan Oct 02 '17 at 15:06
  • Given what Rory pointed out, you should also have noticed at least one syntax error in your browser's console, when you tried to run it? Even if your code editor didn't point it out, the browser will have done. Looking in the console is the first basic step you should take to debug JS problems. – ADyson Oct 02 '17 at 15:15
  • Add your recommendations but it still doesn't work. I try it on local, will that be it?. Also, the console doesn't tell me anything. I use phpStorm and google chrome – Marco Diaz Oct 02 '17 at 15:16
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Oct 02 '17 at 15:22
  • Hi Marco. Could you please check the content of response in the success method. And share it with us – Mario Oct 02 '17 at 15:23
  • gives me: {"uno":"uno","dos":"dos"} (The content of the php array). Maybe if i use JSON.parse? – Marco Diaz Oct 02 '17 at 15:34
  • now we discard that it is a problem in the connection, and to focus that it is a problem when trying to draw the content of the select – Mario Oct 02 '17 at 15:41
  • Possible Duplicate? https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Kevin B Oct 02 '17 at 15:42
  • Thank you all for your help. I think I'll start by changing IDE and then studying more Ajax – Marco Diaz Oct 02 '17 at 15:45

2 Answers2

0

the problem is that you try to concatenate the same string in two different time and place (first inside the document ready, secondly in the success of the ajax call)

js code:

$(document).ready(function() {
  var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
    '<h1>Welcome!</h1>' +
    '<div class="seeTweets"><select id="test-select"></select></div></div>'; 
$(document.body).append(contPrincipalLastTwitter);
  $.get({
      url: 'scriptPHP.php',
      type: 'GET',
      data: {
        usUsers: 'usuarios'
      },
      success: function(response) {console.log(response);
        console.log(response);
        for(var idx in response){
          $('#test-select').append('<option value =' + idx + '>' + response[idx] + '</option>');
        }
      },
      error: function(e) {
        console.log(e.responseType);
     }});  
});

scriptPHP.php

<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
// add header
header('Content-Type: application/json');
echo json_encode($test);
Roberto Bisello
  • 1,235
  • 10
  • 18
0

A slightly simpler option

const target = document.querySelector('#target');

$.ajax({
    url: 'script.php',
    dataType: 'JSON',
    success: response => {
        for (let key in response) {
            const option = `<option value="${key}">${response[key]}</option>`;

            target.innerHTML += option;
        }
    },
    error: error => {
        // todo
    }
});
Mario
  • 4,784
  • 3
  • 34
  • 50