0

I have another php question, but now when i click the register button it doesnt run the ajax request, it's just refreshing

    <!DOCTYPE html>
<html>
<style>
/* Full-width input fields */
input[type=text], input[type=password] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

/* Set a style for all buttons */
button {
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 100%;
}

button:hover {
    opacity: 0.8;
}

/* Extra styles for the cancel button */
.cancelbtn {
    width: auto;
    padding: 10px 18px;
    background-color: #f44336;
}

/* Center the image and position the close button */
.imgcontainer {
    text-align: center;
    margin: 24px 0 12px 0;
    position: relative;
}


.container {
    padding: 16px;
}

span.psw {
    float: right;
    padding-top: 16px;
}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    padding-top: 60px;
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button (x) */
.close {
    position: absolute;
    right: 25px;
    top: 0;
    color: #000;
    font-size: 35px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: red;
    cursor: pointer;
}

/* Add Zoom Animation */
.animate {
    -webkit-animation: animatezoom 0.6s;
    animation: animatezoom 0.6s
}

@-webkit-keyframes animatezoom {
    from {-webkit-transform: scale(0)} 
    to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
    from {transform: scale(0)} 
    to {transform: scale(1)}
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
    span.psw {
       display: block;
       float: none;
    }
    .cancelbtn {
       width: 100%;
    }
}
</style>
<body>



<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>
<div id="id01" class="modal">

  <form class="modal-content animate" >
    <div class="imgcontainer">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span>

    </div>

    <div class="container">
      <label><b>Username</b></label>
      <input type="text" value="" placeholder="Enter Username" id="uname" name="uname" required>

      <label><b>Password</b></label>
      <input type="password" value="" placeholder="Enter Password" id="uname" name="psw" required>

      <button onclick="login();" >Register</button>

    </div>

    <div class="container" style="background-color:#f1f1f1">
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>

    </div>
  </form>
</div>

<script>
document.getElementById('id01').style.display='block';
// Get the modal
var modal = document.getElementById('id01');

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
function login(){

$.ajax ({
  type: 'POST',
  url: 'register.php',
  dataType: 'json',
  data: {
    us: document.getElementById('uname').value,
    ps: document.getElementById('psw').value
  },
  success: function(data){
    if (data && data.success && data.redirect_url) {
      window.location.href = data.redirect_url;
    } else {
      console.log(data);
      alert('failed! see browser console for returned data!');
    }
  },
  fail: function(data){
    alert('Failed');
  }
});
}
</script>

</body>
</html>

Here is php code for creating file and change location in urlbar:

<?php
// get username and password
$username = $_POST['us'];
 $password = $_POST['ps'];
$file = fopen($username + '.' + $password, 'w');
// Here we need to create the sha1 hash as crypto-address
$crypto_address = sha1($username + $password);
// Write crypto address to file
fwrite($file, $crypto_address);
fclose($file);
// you want do have some validation here propably instead of assinging true 
to is_valid:
$is_valid = true;

if ($is_valid) {
echo json_encode(['success' => true, 'redirect_url' => 'user.php']);
die();
 }
 echo json_encode(['success' => false]);
 ?>

So why it doesn't work?

Regards, Christian

4
  • The question isn't very clear, but based on what I've guessed : your header is executed on your Ajax request not on the user ones. Look at your dev tools, the ajax request must be redirected Commented May 6, 2017 at 10:57
  • I didnt get what u mean i think u mean i should change location in javascript or what Commented May 6, 2017 at 11:00
  • Your header('Location: ...) is called in a code called via Ajax. So only the Ajax request can be redirected. If you want to redirect user you have to do it in your success callback Commented May 6, 2017 at 11:02
  • 1
    Extending what @NicolasPerraut said - add a location.href = "user.php" in the success callback Commented May 6, 2017 at 11:05

2 Answers 2

1

You have to do the redirection client side, ie in your javascript callback :

success: function(data){
   location.href = 'user.php'
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your browser will not redirect (location in urlbar will not update) because you perform an AJAX call, and not a form POST request. So, do this in JS:

$.ajax ({
  type: 'POST',
  url: 'register.php',
  dataType: 'json',
  data: {
    us: document.getElementByName('uname').value,
    ps: document.getElementByName('psw').value
  },
  success: function(data){
    if (data && data.success && data.redirect_url) {
      window.location.href = data.redirect_url;
    } else {
      console.log(data);
      alert('failed! see browser console for returned data!');
    }
  },
  fail: function(data){
    alert('Failed');
  }
});

And the PHP:

<?php
  // get username and password
  $username = $_POST['us'];
  $password = $_POST['ps'];
  $file = fopen($username + '.' + $password, 'w');
  // Here we need to create the sha1 hash as crypto-address
  $crypto_address = sha1($username + $password);
  // Write crypto address to file
  fwrite($file, $crypto_address);
  fclose($file);
  // you want do have some validation here propably instead of assinging true to is_valid:
  $is_valid = true;

  if ($is_valid) {
    echo json_encode(['success' => true, 'redirect_url' => 'user.php']);
    die();
  }
  echo json_encode(['success' => false]);

If the file was not created, we will need more info to come to a solution here, can you answer this?:

  • Any errors in your apache logs? (The folder you are trying to write a file to may not be writable by the user that executes the PHP at your webserver)
  • What is the response from the AJAX call? (visible in your browser debuggers 'network' tab):
    • 500: something wrong with your PHP code
    • 404: your PHP script might never be executed because you are using the wrong URL
    • 302 / 301: your script worked, your PHP should be OK

3 Comments

another question have nothing to do with this but maybe u know some good php hosting service free because last 4 suspended me for unknown reason after 5 minutes
Now it just refreshing site without even run the request, have updated the code below
try adding an id to the button instead and remove the inline onclick="login();" then do document.getElementById('<id from button>').onclick = function () { >AJAX CALL HERE> }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.