0

Hey Everyone so I am trying to make a vueapp that makes an ajax call to a php page. On that php page I am running a few mysql statements the most important of which is a insert statement. if that page ajax call is successful and the insert statement runs successfully I want to redirect a page. If the ajax call or the insert statement fails or the user exists I want to redirect them the same page just render the page diffrently based on the result. I've tried doing it with sessions however when i try to use the ajax error function it fires everytime even when its successful. I know this as I get an alert error. But than when it goes to the result.php page I get success. I dont understand. Any help would be great!

<?php ob_start();
session_start();
include('head.php');
include('header.php');
?>
<div id="signUpFormContainer">
  <div id="signUpForm">
    <div class="inputDiv">
      <p>Username*</p>
      <input v-model="userName" placeholder="joseChang">
    </div>
    <div class="inputDiv">
      <p>Password*</p>
      <input type="password" v-model="password" placeholder="********">
    </div>
    <div class="inputDiv">
      <p>Confirm Password*</p>
      <input type="password" v-model="confirmPassword" placeholder="********">
    </div>
    <div class="inputDiv">
      <p>First Name*</p>
      <input v-model="firstName" placeholder="Jose">
    </div>
    <div class="inputDiv">
      <p>Last Name*</p>
      <input v-model="lastName" placeholder="Chang">
    </div>
    <div class="inputDiv">
      <p>Email*</p>
      <input v-model="email" placeholder="jchang@example.com">
    </div>
    <div class="inputButton">
      <input v-on:click.prevent="makeAccount" id="addButton" type="button" value="Sign Up"></input>
    </div>
  </div>
</div>
<div id="footerContainer"></div>

<script>
var app = new Vue({
  el: '#signUpForm',
  data: {
    userName: '',
    password: '',
    confirmPassword: '',
    firstName: '',
    lastName: '',
    email: ''
  },
  computed: {
    passwordsMatch: function() {
      if(this.password == this.confirmPassword) {
        return true;
      } else {
        return false;
      }
    },
    passwordRequirementsMet: function() {
      if(this.password.length >= 8) {
        return true;
      } else {
        return false;
      }
    },
    validEmail: function() {
      var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      if (!reg.test(this.email)) {
        return false;
      }
      return true;
    }
  },
  created: function() {
  },
  watch: {
  },
  methods: {
    makeAccount: function() {
      if(this.userName.length >= 8 && this.firstName != '' && this.lastName != '' && this.validEmail && this.passwordRequirementsMet && this.passwordsMatch) {
        var jsonString = JSON.stringify({
          userName: this.userName,
          firstName: this.firstName,
          lastName: this.lastName,
          password: this.password,
          email: this.email
        });
        $.ajax({
          url: 'makeAccount.php',
          dataType: 'json',
          type: 'post',
          contentType: 'application/json',
          dataType: 'json',
          data: jsonString,
          error: function(){
          alert('Error');
           window.location.href='result.php';
          },
          success: function(data){
            console.log(data);
            alert('success');
           window.location.href='result.php';
          }.bind(this)
        });
     }
    }
    }
  });

</script>
<?php include('foot.php');?>

?>

Heres the code for php page im making an ajax request to. (makeAccount.php)

<?php session_start();
$_SESSION['hitpage']=1
require_once('database.php');
  require_once('functions.php');  
  $requestBody = file_get_contents('php://input');
  $requestJSON = json_decode($requestBody);

  require_once 'lib/Braintree.php';

  $gateway = new Braintree_Gateway([
    'environment' => 'sandbox',
    'merchantId' => 'ygpmj36rrztwbw6x',
    'publicKey' => 'qrf7ncz6kskchgfh',
    'privateKey' => '2e9ab466fca6889dd5e570ac583c8a46'
  ]);

  $braintreeResponse = $gateway->customer()->create([
    'firstName' => $requestJSON->firstName,
    'lastName' => $requestJSON->lastName,
    'email' => $requestJSON->email
  ]);
  if ($braintreeResponse->success) {
    echo(json_encode($braintreeResponse));
  } else {
    echo(json_encode($braintreeResponse));
  }

  function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
  }

  $googleResponse = get_data('https://script.google.com/macros/s/AKfycbzz8Oh3Jqt5tP4wGcNyM8jVhwaMEr6S5AJ-MWqFlhPN1rSzBdSr/exec?name='.urlencode(stripslashes($requestJSON->userName)));

  function get_string_between($string, $start, $end){
      $string = ' ' . $string;
      $ini = strpos($string, $start);
      if ($ini == 0) return '';
      $ini += strlen($start);
      $len = strpos($string, $end, $ini) - $ini;
      return substr($string, $ini, $len);
  }

  $googleResponseParsed = get_string_between($googleResponse, '<title>', '</title>');

  echo($googleResponseParsed);
$username = $requestJSON->userName;
$username = mysqli_real_escape_string($mysqli, $username);
$firstname = $requestJSON->firstName;
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$lastname = $requestJSON->lastName;
$lastname = mysqli_real_escape_string($mysqli, $lastname);
$email = $requestJSON->email;
$email = mysqli_real_escape_string($mysqli, $email);
$cleanGoogleResponseParsed = $googleResponseParsed;
$cleanGoogleResponseParsed = mysqli_real_escape_string($mysqli, $cleanGoogleResponseParsed);
$customerid = $braintreeResponse->customer->id;
$customerid = mysqli_real_escape_string($mysqli, $customerid);

$password = $requestJSON->password;
$encryptedpassword=password_encrypt($password);
  $makeUserSQL = "INSERT INTO user (userName, firstName, lastName, email, driveFolderId, braintreeId, password)
  VALUES ('".$username."','".$firstname."','".$lastname."','".$email."','".$cleanGoogleResponseParsed."','".$customerid."','".$encryptedpassword."')";

  if ($mysqli->query($makeUserSQL) === TRUE) {
      echo "New record created successfully";
      $_SESSION['inserted'];
  } else {
      echo "Error: " . $makeUserSQL . "<br>" . $mysqli->error;
  }

$mysqli->close();

?>

Heres the code for result.php

<?php session_start();
if(isset($_SESSION['hitpage'])){$ajaxworked=1;} else{$axjaxworked=0;}
if(isset($_SESSION['inserted'])){$inserted=1;} else {$inserted=0;}
if($inserted==1 and $ajaxworked==1){echo 'success';}
if($inserted==0 and $ajaxworked==0){echo 'failed';}
session_destroy();
?>

2 Answers2

1

this.userName doesn't exist.

You can also directly do this instead of passing by a variable :

 window.location.href="successfullycreated.php?userName="+ <?php echo "'{$_GET['userName']}'";?>;
Sébastien S.
  • 1,444
  • 8
  • 14
1

As long as the new page has the param present you can just get it from the URL in JavaScript.

var userName = new URL(window.location.href).searchParams.get("userName");
Shaun Webb
  • 426
  • 5
  • 10