Pass AJAX variable to php

Asked

Viewed 1,549 times

3

I don’t have much experience in Ajax, I needed help. Here’s the thing, I have a form that validates the information with ajax. Now I wanted to enter this data in the database, as I can insert the username variable in 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();
}

2 answers

2

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

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

Way to get the parameters on 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.

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

Don’t forget to add Jquery to your project.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.2.js"></script>
  • 1

    It is not using jquery

  • 1

    True, I had not noticed, I do not know that it has some restriction not to use, since it did not quote, but anyway, I will edit my answer talking to add Jquery

1


Send the data using an object of type Xmlhttprequest. I made an example by passing only the username. You can take 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);
}
  • Thank you for the answer! I put the sendData function in my dps script to close the checkForm function?

  • 1

    exact, and remember from inside the checkForm you use sendData(), the way I used.

  • posted the same way, I am not getting any return of php file. In my file I have <?php &#xA;&#xA;&#xA;if (isset($_GET['username'])){&#xA; $user = $_GET['username'];&#xA; echo "$user";&#xA;}&#xA;&#xA;?> I put the full code in the post

  • 1

    Try using $_POST instead of $_GET. I also noticed that you are sending to a page called register.php, it should not be register.php?

  • Sure, I tried, but it didn’t work either. I don’t get anything back

  • 1

    Forgive me forgot to add the line that defines the Content-Type, I edited the code, please try again

  • still not receiving php echo, in the form the username name is correct

  • 1

    Open the element inspecter and go to the console, check for any errors please

  • A warning and an error Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.&#xA;2form_script.js:19 Uncaught TypeError: Cannot read property 'innerHTML' of null

  • 1

    The error is in this line: if (username1.innerHTML == 'More than 4 letters' || password1.innerHTML == 'Password is too small' || Email1.innerHTML == 'Invalid email' || descrica1.innerHTML == 'Invalid description') Comes in chat

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.