Hello, I'm learning to work with AJAX / JSON requests, and I came across a problem (which I think has more to do with Jquery, but I have added the PHP and AJAX tags because you never know). Let's go;
When accessing the page in the browser, an AJAX request will be made to a PHP file that accesses the DB and generates a JSON. This contains the items that will compose the INPUTS RADIOS of my form.
The first INPUT of the FORM contains the CHECKED property.
Could anyone help? Thanks in advance.
Function that loads the data through the AJAX request:
//função pra carregar inputs
function carregarItens() {
var radios = "";
$.ajax({
url: "primeira.php",
cache: false,
dataType: "json",
success: function(data) {
if (data[0].erro) {
$("h1").html(data[0].erro);
} else {
for (var i = 0; i < data.length; i++) {
radios += '<input id="teste" type="radio" name="noticia"';
radios += 'value="' + data[i].id;
radios += '"/>' + data[i].produto + '</br>';
}
$('form').html(radios);
$('input:first').prop('checked', true);
}
}
});
};
Code responsible for changing content based on selected% with%:
//consulta dinamica
$(document).ready(function() {
$('form').on('change', function() {
$('input[type="radio"]').on('change', function() {**
var noticia = $(this).val();
var itens = "";
$.ajax({
url: "processa.php",
method: "POST",
cache: false,
dataType: "json",
data: {
noticia: noticia
},
success: function(data) {
if (data[0].erro) {
$("#resultado").html(data[0].erro);
} else {
for (var i = 0; i < data.length; i++) {
itens += "<div>";
itens += "<p>" + data[i].id + "</p>";
itens += "<p>" + data[i].produto + "</p>";
itens += "<p>" + data[i].valor + "</p>";
itens += "</div>";
}
$("#resultado").html(itens);
}
}
});
});
});
});
HTML file structure:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Teste Sem refresh</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><scriptsrc="javascript.js"></script>
<link href="stylesheet.css" rel="stylesheet">
</head>
<body onload="carregarItens()">
<h1>Busca sem refresh</h1>
<h2></h2>
<form></form>
</br>
<div id="resultado"></div>
</body>
</html>