1

I'm trying to pass 3 variables to another script in my scripts folder to query the db.

EDIT: it refreshes to this page

http://localhost:8080/procity/changepassword.php?username=asdf&password=a&confirm=a&code=bba7886bec2591db69c58dd315144114

JavaScript

function resetPassword() {
    var user = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    var conf = document.getElementById('confirm').value;
    var code = document.getElementById('code').value;

    if (code.length == 0 || password.length == 0 ||
            user.length == 0 || conf.length == 0) {
        alert("Entries empty");
    } else if (password != conf) {
        alert("Passwords don't match");
    }  else {   
        $.ajax({
            type: "POST",
            url:  "scripts/changepassword.php", 
            data: {Username: user, Password: password, Code: code},
            dataType: "json",
            success: function(data) { alert("success"); }
        });
    }
}

HTML

<form>
<input id="username" placeholder="Username" name="username" type="text" /> 
<input id="password" placeholder="Password" name="password" type="password" />
<input id="confirm" placeholder="Confirm Password" name="confirm" type="password" />
<input id="code" placeholder="Code" name="code" type="text" /> 
<div class="registrationFormAlert" id="incorrectEntry"></div>
<p>&nbsp;</p>
<input class="btn" id="signinbut" onclick="resetPassword()" value="Reset"  type="submit" style="width:28%;" />
</form></div>

PHP

My scripts/changepassword.php:

if (isset($_POST['Username']) && isset($_POST['Password'])&& isset($_POST['Code'])) {

}

The problem is that this just refreshes the current page. It doesn't process the request.

Gene
  • 46,253
  • 4
  • 58
  • 96
  • my name= fields are all in lower case already – user2127136 Aug 21 '13 at 14:21
  • 1
    in ajax , he used Username as name , and username variable as value, it's correct – Charaf JRA Aug 21 '13 at 14:22
  • I would recommend removing the JS var declarations at the top of your script. You should be able to do -- data: $('form').serialize(), -- and it will serialize and send the proper POST for you. Once you do this you will have to make sure that your changepassword.php file $_POST[''] vars are called with the same case (lower or upper) as declared in your html name="" – MonkeyZeus Aug 21 '13 at 14:40

4 Answers4

4

When triggering the resetPassword() function, you have to prevent the default form submit action. Since you are using jQuery with the $.ajax, I'm going to use jQuery to do this:

// add this code after your resetPassword function

$('form').submit(function (e) {
    e.preventDefault();

    resetPassword();
});

Since I'm binding to the submit event of the form, you can remove the onclick attribute on your button:

<input class="btn" id="signinbut" value="Reset" type="submit" style="width:28%;">

Also you seem to be missing some closing brackets in your JavaScript.

Personally, I'd write it like this:

JavaScript

$('form').submit(function (e) {
    'use strict';

    var user = $('#username').val();
    var password = $('#password').val();
    var conf = $('#confirm').val();
    var code = $('#code').val();

    e.preventDefault();

    if (code.length === 0 || password.length === 0 || user.length === 0 || conf.length === 0) {
        alert("Entries empty");
    } else if (password !== conf) {
        alert("Passwords don't match");
    } else {

        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: "json",
            success: function (data) {

                alert("success");

            }

        });
    }
});

HTML

Notice that I've removed the name attribute from the confirmation input, to prevent that from being serialized. Also, I've added the required attribute for the inputs.

<form action='scripts/changepassword.php' method='POST'>
    <input id="username" placeholder="Username" name="username" type="text" required />
    <input id="password" placeholder="Password" name="password" type="password" required />
    <input id="confirm" placeholder="Confirm Password" type="password" required />
    <input id="code" placeholder="Code" name="code" type="text" required />
    <div class="registrationFormAlert" id="incorrectEntry"></div>
    <p>&nbsp;</p>
    <button class="btn" id="signinbut" type="submit" style="width:28%;">Reset</button>
</form>

See jsFiddle.

PHP

Since the HTTP POST parameters are lowercase (as in the name attributes of the serialized form elements), the $_POST array keys should be lowercase in your PHP.

<?php

if (isset($_POST['username']) && isset($_POST['password'])&& isset($_POST['code'])) {
    // ... do something
    header('Content-Type: application/json; charset=utf-8');
    echo $someJsonOutput;
}
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
0

You need to prevent the default submit action

in pure JavaScript it's

form.addEventListener('submit',resetpassword,false)

function resetPassword(event){
    event.preventDefault();
    //your code here
}

this works on the button but also if you press the enter button.

in jquery its somehting like this..

$('form').submit(function(e){resetPassword(e);return false}) 

resetPassword(e){
e.preventDefault();
// your code
}

EDIT

The FORM when submit button is clicked or enter button is pressed

will trigger the event 'submit'

so if you remove the function caller from button

and add it to the form

you can press enter or click submit

in both cases it will execute your function

inside your function

the first argument in pure javascript and prolly also in jquery is the event

you need to stop that default event

and you do that with the ntive function

event.preventDefault();

so:

$('form').onsubmit(function(e){

e.preventDefault();


var user = document.getElementById('username').value;
var password = document.getElementById('password').value;
var conf = document.getElementById('confirm').value;
var code = document.getElementById('code').value;

if(code.length == 0 || password.length == 0 || user.length == 0 || conf.length == 0) {
    alert("Entries empty");
} else if(password != conf) {
    alert("Passwords don't match");
}  else {

    $.ajax({
     type: "POST",
     url:  "scripts/changepassword.php", 
     data: {Username: user, Password: password, Code: code},
     dataType: "jso..................

and your html

<form>
<input id="username" placeholder="Username" name="username" type="text" /> 
<input id="password" placeholder="Password" name="password" type="password" />
<input id="confirm" placeholder="Confirm Password" name="confirm" type="password" />
<input id="code" placeholder="Code" name="code" type="text" /> 
<div class="registrationFormAlert" id="incorrectEntry"></div>
<p>&nbsp;</p>
<input class="btn" id="signinbut" value="Reset" type="submit" style="width:28%;" />
</form>

Now said that take a look at pure javascript (maybe not compatible with all browsers) http://caniuse.com/xhr2

document.getElementsByTagName('form')[0].addEventListener('submit',function(e){
 e.preventDefault();
 // validate form here else return or alert something
 var xhr = new XMLHttpRequest;
 xhr.open( 'POST' , YOURURL );
 xhr.onload = function (){ alert('success') };
 xhr.send( new FormData( this ) )
} , false );
cocco
  • 16,442
  • 7
  • 62
  • 77
0

Change your code like this:

<script>
function resetPassword() {
    var user = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    var conf = document.getElementById('confirm').value;
    var code = document.getElementById('code').value;

    if(code.length == 0 || password.length == 0 || user.length == 0 || conf.length == 0) {
        alert("Entries empty");
    } else if(password != conf) {
        alert("Passwords don't match");
    }  else {

        $.ajax({
         type: "POST",
         url:  "scripts/changepassword.php", 
         data: {Username: user, Password: password, Code: code},
         dataType: "json",
         success: function(data) {

            alert("success");

         }

        });
    }
}
</script>

<form>
<input id="username" placeholder="Username" name="username" type="text" /> 
<input id="password" placeholder="Password" name="password" type="password" />
<input id="confirm" placeholder="Confirm Password" name="confirm" type="password" />
<input id="code" placeholder="Code" name="code" type="text" /> 
<div class="registrationFormAlert" id="incorrectEntry"></div>
<p>&nbsp;</p>
<input class="btn" id="signinbut" onclick="resetPassword();return false;" value="Reset"  type="submit" style="width:28%;" />
</form></div>

I have changed only two places. First error: while using onclick event, use return false to avoid the form from getting submitted to next page(if you are using ajax). Also your code is improperly formatted before. I have changed them. It should work now

Ganesh Babu
  • 3,590
  • 11
  • 34
  • 67
0

Before using Ajax, we should check with the following:

  • We should be careful in using <input type="submit" onclick="functioncall()">, since submitting a form by clicking this button will eventually redirect us to action page specified in form.
  • That's why you have got this link http://localhost:8080/procity/changepassword.php?username=asdf&password=a&confirm=a&code=bba7886bec2591db69c58dd315144114
  • The solution is simple: Stop submit event from executing. Use event.preventDefault() or return false in this situation.

I personally recommend the Ajax-PHP by the method suggested in this fiddle

The fiddle is created by another user and this method can be used for Ajax-PHP

Ganesh Babu
  • 3,590
  • 11
  • 34
  • 67