PHP autoload is preventing POST - php

I developed my own PHP classes and used composer to manage all the dependencies between them. But whenever I include "vendor/autoload" on top of any PHP script, the page does not POST. None of the post data from any of the input elements is recognized or received by the script. The following script 'call.php' posts onto itself and nothing happens.
try
{
//------Page url
$url = 'call';
//------Set page timeout parameters
session_start();
if(isset($_SESSION['timeout']) && ((time() - (int)$_SESSION['timeout']) > 600)):
session_destroy();
header('Location: '.$url);
die();
endif;
$_SESSION['timeout'] = time();
//------Add required methods and classes
require dirname(__FILE__).'/../includes/vendor/autoload.php';
//------Get encrypted user id & device id
if(isset($_GET['id']) || isset($_GET['device'])):
//-----Decrypt user id and device id
$decrypt = new decryption();
$user_id = $decrypt->mc_decrypt($_GET['id']);
$device_id = $decrypt->mc_decrypt($_GET['device']);
//-----Validate decrypted data
$check = new validation();
$c_id = $check->check_number($user_id ,'n');
$c_device = $check->check_number($device_id ,'y');
if($c_id==1 && $c_device==1)
{
//-----Create a service object
$service = new service($user_id);
$status = $service->get_user_status();
//-----Check if the user has a valid status
if($status != 100)
{
header('Location: logout?logout&message='.$status.'#re101');
die();
}
else
{
$user_name = $decrypt->mc_decrypt($service->get_user_name());
//-----Check for previous service requests
$details = $service->get_service_call();
if($details)
{
$completed = false;
if($details['b'] == 'pending' )
{
$message = '<h2>Your request has been placed...</h2>';
$image = '<h2><img src="images/call_in.png alt="" height="100px" width="300px"/></h2>';
}
else if($details['b'] == 'processing' )
{
$message = '<h2>Your request is under process...</h2>';
$image = '<h2><img src="images/call_up.png" alt="" height="100px" width="300px"/></h2>';
}
else
{
$completed = true;
$service_id = $details['a'];
$message = '<h2>Your request has been fulfilled...</h2>';
$image = '<h2><img src="images/call_out.png" alt="" height="100px" width="300px"/></h2>';
}
$dated = $details['c'];
}
else
{
//-----Create a new service request
if($service->create_service_call($device_id))
echo "Service created";
$dated = date('d-m-Y', time());
}
}
}
endif;
//-----Once fulfilled, close the service by accepting user rating and feedback
if(isset($_POST['submit'])&&!empty($_POST['submit'])):
$id = !empty($_POST['service'])?$_POST['service']:'';
$rating = !empty($_POST['rate'])?$_POST['rate']:'';
$feedback = !empty($_POST['feed'])?$_POST['feed']:'';
$check = new validation();
$c_text = $check->check_textarea($feedback, 'y');
$feed = new service(0);
if(($rating == 10 || $rating == 5 || $rating == 1) && $c_text == 1)
{
if($feedback == '')
$feedback = 'nil';
if ($feed->give_service_feedback($id, $rating, $feedback))
$give = 'Thank you for your feedback!';
else
$give = 'Sorry, could not post your feedback.';
}
else
$give = 'Sorry, there was an error.';
endif;
}
catch(Exception $e)
{
$log = new misc();
$log->handle_ex($url, $_SESSION['account'], $e->getMessage(), $e->getFile(), $e->getLine());
header('Location: '.SITE.'404.shtml');
die();
}

Post via ajax
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- button to send form post -->
<button id="sendforms">Submit forms</button>
<div id="result"><!-- result of post page goes here --></div>
<script type="text/javascript">
$(document).ready(function () {
$("#sendforms").click(function() {
var combinedFormData = $("#form1").serialize();
$.post(
"test.php",
combinedFormData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>
so all the code post is made in the test.php file you can check if is set with php and also return it your form must have a id="form1" and don't need
action="page.php" method="post" please remove this from your form
also the button must be
<button id="sendforms">Submit forms</button>
If you did't understand I can make a implementation for your you if send all code the form and the php part

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; ?>.");

Load more instead of going to next page using pagination/API

I am working on a project to display select Instagram photos in an album by hashtag, since the Instagram API limits 35 images per API call I figured out I either had to use AJAX (which I am very poor at) or a mixture of PHP and AJAX. I decided on the latter because I didn't want my access token and user ID made available in the code on my gallery.
<?PHP
function jsongram($next=null){
$userid = "xxx";
$accessToken = "xxx";
$url = ("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}");
if($url !== null) {
$url .= '&max_id=' . $next;
}
//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
//unlink($cache); // Clear the cache file if needed
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}
?>
<html>
<head>
</head>
<body>
<?php
$data_array = array();
foreach ($jsonData->data as $data){
if (stripos($data->caption->text,'egypt') === false) {
}
else{
$data_array[] = $data;
$data = (str_split($data->caption->text));
$data = (array_filter($data));
}
}
foreach ($data_array as $data):{
$igimglow = $data->images->low_resolution->url;
$igimgstd = $data->images->standard_resolution->url;
$igimgthumb = $data->images->thumbnail->url;
$igcaption = str_replace('#', '', (preg_replace('/(?:#[\w-]+\s*)+$/', '', $data->caption->text)));
$igtime = date("F j, Y", $data->caption->created_time);
$iglikes = $data->likes->count;
$igcomments = $data->comments->count;
$iglong = $data->location->longitude;
$iglat = $data->location->latitude ;
$igusername = $data->user->username;
$igfullname = $data->user->full_name;
$iglink = $data->link;
$igfilter = $data->filter;
$igtags = implode(',',$data->tags);
?>
<img src="<?php echo ($igimglow);}?>">
<?php endforeach ?>
<?php
if(isset($jsonData->pagination->next_max_id)) {
$result .= '<div>Next</div>';
}
return $result;
}
?>
<div id="container">
<?=jsongram(#$_GET['next']);?>
<div id="result"></div>
</div>
</body>
</html>
Here's a live example of the above code:
http://johnricedesign.com/examples/pn.php
As shown above on the 2nd page photos tagged with "egypt" are displayed. I would like to replace the "Next" link to automatically load on the same page with a "Load More" button - to the best of my knowledge using AJAX is the only way of doing so. However I do not know how to do so, or even where to start. The second obvious problem I have is that even though I am removing the photos that don't contain the caption of "egypt" I am still getting a lot of blank spaces, I presume that will be rather simple to fix once AJAX is being used.
I have been pulling my hair out for the last 5 days trying to do this. You help, advice, wisdom, are much appreciated in advance.
I changed the the api to work with client_id rather than access_token. You can change it back it will have no effect.
Demo: https://tjay.co/l/instagrampagination
ajax.php
<?php
function jsongram($next = null)
{
$userid = "xxx";
$accessToken = "xxx";
$url = ("https://api.instagram.com/v1/users/{$userid}/media/recent/?client_id={$accessToken}");
if ( !empty($next) ) {
$url.= '&max_id=' . $next;
}
// Also Perhaps you should cache the results as the instagram API is slow
$cache = './' . sha1($url) . '.json';
// unlink($cache); // Clear the cache file if needed
// If a cache file exists, and it is newer than 1 hour, use it
if (file_exists($cache) && filemtime($cache) > time() - 60 * 60) {
$jsonData = json_decode(file_get_contents($cache));
} else {
$jsonData = json_decode(file_get_contents($url));
file_put_contents($cache, json_encode($jsonData));
}
return $jsonData;
}
function instaFormat($jsonData)
{
$data_array = array();
$response = array();
foreach($jsonData->data as $data) {
if ( !empty($data->caption->text) && stripos($data->caption->text, 'egypt') !== false ) {
$data_array[] = $data;
$data = (str_split($data->caption->text));
$data = (array_filter($data));
}
}
$response['next'] = $jsonData->pagination->next_max_id;
foreach($data_array as $data) {
$igimglow = $data->images->low_resolution->url;
// $igimgstd = $data->images->standard_resolution->url;
// $igimgthumb = $data->images->thumbnail->url;
// $igcaption = str_replace('#', '', (preg_replace('/(?:#[\w-]+\s*)+$/', '', $data->caption->text)));
// $igtime = date("F j, Y", $data->caption->created_time);
// $iglikes = $data->likes->count;
// $igcomments = $data->comments->count;
// $iglong = $data->location->longitude;
// $iglat = $data->location->latitude;
// $igusername = $data->user->username;
// $igfullname = $data->user->full_name;
// $iglink = $data->link;
// $igfilter = $data->filter;
// $igtags = implode(',', $data->tags);
$response['data'][] = '<img src="'.$igimglow.'">';
}
return $response;
}
if ( isset($_POST['next']) ) {
echo json_encode(instaFormat(jsongram($_POST['next'])));
die();
}
index.php
<!doctype html>
<html>
<body>
<div data-pictures></div>
<div><button type="button" data-get-next>Next</button></div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
jQuery(function($) {
$(document).on('get-feed', function(e, next_id) {
var data = {
next: next_id
};
$.post('ajax.php', data, function(response) {
var container = $('[data-pictures]');
response = $.parseJSON(response);
container.html('');
$('[data-get-next]').attr('data-get-next', response.next);
$.each(response.data, function(i, val) {
$(val).appendTo(container);
});
});
});
$('[data-get-next]').click(function() {
var next_id = $(this).attr('data-get-next');
$.event.trigger('get-feed', next_id);
});
$.event.trigger('get-feed', 0);
});
</script>
</body>
</html>

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

Reload a function without reloading the page

I want to callout a function without the page is reloading.
I know that this is possible with AJAX but i don't know how it works with calling a function.
I want to put a timer so it will reload the function every 3 seconds, so the users doesnt need to reload the page everytime to see if there is a new message.
$object = new Messages();
$object->ShowMessage($nick);
ShowMessage(); is the function that i want to call out every 3 seconds.
Full code :
public function ShowMessage() {
$st = $this->db->prepare("SELECT * FROM bericht");
$st->execute();
if($st->rowCount() == 0){
echo 'There is no message jet!';
}
foreach ($st as $bericht){
$uid = $bericht['uid'];
$nick = $this->db->prepare("SELECT * FROM users WHERE id=?");
$nick->bindParam(1, $uid);
$nick->execute();
foreach($nick as $name) {
$image = $name['foto'];
if($image == 'nophoto.jpg'){
echo '<img src="image/nophoto.jpg" width="60px" height="30px">';
} else {
echo '<img src="image/'; echo $image.'"'; echo ' width="60px" height="30px">';
}
echo json_encode($name['name']) .': ';
echo json_encode($bericht['message']).' <br> ';
}
}
}
You can do that with ajax. In order to do that, you need to implement ajax client function on frontend and a handler for processing ajax request. In frontend you can use jquery for ajax operations;
setInterval(function() {
$.get( "handler.php", function( data ) {
// You can use data. It is in json format.
// Ex: alert(data.message) . "message" is one of the
// fields of returned array in php handler file
});
}, 3000);
handler.php
<?php
$object = new Messages();
$result = $object->ShowMessage($nick);
// I assume this returns array.
// Ex: array("type" => "error", "message" => "Error occured on feed");
echo json_encode($result);
?>
Update: If you do not want to use json data
Update your code like below. Only use echo, you do not need to return json data.
public function ShowMessage() {
$st = $this->db->prepare("SELECT * FROM bericht");
$st->execute();
if($st->rowCount() == 0){
echo 'There is no message jet!';
}
foreach ($st as $bericht){
$uid = $bericht['uid'];
$nick = $this->db->prepare("SELECT * FROM users WHERE id=?");
$nick->bindParam(1, $uid);
$nick->execute();
foreach($nick as $name) {
$image = $name['foto'];
if($image == 'nophoto.jpg'){
echo '<img src="image/nophoto.jpg" width="60px" height="30px">';
} else {
echo '<img src="image/'; echo $image.'"'; echo ' width="60px" height="30px">';
}
echo $name['name'] .': ';
echo $bericht['message'].' <br> ';
}
}
}
and in js;
setInterval(function() {
$.get( "handler.php", function( data ) {
// alert(data);
});
}, 3000);
You need to do that integrating javascript to your php code.
Using jquery, you can take a look at $.post function. You can rise the event with the javascript function window.setInterval(yourFunction(),3000)
You also need to create a php page that will reply to the Ajax request, that will be passed as a parameter to the $.post
Just call that script via ajax:
.html:
setInterval(function(){
$.ajax({
url: "showMessageScript.php",
type: "post",
data: {nick: $("#nick").val(), token: <?php echo $_SESSION['token']; ?>},
success: function(jsonData){
$('#display').text(jsonData['message']);
}
});
},
3000);
showMessageScript.php:
function showMessage($nick) {
$object = new Messages();
$object->ShowMessage($nick);
echo json_encode(array('message': 'Your message is here'));
}
// check if authorized to do some action
if (!empty($_SESSION['token']) && $_SESSION['token'] == $_POST['token'] && !empty($_POST['nick'])) {
showMessage($nick);
} else {
echo json_encode(array('message': 'not authorized'));
}

Javascript Password Change Form Validation doesn't work on IE8

got this function to validate two fields from a changing password form and it's doesn't seem to work at IE8. FF, Opera, Safari and Chrome work.
function chk_form_pw()
{
if(document.getElementById('new_passwd').value == '')
{
alert("<?php _e('Please enter New Password') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value.length < 5 )
{
alert("<?php _e('Please enter New Password minimum 5 chars') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value == '')
{
alert("<?php _e('Please enter Confirm New Password') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value.length < 5 )
{
alert("<?php _e('Please enter Confirm New Password minimum 5 chars') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value != document.getElementById('cnew_passwd').value)
{
alert("<?php _e('New Password and Confirm New Password should be same') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
}
This is the form:
<form name="registerform" id="registerform" action="<?php echo get_option( 'siteurl' ).'/?page=account&chagepw=1'; ?>" method="post">
<p><label><?php _e('New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="new_passwd" id="new_passwd" class="lostpass_textfield" /></p>
<p><label><?php _e('Confirm New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="cnew_passwd" id="cnew_passwd" class="lostpass_textfield" /></p>
<p><input type="submit" name="Update" onclick="return chk_form_pw();" value="<?php _e('Update Password') ?>" class="btn grey"/></p>
</form>
And here is the chagepw=1 thing:
<?php
if($_POST)
{
if($_REQUEST['chagepw'])
{
$new_passwd = $_POST['new_passwd'];
if($new_passwd)
{
$user_id = $current_user->data->ID;
wp_set_password($new_passwd, $user_id);
$message1 = "Password Changed successfully.You need to sign back in.";
}
}else
{
$user_id = $userInfo['ID'];
$user_add1 = $_POST['user_add1'];
$user_add2 = $_POST['user_add2'];
$user_city = $_POST['user_city'];
$user_state = $_POST['user_state'];
$user_country = $_POST['user_country'];
$user_postalcode = $_POST['user_postalcode'];
$buser_add1 = $_POST['buser_add1'];
$buser_add2 = $_POST['buser_add2'];
$buser_city = $_POST['buser_city'];
$buser_state = $_POST['buser_state'];
$buser_country = $_POST['buser_country'];
$buser_postalcode = $_POST['buser_postalcode'];
$user_address_info = array(
"user_add1" => $user_add1,
"user_add2" => $user_add2,
"user_city" => $user_city,
"user_state" => $user_state,
"user_country" => $user_country,
"user_postalcode"=> $user_postalcode,
"buser_name" => $_POST['buser_fname'].' '.$_POST['buser_lname'],
"buser_add1" => $buser_add1,
"buser_add2" => $buser_add2,
"buser_city" => $buser_city,
"buser_state" => $buser_state,
"buser_country" => $buser_country,
"buser_postalcode"=> $buser_postalcode,
);
update_usermeta($user_id, 'user_address_info', serialize($user_address_info)); // User Address Information Here
$userName = $_POST['user_fname'].' '.$_POST['user_lname'];
$updateUsersql = "update $wpdb->users set user_nicename=\"$userName\", display_name=\"$userName\" where ID=\"$user_id\"";
$wpdb->query($updateUsersql);
$message = "Information Updated successfully.";
}
}
$userInfo = $General->getLoginUserInfo();
$user_address_info = unserialize(get_user_option('user_address_info', $user_id));
$user_add1 = $user_address_info['user_add1'];
$user_add2 = $user_address_info['user_add2'];
$user_city = $user_address_info['user_city'];
$user_state = $user_address_info['user_state'];
$user_country = $user_address_info['user_country'];
$user_postalcode = $user_address_info['user_postalcode'];
$display_name = $userInfo['display_name'];
$display_name_arr = explode(' ',$display_name);
$user_fname = $display_name_arr[0];
$user_lname = $display_name_arr[2];
$buser_add1 = $user_address_info['buser_add1'];
$buser_add2 = $user_address_info['buser_add2'];
$buser_city = $user_address_info['buser_city'];
$buser_state = $user_address_info['buser_state'];
$buser_country = $user_address_info['buser_country'];
$buser_postalcode = $user_address_info['buser_postalcode'];
$bdisplay_name = $user_address_info['buser_name'];
$display_name_arr = explode(' ',$bdisplay_name);
$buser_fname = $display_name_arr[0];
$buser_lname = $display_name_arr[2];
if($_SESSION['redirect_page'] == '')
{
$_SESSION['redirect_page'] = $_SERVER['HTTP_REFERER'];
}
if(strstr($_SESSION['redirect_page'],'page=checkout'))
{
$login_redirect_link = get_option( 'siteurl' ).'/?page=checkout';
}
?>
A smoother solution would be jQuery. There you can load a loading-animation, put color like red/green on wrong/correct and simplified print out text depending on what happening to the form.
Download jQuery from: http://docs.jquery.com/Downloading_jQuery
Then you insert it in the html code like this:
<script type="text/javascript" src="jquery.js">
</script>
Then you can have a valid.js like this:
$(document).ready(function () {
var validatefield = $('#validatefield');
$('#validatefield').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatefield.html('<img src="images/Here_you_can_put_your_gif_animation"
alt="Loading..."
height="16" width="16"/>');
this.timer = setTimeout(function () {
$.ajax({
url: 'check_field.php',
data: 'action=check_field&field=' + encodeURIComponent(t.value),
dataType: 'json',
type: 'post',
success: function (j) {
if (j.ok) {
validatefield.html(j.msg);
}
else if ($("#validatefield").val() == "")
{
validatefield.html('');
}
else {
validatefield.html(j.msg);
}
}
});
}, 200);
this.lastValue = this.value;
}
});
});
Then in the check_field.php, have this;
echo json_encode(check_field($_POST['field']));
function check_field($field) {
$fieldSum = stripslashes(strip_tags(trim(htmlspecialchars($field))));
$response = array();
if (strlen($fieldSum) > 15) {
$response = array(
'ok' => false,
'msg' => "The field characters were over 15!");
}
else
{
$response = array(
'ok' => true,
'msg' => "Correct");
}
return $response;
}
The id #validatefield is an id inside the html code that you have to create in order to print things out.
Example:
<div id="validatefield">Here comes the text etc, from the valid.js</div>
Finally got it done using the JQuery script posted before:
http://code.google.com/p/form-validation-engine/downloads/list
It's been really easy to fit into my previous code and works flawlessly through every browser tested.
Thank you all for your help!

Categories