简体   繁体   中英

echo out php variable in jQuery

this is changepassword.php file

<?php 

include 'core/init.php';

if (empty($_POST) === false) {

  if (md5($_POST['current_password']) === $user_data['password']) {

 } else {

 $errors[] = 'Your current psasword is incorrect';

}


   }

if (empty($_POST) === false && empty($errors) === true) {

    change_password($session_user_id, $_POST['password']);

    } else if (empty($errors) === false)  {


    $error = output_errors($errors);

this variable

    }
?>

this is the jQuery file

$('#save_pass').click(function(){


    var current_password = $('#current').val();
    var password = $('#new').val();
    var password_again = $('#confirm').val();   

    if ((password == password_again) && (password.length >= 8)) {


    $.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });

        $('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
    } else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {

        $('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);

        } else  {

             $('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }

             $('#current').val(null);
             $('#new').val(null);
             $('#confirm').val(null);
    });

i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"

You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:

<script>
function something() {
    alert('<?php echo $error; ?>');
}
</script>

In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post() :

$.post('changepassword.php', {current_password: current_password ...})
    .done(function (data) {     
        alert(data);
    }

This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM