Pass variable from AJAX to php

3

I do not have much experience in Ajax, I needed some help. It's the following, I have a form that validates the information with ajax. Now I wanted to insert this data into the database, how can I insert the username variable into the database, for example?

form button

<input onclick="checkForm()" type='button' class="btn btn-info btn-block" value='Inserir' name="submit1">

script.js

function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var password = document.getElementById("password1").value;
var email = document.getElementById("email1").value;
var website = document.getElementById("descricao1").value;
//Check input Fields Should not be blanks.
if (name == '' || password == '' || email == '' || website == '') {
alert("Por favor, preencha todos os campos");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var password1 = document.getElementById("password");
var email1 = document.getElementById("email");
var descricao1 = document.getElementById("website");
//Check All Values/Informations Filled by User are Valid Or Not.If All   Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Mais de 4 letras' || password1.innerHTML ==   'Password é pequena de mais' || email1.innerHTML == 'Email inválido' ||   descricao1.innerHTML == 'Descricao inválida') {
alert("Preencha com informação válida.");
} else {
//Submit Form When All values are valid.
//document.getElementById("myForm").submit();
sendData('regista.php', 'POST','username='+username1);
}
}
}



function sendData(url, metodo, dados){
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
  alert("Enviado!");
  location.href = location.href;
 }
};
 xhttp.open(metodo, url, true);
 xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xhttp.send(dados);
}



// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validando..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;

} else {
document.getElementById(field).innerHTML = "Error Occurred. <a     href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
    
asked by anonymous 12.04.2016 / 19:45

2 answers

1

Send the data using an object of type XMLHttpRequest. I made an example just passing the username. You can get this data in php using $_POST['username'];

Follow the example in javascript:

function checkForm() {
  var username1 = document.getElementById("username");
  var password1 = document.getElementById("password");
  var email1 = document.getElementById("email");
  var descricao1 = document.getElementById("website");
  if (username1.innerHTML == 'Mais de 4 letras' || password1.innerHTML == 'Password é pequena de mais' || email1.innerHTML == 'Email inválido' ||  descricao1.innerHTML == 'Descricao inválida') {

  alert("Preencha com informação válida.");

  } else {

  //configure aqui seu endereco, o metodo em que quer passar os dados(GET OU POST)
  //e os dados que quer enviar
    sendData('seuendereco/seuscript.php', 'POST','username='+username1);
    //document.getElementById("myForm").submit();

  }
}
function sendData(url, metodo, dados){
 xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      alert("Enviado!");
      location.href = location.href;
    }
 };
 xhttp.open(metodo, url, true);
 xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xhttp.send(dados);
}
    
12.04.2016 / 20:22
2

Use this in JS, it will send the parameters to your PHP code where you can send it to the database.

$.ajax({
    method: "GET",
    url: "seucodigobanco.php",
    data: { 
        usr: username1,
        pws: password1,
        ... //Resto dos parâmetros
    }
})
.done(function(msg) {
    alert(msg);
});

How to get the parameters in seucodigobanco.php would be

if (isset($_GET['usr'])){
    $user = $_GET['usr'];
}
if (isset($_GET['pwd'])){
    $pass = $_GET['pwd'];
}
... //Resto dos parâmetros

//Resto do código de persistência no banco de dados em PHP

And then the rest of the database code in PHP.

Any echo you give in seucodigobanco.php will drop as a string in the variable msg of .done()

Do not forget to add JQuery to your project.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.2.js"></script>
    
12.04.2016 / 20:09