echo out php variable in jQuery - php

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.

Related

Uncaught SyntaxError:

The code should make a pop up window, asking for confirmation "press ok to confirm the action for user" but it doesn't. i'm all out of ideas.
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
if(conf != true){
return false;
}
$(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "php_parsers/friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
$(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
$(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
$(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&user="+user);
}
</script>
PHP code:
<?php
$friend_button = '<button disabled>Request As Friend</button>';
$block_button = '<button disabled>Block User</button>';
// LOGIC FOR FRIEND BUTTON
if($isFriend == true){
$friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>';
}
else if($user_ok == true && $u != $log_username &&
$ownerBlockViewer == false){
$friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>';
}
// LOGIC FOR BLOCK BUTTON
if($viewerBlockOwner == true){
$block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>';
} else if($user_ok == true && $u != $log_username){
$block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>';
}
?>
Opening up the console i see "Uncaught SyntaxError: Invalid or unexpected token"
The console issue is with lines 2 & 3 of your JavaScript code;
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
You have a multi-line String which the console is not interpreting as one String value. In order to resolve, ECMAScript 6 (ES6) introduced template literals which can be utilized like below to handle multi-line Strings;
var conf = confirm(`Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.`);
(i.e. use back-ticks rather than double quotes to start & end the multi-line String)
Or, if ES6 isn't supported you can use good old String concatenation like below;
var conf = confirm("Press OK to confirm the '"+type+"' action for user" +
"<?php echo $u; ?>.");

How do I code this the smart way, Ajax/PHP

I've got myself a little script that checks the validity of a link supplied by the user, making it safe to store in the database (safer at least) and to confirm it's a link to facebook.
Now I want to roll this code out for another links, changing parameters as and when needed so that links to people user profile on these sites work, bit I dont want to copy and paste the code another 5 times and then try and adapt the Ajax to work with it, if theres a better way to approach this.
This is my code, it can been seen working at www.vwrx_project.co.uk/test.php. It hopefully only accepts facebook.com/(something here) .
link_checker.php
<?php
function check_url($dirty_url) {
//remove anything before facebook.com using strstr()
//clean url leaving alphanumerics : / . only - required to remove facebook link format with /#!/
$clean_url = strstr(preg_replace('#[^a-z0-9:/.?=]#i', '', $dirty_url), 'facebook.com');
$parsed_url = parse_url("http://www.".$clean_url); //parse url to get brakedown of components
$safe_host = $parsed_url['host']; // safe host direct from parse_url
// str_replace to switch any // to a / inside the returned path - required due to preg_replace process above
$safe_path = str_replace("//", "/", ($parsed_url['path']));
if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] != '' && $parsed_url['path'] != '/') {
echo "Facebook";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '') {
echo "missing_profile1";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '/') {
echo "missing_profile2";
} else {
echo "invalid_url";
}
}
?>
Test.php
<?php
include_once ("includes/check_login_status.php");
include_once ("includes/link_checker.php");
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["L"])){
$dirty_url = $_POST["L"]; //user supplied link
//$dirty_url = "http://www.facebook.com/profile.php?id=4";
// if $dirty_url is blank
if($dirty_url == ""){
echo "no link supplied";
exit();
} else {
check_url($dirty_url);
}
exit();
}
?>
<html>
<head>
<title>testing</title>
<script type="text/javascript" src="js/main.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function cleanURL(){
var user_url = _("user_link").value;
var func = _("hidden").value;
if(user_url == ""){
_("status").innerHTML = "Please provide a link before clicking submit";
} else {
_("submitbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "test.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no link supplied"){
_("status").innerHTML = "Submitted blank form data.";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "invalid_url"){
_("status").innerHTML = "The url supplied is invalid";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile1"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile2"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else{
_("status").innerHTML = ajax.responseText;
}
}
}
ajax.send("L="+user_url);
}
}
</script>
</head>
<body>
<p id="status"></p>
<form id="linkform" onSubmit="return false;">
<input type="text" id="user_link">
<input type="hidden" id="hidden" value="Facebook">
<button id="submitbtn" onClick="cleanURL()">Submit</button>
</form>
Why dont you add an additional parameter which is the website you want to allow?
function check_url($dirty_url, $websiteURL)
Then update your function to use the $websiteURL variable instead of the hardcoded 'facebook.com'
Then when you want to have several different urls you can do this
check_url($dirty_url, 'facebook.com');
or
check_url($dirty_url, 'twitter.com');
Or are you wanting to be able to check for multiple sites in the single function? such as facebook.com and twitter.com

POST php headers failing

When I call a script from Javascript
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var conf = document.getElementById('confirm').value;
var code = document.getElementById('code').value;
if(code.length == 0 || pass.length == 0 || user.length == 0 || conf.length == 0) {
alert("Entries empty");
} else if(pass != conf) {
alert("Passwords don't match");
}
window.location = "scripts/changepassword.php?Username="+user+"&Password="+pass+"&Code="+code;
changepassword.php in my scripts folder has the following headings its refreshing the current page and not passing the parameters into the script. any ideas?
it gives me error2.
scripts/changepassword.php
if (isset($_GET['Username']) && isset($_GET['Password'])&& isset($_GET['Code'])) {
...
} else {
$response = array('result'=>"error2");
echo json_encode($response);
echo "hi";
}
the window.location changes the page location (url). If you want to execute the php script without refreshing the page, use AJAX

Ajax + PHP validation and call Javascript function inside PHP validation

Basically, I'm trying to call a Javascript function inside a PHP script when using Ajax.
JavaScript:
<script type="text/javascript">
function Validate() {
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function() {
if ( hr.readyState == 4 && hr.status == 200 ) {
document.getElementById('message').innerHTML = hr.responseText;
}
}
hr.send('name=' + name);
}
function disable() {
document.getElementById('message').innerHTML = '';
}
</script>
HTML:
<div id="message"></div>
Name: <input type="text" id="name /">
<input type="button" onclick="Validate();" value="Validate" />
PHP:
<?php
$name = $_POST['name'];
if ( !empty( $name ) ) {
if ( $name == 'Tom' ) {
echo "<script>alert('Hello Tom, Welcome Back')</script>";
} else {
echo 'You are not Tom';
}
} else {
echo 'Please enter a name.';
}
?>
Everything works fine except calling the Javascript function inside PHP echo <script>alert()</script>
What I think the problem here is because I declared hr.responseText, as a result, the javascript I want to show has returned into text. But what should I do to solve this problem?
Any help would be appreciated.
Try changing your echo from "<script>alert('Hello Tom, Welcome Back')</script>";
to just 'Hello Tom, Welcome Back';
Then in your javascript you can call alert(hr.responseText);
You will have to change your javascript to check for what is returned so you know to call either the alert or the
document.getElementById('message').innerHTML = hr.responseText;
EDIT: I will add all the changed code...
<?php
$name = $_POST['name'];
if(!empty($name)){
if($name == 'Tom'){
echo 'Hello Tom, Welcome Back';
}else{
echo 'You are not Tom';
}
}else{
echo 'Please enter a name.';
}
?>
Javascript
<script type="text/javascript">
function Validate(){
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
response = hr.responseText.replace(/^\s+|\s+$/g,''); //remove whitespace so you can compare
if (response == ("You are not Tom") || response == ("Please enter a name."))
{
document.getElementById('message').innerHTML = hr.responseText;
}
else {
alert(hr.responseText);
}
}
}
hr.send('name=' + name);
}
function disable(){
document.getElementById('message').innerHTML = '';
}
</script>
Try this:
function do_alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
if(!empty($name)){
if($name == 'Tom'){
do_alert("You are tom");
}else{
do_alert("You are not tom");
}
}else{
echo 'Please enter a name.';
}
You didn't tag jQuery, but if you are using it, $.getScript might be what you want.
Aside from that, it might be better to build the script into your original document, and then execute this or that function based on the response text.

validating and submitting with 'if' and 'else' using PHP

This code is supposed to check to see if any fields are blank or invalid, if they are, it will turn them red. if all is ok then it will send to the database.
The problem is, if the last 'if' is not met, then the 'else' will fire.
This means as long as a valid email address is entered the form will submit, even if other fields are blank.
How can I make so that all requirements must be met for the form to submit
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
else {
//submits to database...
}
You can use a flag as:
$isValid = true;
if(empty($_POST['company'])) {
$isValid = false;
// your echo
}
Similarly add the $isValid = false; for all the other if bodies.
Finally remove your else part and replace it with:
if($isValid) {
// submit to DB.
}
you either can use else if, but then you won't see your "red" for all wrong fields but only for the first that failed validation.
like so:
if() {
} elseif() {
} else {
...
}
or you could set something to $error=false at the beginning, and set error to true inside the if controlled code and the submission to database checks if error is still false...
<?php
$error = 1;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if($error == 1) { //submits to database...
}
?>
There is a far better way of doing this instead of repeating your own code for each POST variable, which is not efficient.
// loop through all submitted fields
foreach( $_POST as $key => $value){
// see if the field is blank
if($value=="" || $value is null){
// if blank output highlighting JS
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$key."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
// variable to value showing form is invalid in some way
$invalid=1;
}
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$invalid= 1;
}
// if form invalid variable not set, submit to DB
if($invalid!=1){
// submit to DB
}
If you want to be super efficient you can simply use:
// search for any values that are null (empty fields)
$invalid_fields=array_keys($_POST, null);
// you may need to use $invalid_fields=array_keys($_POST, "");
// if there are any results from this search, loop through each to highlight the field
if($invalid_fields){
foreach( $invalid_fields as $key => $value){
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$value."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
}
$error = 1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 1;
}
if($error!=1){
// submit to DB
}
Introduce a Variable $sendToDb and initialy set it to (bool) true. If any of your checks fails, set this variable to false.
Then rewrite the else-Part and do a
if ($sendToDb) {
/* Your Db-Write code */
}
Take a flag variable and check like this
$flag=0;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if ($flag == 0)
{//submit to database
}
You really shouldn't be mixing server-side code (PHP) with client-side code (JavaScript).
Validate on the server side first. Then add validation on the client side. The reason being, if your user has JavaScript enabled then they'll get the error messages before the form submits. If they have JavaScript disabled, then your PHP script will throw the errors. Something like the following script:
<?php
if (isset($_POST['submit'])) {
$errors = array();
// do server-side validation
if ($_POST['fieldName'] == '') {
$errors['fieldName'] = 'fieldName is required';
}
if (count($errors) == 0) {
// save your record to the database or whatever
}
}
And then the following template:
<style>
.error { border-color: red; }
</style>
<script>
$(document).ready(function() {
$('form#yourFormId').submit(function() {
var errors = null;
if (errors.length > 0) {
return false;
}
});
});
</script>
<form action="yourScript.php" method="post" id="yourFormId">
<input type="text" name="fieldName" value="" id="id"<?php if (in_array('fieldName', $errors)) echo ' class="error"'; ?>>
<input type="submit" name="submit">
</form>
This will apply a class of .error to any invalid form fields, first by JavaScript and then server-side.

Categories