Marco Diaz Marco Diaz - 1 year ago 107
Ajax Question

Simple code in Ajax+Jquery+PHP doesn't work

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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download