ZeusV
ZeusV

Reputation: 21

Pass a variable to php

I need to pass variable "x" to php and I don't know how. (I am very new to html. If you need more info tell me please. THX :D )

function functionT() {
  swal({
      title: "For help",
      text: "Write your phone number here and we will call you:",
      type: "input",
      showCancelButton: true,
      closeOnConfirm: false,
      animation: "slide-from-top",
      inputPlaceholder: "ex: 0711342647"
    },
    function(inputValue) {
      if (inputValue === false) return false;

      if (inputValue === "") {
        swal.showInputError("Try again");
        return false
      }
      x = inputValue;

      swal("", "You were added on our list: " + x, "success");

    });
}

Upvotes: 0

Views: 67

Answers (2)

ZeusV
ZeusV

Reputation: 21

I found a working way.

function functionT() {
  swal({
  title: "For help",
  text: "Write your phone number here and we will call you:",
  type: "input",
  showCancelButton: true,
  closeOnConfirm: false,
  animation: "slide-from-top",
  inputPlaceholder: "ex: 0711342647"
},
function(inputValue){
  if (inputValue === false) return false;

  if (inputValue === "") {
    swal.showInputError("Try again");
    return false
  }
  x = inputValue;



  swal("", "You were added on our list: " + x, "success");
  phone(x);
});
}
function phone(x){

var xmlhttp = new XMLHttpRequest();
  var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                res = xmlhttp.responseText;

            }
        };
  xmlhttp.open("GET", "php.php?x="+x, true);
  xmlhttp.send();

And php :

<?php
$myfile = fopen("newfile.txt", "a+") or die("Unable to open file!");
$phone_nr = $_GET['x'];
fwrite($myfile, $phone_nr);
fclose($myfile);
?> 

php will write in "newfile.txt" the phone number.

Upvotes: 1

AlwaysConfused
AlwaysConfused

Reputation: 478

Javascript/Jquery is served client side whilst PHP is served server side, that means you cannot add the x value to a php variable until the form/page is posted. Easy work around is to create a hidden input element with id myxinputbox in your form element, add the x value in there -

document.getElementById('myxinputbox').value = x;

Then, when you post the form, add x to php -

$posted_x = $_POST['myxinputbox'];

Upvotes: 0

Related Questions