How to build a php array with user input values? - javascript

**I need to take the values populated by users in 7 separate, single-line input fields and order them in a php array or set so that my built code can read them and validate them against a database **
I have built a functioning php code block that allows me to validate the address field values inputted by users through a Gravity Forms contact form to ensure they match a real world address. If the address does not match, they are not allowed to move forward with the form but instead need to input a valid address.
The code structure is here:
`
/**
* Address Verification
*/
add_filter( 'gform_field_validation_8_21', 'custom_address_validation', 10, 4 );
function custom_address_validation( $result, $value, $form, $field ) {
//address field will pass $value as an array with each of the elements as an item within the array, the key is the field id
if ( 'address' === $field->type && $field->isRequired ) {
GFCommon::log_debug( __METHOD__ . '(): Running.' );
//address failed validation because of a required item not being filled out
//do custom validation
$street1 = rgar( $value, $field->id . '.1' );
$street2 = rgar( $value, $field->id . '.2' );
$city = rgar( $value, $field->id . '.3' );
$state = rgar( $value, $field->id . '.4' );
$zip = rgar( $value, $field->id . '.5' );
//$country = rgar( $value, $field->id . '.6' );
//check to see if the values you care about are filled out
$required_inputs = array( '1' => $street1, '3' => $city, '4' => $state, '5' => $zip );
$empty_input = false;
foreach ( $required_inputs as $input_number => $input_value ) {
GFCommon::log_debug( __METHOD__ . '(): Is Hidden? ' . $field->get_input_property( $input_number, 'isHidden' ) );
if ( empty( $input_value ) && ! $field->get_input_property( $input_number, 'isHidden' ) ) {
$field->set_input_validation_state( $input_number, false ); // Only for Gravity Forms 2.5.10 or higher.
$empty_input = true;
GFCommon::log_debug( __METHOD__ . "(): Empty input: {$field->id}.{$input_number}" );
}
}
if ( $empty_input ) {
$result['is_valid'] = false;
$result['message'] = empty( $field->errorMessage ) ? 'This field is required. Please enter a street, city, state, and zip.' : $field->errorMessage;
return $result;
} else {
$valid_input=true;
$valid_url = true;
$key = "";
// Begin by removing any leading and trailing spaces in each element (e.g., " Houston" or "Lurleen Wallace ") and then reducing any multi-space sequences (e.g., " ") to a single space (" ")
$street1 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $street1);
$street2 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $street2);
$city = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $city);
$state = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $state);
$zip = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $zip);
if (str_contains($street1, " ")) {
$streetnumber = substr($street1,0,strpos($street1, " ", 0));
$streetname = substr($street1, strpos($street1, " ", 0)+1,iconv_strlen($street1));
} else {
GFCommon::log_debug( __METHOD__ . '(): Returning validation result.' );
$result['is_valid'] = false;
$result['message'] = $field->errorMessage ? 'This is not a valid address. Please enter the full address where you would like to receive gifts, starting with the street number and street name in Address Line 1.' : $field->errorMessage;
return $result;
}
if ( empty( $street2 )) {
$street2 = "";
}
if (strlen($street2) > 0) {
$street = $street1 . ", " . $street2;
} else {
$street = $street1;
}
$address = $street . ", " . $city . ", " . $state . " " . $zip;
$url = "https://" . "maps.google.com/maps/api/geocode/json?key=" . rawurlencode($key) . "&address=" . rawurlencode("{" . $address . "}");
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if ($resp['status']!=='OK') {
GFCommon::log_debug( __METHOD__ . '(): Returning validation result.' );
$result['is_valid'] = false;
$result['message'] = empty( $field->errorMessage ) ? 'This is not a valid address. Please enter the address where you would like to receive gifts.' : $field->errorMessage;
return $result;
} else {
foreach($resp['results'] as $res) {
$respstreetnumbershort = "";
$respstreetnumberlong = "";
$respstreetnameshort = "";
$respstreetnamelong = "";
$respstreet2short = "";
$respstreet2long = "";
$respcityshort = "";
$respcitylong = "";
$respstateshort = "";
$respstatelong = "";
$respzipshort = "";
$respziplong = "";
foreach ($res['address_components'] as $comp) {
if (in_array("street_number", $comp['types'])) {
$respstreetnumbershort = $comp['short_name'];
$respstreetnumberlong = $comp['long_name'];
}
if (in_array("route", $comp['types'])) {
$respstreetnameshort = $comp['short_name'];
$respstreetnamelong = $comp['long_name'];
}
// It turns out that the API doesn't return the address2 value (e.g., apartment number) at all, so the block below has just been commented out
//if (in_array("ADDRESS2_NAME_ON_GOOGLE_MAPS_API", $comp['types'])) {
// $respstreet2short = $comp['short_name'];
// $respstreet2long = $comp['long_name'];
//}
if (in_array("locality", $comp['types'])) {
$respcityshort = $comp['short_name'];
$respcitylong = $comp['long_name'];
}
if (in_array("administrative_area_level_1", $comp['types'])) {
$respstateshort = $comp['short_name'];
$respstatelong = $comp['long_name'];
}
if (in_array("postal_code", $comp['types'])) {
$respzipshort = $comp['short_name'];
$respziplong = $comp['long_name'];
}
}
if (($street1 !== $respstreetnumbershort . " " . $respstreetnameshort) and ($street1 !== $respstreetnumbershort . " " . $respstreetnamelong) and ($street1 !== $respstreetnumberlong . " " . $respstreetnameshort) and ($street1 !== $respstreetnumberlong . " " . $respstreetnamelong)) {
// $valid_input = false;
//}
//Note: The Google API doesn't even return a value corresponding to the unit/apartment number, etc., so there's not even a way to check this.
//if (strlen($street2) > 0) {
// if (($street2 !== $respstreet2short) and ($street2 !== $respstreet2long)) {
// $valid_input = false;
// }
//}
//if (($city !== $respcityshort) and ($city !== $respcitylong)) {
// $valid_input = false;
//}
if (($streetnumber !== $respstreetnumbershort) and ($state !== $respstreetnumberlong)) {
$valid_input = false;
}
if (($state !== $respstateshort) and ($state !== $respstatelong)) {
$valid_input = false;
}
if (($zip !== $respzipshort) and ($zip !== $respziplong)) {
$valid_input = false;
}
}
}
if ($valid_input) {
$result['is_valid'] = true;
$result['message'] = '';
} else {
$result['is_valid'] = false;
if (empty($respstreetnumberlong) or empty($respstreetnamelong) or empty($respcitylong) or empty($respstatelong) or empty($respziplong)) {
$result['message'] = empty( $field->errorMessage ) ? 'This is not a valid address. Please enter the address where you would like to receive gifts.' : $field->errorMessage;
} else {
if (strlen($respstreet2long) > 0) {
$result['message'] = empty( $field->errorMessage ) ? 'This is not a valid address. Did you mean: ' . nl2br("\r\n") . $respstreetnumberlong . ' ' . $respstreetnamelong . ', ' . $respstreet2long . ', ' . $respcitylong . ', ' . $respstatelong . ' ' . $respziplong: $field->errorMessage;
} else {
$result['message'] = empty( $field->errorMessage ) ? 'This is not a valid address. Did you mean: ' . nl2br("\r\n") . $respstreetnumberlong . ' ' . $respstreetnamelong . ', ' . $respcitylong . ', ' . $respstatelong . ' ' . $respziplong: $field->errorMessage;
}
}
}
}
}
GFCommon::log_debug( __METHOD__ . '(): Returning validation result.' );
return $result;
}
`
This works for Gravity Forms address fields as it handles the entire block of address inputs as one form or input that are all combined and my code can go down in order and validate each snippet of information as it needs. I only have to call 'gform_field_validation_8_21' to reference the entire form of 5 distinct fields.
However, this is not the only place I need to validate address information: when a user signs up for my site, I have my account signup form intake not only name, age, user ID, and password, but also Address, city, state, zip, and phone. This info is then auto-populated onto the user's profile. **These fields are not run by Gravity Forms and are instead individual, single-line text fields. I need to learn how to gather these individual fields and put them into an array. This will allow me to feed my function the collection of address fields (address, city, state, zip, phone) so that it may validate them against the database. **
My issue is I do not know the proper hook names for these fields in php, or where I go to find these names. I have been using browser Inspect tools to find CSS selector names for items and then reverse engineer to the proper identifier for an individual element I need to manipulate. However, I have not been able to narrow these field selectors down. For example: the CSS selector for this one particular input field is #field_5 while its selector path is html body.xprofile.bp-user.my-account.my-profile.profile-edit.profile.edit.buddypress.bp-nouveau.page-template-default.page.page-id-0.page-parent.logged-in.admin-bar.paged-2.page-paged-2.theme-buddyboss-theme.woocommerce-js.buddyboss-theme.bb-template-v1.buddypanel-logo-off.bb-custom-typo.header-style-1.menu-style-standard.sticky-header.bp-location-autocomplete.bp-search.elementor-default.elementor-kit-475.customize-support.js.bb-page-loaded div#page.site div#content.site-content div.container div.bb-grid.site-content-grid div#primary.content-area.bs-bp-container main#main.site-main article#post-1504.bp_members.type-bp_members.post-1504.page.type-page.status-publish.hentry.user-has-earned div.entry-content div#buddypress.buddypress-wrap.bp-single-plain-nav.bp-dir-hori-nav div.bp-wrap.bp-fullwidth-wrap div.bb-profile-grid div#item-body.item-body div.item-body-inner div.bp-profile-wrapper div.bp-profile-content div.profile.edit form#profile-edit-form.standard-form.profile-edit.billing-address div.editfield.field_5.field_first-name.field_order_1.required-field.visibility-adminsonly.field_type_textbox fieldset input#field_5
To summarize, my two questions are: 1. How do I learn the proper php call to select the value of these individual input fields? 2. How do I take these values and assign them to an array that I may feed my function so it may read and validate these fields?
I have explored this question and this thread but still not sure if it is what I need.

Related

How to show from which country / city the last login was made?

I have a problem that I will never be able to solve on my own, I hope someone will help me here, thank you for any answers and I appreciate any help.
Basically I have two functions, one sets the date of the last login and current login, while the other gets the login set by the first function. With simple shortcodes I can then display the date of the last login and current login. This works well, but in addition to the dates I also want to show the location from which the login was made and which browser was used.
Geolocation Function
So to do this I wrote a geolocation function that returns lat and long value, with reverse geocoding I then get the readable address. This also works well.
Get Browser Function
Then I wrote another little function that gets the browser used by the user with user agent, this also works wonderfully.
Main Problem
The problem with geolocation and get browser is that functions always return current values. But that's not what I want.
What I want to do is store locations and browsers at login (just like I do with dates) and then view them. In this way, if you log in at point A at 00:00, this will remain the same. Currently it does not do this because it is only hovering where you are at the moment and not where you were at 00:00.
So how can I memorize locations and browsers just like I am doing with dates? I specify that I am working on my website with wordpress.
Date function
// Function that get last login
function get_last_login($user_id, $prev = null) {
$last_login = get_user_meta($user_id);
$time = current_time( 'timestamp' );
if(isset($last_login['_last_login_prev'][0]) && $prev) {
$last_login = get_user_meta($user_id, '_last_login_prev', 'true' );
}
else if(isset($last_login['_last_login'][0])) {
$last_login = get_user_meta($user_id, '_last_login', 'true' );
}
else {
update_user_meta( $user_id, '_last_login', $time );
$last_login = $last_login['_last_login'][0];
} return $last_login;
}
// Shortcode (1) - Last Login Date
function last_login_date() {
global $current_user;
echo '<div class="lastlogin"> '.date("j/m/Y - H:i", get_last_login($current_user->ID, true)).' </div>';
} add_shortcode('lastlogin', 'last_login_date');
// Shortcode (2) - Current Login Date
function current_login_date() {
global $current_user;
echo '<p>Current: Login date: '. date("j M Y - H:i", get_last_login($current_user->ID)). '</p>';
} add_shortcode('currentlogin', 'current_login_date');
Geolocation function
//enqueue my-script
wp_enqueue_script( 'my-script', trailingslashit( get_stylesheet_directory_uri() ) . 'woocommerce/myaccount/assets/my-script.js', array( 'jquery-min' ), wp_get_theme()->version, true );
//pass ajax and a nonce to my-script
wp_localize_script( 'my-script', 'localize', array(
'_ajax_url' => admin_url( 'admin-ajax.php' ),
'_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
));
add_action( 'wp_ajax__wpso_73934145', function () {
if ( check_ajax_referer( '_ajax_nonce' ) ) {
$user_id = get_current_user_id();
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$openStreetMapObject = $_POST['openStreetMapObject'];
$meta_key = '_user_position';
$meta_value = array(
'latitude' => $latitude,
'longitude' => $longitude,
'openStreetMapObject' => $openStreetMapObject,
);
update_user_meta( $user_id, $meta_key, $meta_value );
wp_send_json_success( $meta_value );
} else {
wp_send_json_error();
};
wp_die();
});
my-script.js (for geolocation function)
console.log( 'my-script.js has been successfully loaded' );
if ( navigator.geolocation ) {
window.navigator.geolocation.getCurrentPosition( function( position ) {
let lat = position.coords.latitude;
let lon = position.coords.longitude;
//https://nominatim.org/release-docs/latest/api/Reverse/
$.getJSON(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}`, function( object ) {
let adress = object.address;
$.ajax( {
type: 'POST',
url: localize._ajax_url,
data: {
_ajax_nonce: localize._ajax_nonce,
action: '_wpso_73934145',
latitude: lat,
longitude: lon,
openStreetMapObject: adress,
},
success: function ( response ) {
console.log( response.data );
},
} );
} );
} );
};
my-template.php (to view everything).
$user_id = get_current_user_id();
$meta_key = '_user_position';
if ( metadata_exists( 'user', $user_id, $meta_key ) ) {
$meta_value = get_user_meta( $user_id, $meta_key, true);
//var_dump( $meta_value );
//var_dump( $meta_value['openStreetMapObject']["ISO3166-2-lvl6"] );
//echo $meta_value['openStreetMapObject']['county'];
//echo $meta_value['openStreetMapObject']['country'];
//var_dump( $meta_value['openStreetMapObject']['city_district'] );
//echo $meta_value['openStreetMapObject']['city_district'] ;
$mybrowser = $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
$mybrowser = $_SERVER['HTTP_USER_AGENT'];
if (strpos(strtolower($mybrowser), "safari/") and strpos(strtolower($mybrowser), "opr/")) {
// OPERA
$mybrowsername="Opera";
} else if (strpos(strtolower($mybrowser), "safari/") and strpos(strtolower($mybrowser), "chrome/")) {
// CHROME
$mybrowsername="Chrome";
} else if (strpos(strtolower($mybrowser), "msie")) {
// INTERNET EXPLORER
$mybrowsername="Internet Explorer";
} else if (strpos(strtolower($mybrowser), "firefox/")) {
// FIREFOX
$mybrowsername="Firefox";
} else if (strpos(strtolower($mybrowser), "safari/") and strpos(strtolower($mybrowser), "opr/")==false and strpos(strtolower($mybrowser), "chrome/")==false) {
// SAFARI
$mybrowsername="Safari";
} else {
// OUT OF DATA
$mybrowsername="OUT OF DATA";
};
echo $mybrowsername;
echo $meta_value['openStreetMapObject']['county'];
echo $meta_value['openStreetMapObject']['country'];
echo $meta_value['openStreetMapObject']["ISO3166-2-lvl6"];
} else {
echo 'You need to share your location';
};
your current code cannot work with what you're trying to achieve, you need to save a login activity everytime a user perform a login which includes all the details you want to pull later.
Here is a full example.
1. modify the login form and add two hidden input fields for latitude and longitude from navigator.geolocation which you can do via login_form action hook
add_action('login_form', function() {
?>
<input type="hidden" name="latitude" id="latitude" />
<input type="hidden" name="longitude" id="longitude" />
<script>
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition( (position) => {
const latitude = document.getElementById('latitude') // get the latitude input field
const longitude = document.getElementById('longitude') // get the longitude input field
latitude.value = position.coords.latitude // assign the latitude input value
longitude.value = position.coords.longitude // assign the longitude input value
})
}
</script>
<?php
});
2. Process all the data you want to pull later and save it on user meta once the user successfully login, you can inject it via wp_login action hook
add_action('wp_login', function( $uname, $user) {
$limit = 5; // the activity limit you want to save
$lat = $_REQUEST['latitude']; // get the latitude value from the login request
$long = $_REQUEST['longitude']; // get the longitude value from the login request
$browser = detectBrowser(); // generate browser data based on user agent
//generate location if latitude and longitude is present. Otherwise, use the user ip to generate the location
$location = $lat && $long && getLatLongLocation($lat, $long)->address ? getLatLongLocation($lat, $long)->address : getIPLocation();
$date = date('j/m/Y - H:i');
// Format the data to be saved as login activity
$loginDetails = [
'date' => $date,
'browser' => [
'ua' => $_SERVER['HTTP_USER_AGENT'],
'name' => ( isset( $browser->client ) && isset($browser->client->name) ) ? $browser->client->name : '',
'device_type' => ( isset( $browser->device ) && isset($browser->device->type) ) ? $browser->device->type : '',
'os' => ( isset( $browser->os ) && isset($browser->os->name) ) ? $browser->os->name : '',
],
'location' => [
'ip' => $_SERVER['REMOTE_ADDR'],
'city' => isset( $location->city ) ? $location->city : '',
'country' => isset( $location->country ) ? $location->country : '',
'lat' => $lat,
'long' => $long
]
];
$logins = get_user_meta($user->ID, '_login_activity', true); // get the user meta that holds the login activities
$logins = $logins ? $logins : []; // pass empty array if the user meta does not contain anything yet
array_unshift($logins, $loginDetails); // push the recent $loginDetails to the top of the login activities array
//Save the login activities, only save the array from 0 to $limit position
update_user_meta( $user->ID, '_login_activity', array_slice($logins, 0, $limit) );
}, 10, 2);
the above code you uses the following functions that request to 3rd party APIs to get the data;
// Get location details from IP address
function getIPLocation( $ip = false) {
$ip = $ip ? $ip : $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("https://ipinfo.io/{$ip}/json"));
return $details;
}
// Get location details from latitude and longitude
function getLatLongLocation( $lat = false, $long = false) {
if ( !$lat || !$long )
return;
$query = "format=json&lat=$lat&lon=$long&limit=1&email=test#email.com";
$details = json_decode(file_get_contents("https://nominatim.openstreetmap.org/reverse?$query"));
return $details;
}
// Get browser details from user-agent
function detectBrowser( $ua = false ) {
$ua = $ua ? $ua : $_SERVER['HTTP_USER_AGENT'];
$ua = urlencode( $ua);
$details = json_decode(file_get_contents("https://api.apicagent.com/?ua={$ua}"));
return $details;
}
You can check the output of these function by simply dumping the output like;
add_action('wp_head', function() {
$latLongLocation = getLatLongLocation('lat-here', 'long-here');
$ipLocation = getIPLocation('ip-here');
$uaDetails = detectBrowser('user-agent-here');
echo '<pre>', print_r($latLongLocation, 1), '</pre>';
echo '<pre>', print_r($ipLocation, 1), '</pre>';
echo '<pre>', print_r($uaDetails, 1), '</pre>';
});
After, you've added the modification for login_form and wp_login action hook, there should be a user meta with a key _login_activity everytime a user perform a login.
Now you can simply create a function to pull the value and display anywhere you want.
First, a function to format the HTML output for invidiual login record
// display format for individual login activity
function logFormat( $log ) {
if ( !$log || !is_array( $log ) )
return;
return '<div class="login-activity">
<div>Date: '.$log['date'].'</div>
<div>Browser: '.$log['browser']['name'].'</div>
<div>OS: '.$log['browser']['os'].'</div>
<div>City: '.$log['location']['city'].'</div>
<div>Country: '.$log['location']['country'].'</div>
<div>IP: '.$log['location']['ip'].'</div>
</div>';
}
then a function to get all or a single specific login record
// Pull the login activity with dynamic position attribute
function getLoginActivity( $atts ) {
//exit function of user is not logged
if ( !get_current_user_id() )
return;
// get the current user meta
$logins = get_user_meta(get_current_user_id(), '_login_activity', true);
//add shortcode attribute support
$attr = shortcode_atts([
'position' => 'all'
], $atts );
if ( !isset( $logins[0] ) )
return 'No Login Activity';
// Output all login activity if position is left to default
if ($attr['position'] === 'all' ) {
$out = '<div class="all-logins">';
foreach( $logins as $login ) {
$out .= logFormat( $login );
}
return $out. '</div>';
}
//return the login activity with exact position
if ( isset( $logins[ (int) $attr['position'] ] ) )
return logFormat( $logins[ (int) $attr['position'] ] );
return 'No activity with position: '. $attr['position'];
}
add_shortcode('login-activity', 'getLoginActivity'); // add shortcode support
then you can simply use getLoginActivity function anywhere in your php file, the current login details should be the 0 position and previous last login details should be the 1 position
so you can simply do
echo getLoginActivity(['position' => '0']); // current login data
echo getLoginActivity(['position' => '1']); // last login data
echo getLoginActivity(); // all login data
or via shortcode added to a page
[login-activity position="0"]

Form Validation not working as expected

I have made a cart-mechanism using PHP and done validation with the help of JavaScript and the validation is not working.
This is my actual php script:
$result = mysqli_query($conn, "SELECT * FROM products");
while($row = mysqli_fetch_array($result)){
$fieldidval[] = $row['product_id'];
$fieldnameval[] = $row['product_name'];
$fieldcostval[] = $row['product_cost'];
$fieldimgval[] = $row['product_image'];
$fielddescval[] = $row['product_description'];
}
//printing field values
for($i = 0; $i < mysqli_num_rows($result); $i++){
echo "<tr><form action = 'cart.php?pid=" . $fieldidval[$i] . "&name=" .$fieldnameval[$i] . "&cost=" . $fieldcostval[$i] . "' method = 'post' name = 'tocart' onsubmit = 'return(validateAll());'><td>" . $fieldnameval[$i] . "</td><td>" . $fieldcostval[$i] . "</td><td>" . $fieldimgval[$i] . "</td><td>" . $fielddescval[$i] . "</td><td><input type = 'text' name ='qty_input[$i]' ></td><td><input type = 'submit' name = 'submit'></td></form></tr>"; }
and this is my validation in javascript:
function validateAll(){
if( document.tocart.qty_input[0].value == "" ){
alert("Please enter a valid number");
document.tocart.qty_input.focus();
return false;
}
When I hit submit nothing works.
Converting comment to answer
If we keep the inline submit handler, pass the form using this
onsubmit = 'return validateAll(this);'
Then we can access the form directly in the handler without having to use the longer document.formname
function validateAll(form) { // "this" -> whatever is in (....) here
var qty_input= form["qty_input[0]"];
if (qty_input.value == "") {
alert("Please enter a valid number");
qty_input.focus();
return false;
}
}
Here is a better way using unobtrusive code
window.onload=function() { // when page loads. You can use event listener too
document.querySelector("[name=tocart]").onsubmit=function() {
var qty_inputs = document.querySelectorAll("[name^=qty_input]"); // starts with
for (var i=0;i<qty_inputs.length;i++) {
if (qty_inputs[i].value == "") {
alert("Please enter a valid number");
qty_inputs[i].focus();
return false;
}
}
}
}
And all this can be avoided by using
<input type = 'text' name ='qty_input[$i]' required />

Adjusting a pre-made URL shortening script

I'm not familiar with javascript and I'm sure the problem I have has a simple solution, I just need some direction.
The script below wasn't written by me, it's an URL shortening script. When the user inputs the long URL and presses submit the script creates a random short URL and displays the short URL in the input field. What I want to know is which part of the javascript controls the display of the short URL in the input? I want to change what is displayed after the URL is shortened.
page.php
<script src="script.js" type="text/javascript"></script>
<form action="#" id="form-add-url" class="profile" method="post" onsubmit="return add_url()">
<input type="text" id="urls-url" name="url" class="widefat-main" placeholder="Paste a link" tabindex="1" title="URL">
<input type="hidden" name="action" value="add_url">
<button type="submit" class="button-main" tabindex="3">Submit</button>
</form>
script.js
function add_url() {
jQuery("#front-url .loading-dark").fadeIn(200);
jQuery.post(url_base+"ajax.php", jQuery("#form-add-url").serialize(),
function(return_data) {
jQuery("#front-url .loading-dark").fadeOut(200);
data = jQuery.parseJSON(return_data);
var status = data.status;
if (status == "OK") {
jQuery("#urls-url").val(data.url);
} else if (status == "OK2") {
jQuery("#search_query").val("");
jQuery("#page_number").val("");
reload_urls("", 1);
jQuery("#urls-url").val(data.url);
} else if (status == "ERROR") {
show_notification("error", data.message, 3000);
} else {
show_notification("error", "Internal error. Please contact administrator.", 3000);
}
}
);
return false;
}
My PHP:
case 'add_url':
if ($options['only_registered'] == 'yes' && !$active_user)
{
$return_object = new stdClass();
$return_object->message = 'URL shortening is available for registerd users only.';
$return_object->status = 'ERROR';
echo json_encode($return_object);
exit;
}
$url = trim(stripslashes($_POST['url']));
if (substr(strtolower($url) , 0, 7) != "http://" && substr(strtolower($url) , 0, 8) != "https://") $url = 'http://' . $url;
$error = '';
if ($url == '')
{
$error = 'Hey, seems you forgot to paste a link.';
}
else
if (!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url))
{
$error = 'Are you sure you submitted the correct URL?';
}
else
if (sizeof($url) > 255)
{
$error = 'Hey, seems URL is too long.';
}
if (!empty($error))
{
$return_object = new stdClass();
$return_object->message = $error;
$return_object->status = 'ERROR';
echo json_encode($return_object);
exit;
}
if (substr(strtolower($url) , 0, strlen($url_base)) == strtolower($url_base))
{
$return_object = new stdClass();
$return_object->message = 'Hey. Seems this URL is short enough. ;-)';
$return_object->status = 'ERROR';
echo json_encode($return_object);
exit;
}
if ($active_user) $user_id = $active_user['id'];
else $user_id = 0;
$url_details = $icdb->get_row("SELECT * FROM " . $icdb->prefix . "urls WHERE url = '" . mysql_real_escape_string($url) . "' AND deleted = '0' AND user_id = '" . $user_id . "'");
if ($url_details)
{
$icdb->query("UPDATE " . $icdb->prefix . "urls SET created = '" . time() . "' WHERE id = '" . $url_details['id'] . "'");
$url_code = $url_details['url_code'];
}
else
{
$icdb->query("INSERT INTO " . $icdb->prefix . "urls (user_id, url, url_code, redirects, created, blocked, deleted, short) VALUES ('" . $user_id . "', '" . mysql_real_escape_string($url) . "', '', '0', '" . time() . "', '0', '0', '" . $_POST[short] . "')");
$url_code = url_code($icdb->insert_id);
$icdb->query("UPDATE " . $icdb->prefix . "urls SET url_code = '" . $url_code . "' WHERE id = '" . $icdb->insert_id . "'");
}
$htaccess = url_rewrite();
$return_object = new stdClass();
if ($active_user)
{
$return_object->status = 'OK2';
}
else $return_object->status = 'OK';
$return_object->url = $url_base . ($htaccess ? '' : '?u=') . $url_code;
echo json_encode($return_object);
exit;
break;
check this out
function add_url() {
// fading effect
jQuery("#front-url .loading-dark").fadeIn(200);
// posting with ajax post method
jQuery.post(url_base+"ajax.php", jQuery("#form-add-url").serialize(),
// success function after request complete
function(return_data) {
// applying fade out effect
jQuery("#front-url .loading-dark").fadeOut(200);
//parsing response string from server into javascript object
data = jQuery.parseJSON(return_data);
// getting status value
var status = data.status;
if (status == "OK") {
//putting [data.url] value in html element with id [urls-url]
//data.url => url value from server
jQuery("#urls-url").val(data.url);
} else if (status == "OK2") {
jQuery("#search_query").val("");
jQuery("#page_number").val("");
reload_urls("", 1);
jQuery("#urls-url").val(data.url);
} else if (status == "ERROR") {
show_notification("error", data.message, 3000);
} else {
show_notification("error", "Internal error. Please contact administrator.", 3000);
}
}
);
return false;
}
jQuery("#urls-url").val(data.url);
In the response of the post to url_base+"ajax.php" a JSON string is returned. The URL part of this response (data.url) is used as a value for you input (#urls-url).
I believe this is what you are after:
jQuery("#urls-url").val(data.url);
The .val() method is used to get and set the values of form elements such as input, select and textarea.
Thanks for your input guys! Very much appreciated.
The 4th last line in ajax.php (111.118.164.146/~jodeleep/ajax.php.html) was what I need to look for.

Get ajax result in different divs if success or error

I currently have my jQuery outputting the result in the same div as per error or success:
HTML
<div id="error-message").html(res);
JQUERY
jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
});
});
PHP
$error = '';
$uname = trim( $_POST['username'] );
$email = trim( $_POST['mail_id'] );
$fname = trim( $_POST['firname'] );
$lname = trim( $_POST['lasname'] );
$pswrd = $_POST['passwrd'];
if( empty( $_POST['username'] ) )
$error .= '<p class="error">Enter Username</p>';
if( empty( $_POST['mail_id'] ) )
$error .= '<p class="error">Enter Email Id</p>';
elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= '<p class="error">Enter Valid Email</p>';
if( empty( $_POST['passwrd'] ) )
$error .= '<p class="error">Password should not be blank</p>';
if( empty( $_POST['firname'] ) )
$error .= '<p class="error">Enter First Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) )
$error .= '<p class="error">Enter Valid First Name</p>';
if( empty( $_POST['lasname'] ) )
$error .= '<p class="error">Enter Last Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$lname) )
$error .= '<p class="error">Enter Valid Last Name</p>';
if( empty( $error ) ){
$status = wp_create_user( $uname, $pswrd ,$email );
if( is_wp_error($status) ){
$msg = '';
foreach( $status->errors as $key=>$val ){
foreach( $val as $k=>$v ){
$msg = '<p class="error">'.$v.'</p>';
}
}
echo $msg;
} else {
$msg = '<p class="success">Registration Successful</p>';
echo $msg;
}
} else {
echo $error;
}
die(1);
}
}
I'm getting confused on how to get the results in 2 different places.
1: Error = display errors and show the form, ideally errors should be displayed below each form field, at the moment is a div on top of the form
2: Success = hide the form, display only the success msg
METHOD 1
If you would like to have an error message per validated field then:
You have a form input, for example:
<input name="myfield" id="myfield" type="text">
Next to it, you can add a div or span with your alert/error message and appropriate id, something like:
<input name="myfield" id="myfield" type="text">
<span id="myfield_Error" class="none">Please fill this field</span>
Where class="none" in your css, is used to hide the error container. Something like:
.none {display:none;}
Now for your jquery part:
var myfield= $("#myfield").val();
if (myfield=='') { $("#myfield_error").show(); }
The trick here is to named your error containers in a similar way as your target form element you validate. So for id="fieldA" you will have the error id="fieldA_error".
EDIT1:
If you need to use classes, you need to modify a little the code.
You need to form an array of element to check.
Loop through the array.
And use somethign like:
var fieldName = $(this).attr('name');
var fieldVallue = $(this).val();
if (fieldVallue=='')
{
$("#"+fieldName+"_error").show();
}
else
{
$("#"+fieldName+"_error").hide;
}
Method 2
If you just like to have 2 different containers, one for success and one for error/failed validation, then you need to output something different from your php file.
So your php file can output someting like:
$report['status'] = 'error'
$report['message'] = 'error in xxxx field - please use a proper email'
echo json_encode($report);
Then in your ajax success you can check what response you got. You parse your json response and based on your 'status', you put your 'message' in different containers
I hope this is what you look for.
Alternatively you can assign an error handler as follow
var jqxhr = jQuery.post(
ajaxurl,
ajaxdata,
function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
}
).fail(function() {
alert("error");
});
and send a non-2xx code from your php code (with http_response_code) if it doesn't validate.
It would be easier for you to return (for example) JSON to the front end instead of one string. The JSON would containt key/value pairs in the form of ID => Message.
For example:
$errors = array();
if( empty( $_POST['passwrd'] ) ) {
$errors['st-psw'] = "Password should not be blank";
}
if( empty( $_POST['firname'] ) ) {
$errors['st-fname'] = 'Enter First Name';
} elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) ) {
$errors['st-fname'] = 'Enter Valid First Name';
}
...
...
if( empty( $errors ) ){
$response['success'] = true;
} else {
$response['success'] = false;
$response['errors'] = $errors;
}
echo json_encode($response);
Then you will loop the JSON object in your javascript and insert the error messages after each target.
Encode result array in JSON format and return the response.
<?php
if ($validation==false)
{
$result = array ('response'=>'error','message'=>'Some validation error');
}
else
{
$result = array ('response'=>'success','message'=>'Success');
}
echo json_encode($result);
?>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: "json",
success: function (data) {
if (data.response == 'error') {
alert('error');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
});
</script>

Can jQuery/JS check what changed the input?

can jQuery or plain JavaScript check how the value of input field was changed? Maybe something similar to that:
$('input').change(function(e){
e.preventDefault();
console.log(e.changedFunction.name);
});
I know given code doesn't work and doesn't do what I want. But is this even possible somehow?
Why do I need that? I have a dialog box where I have multiple forms (each form changes one thing). When I submit form, the value resets back to value which was there previously. e.g. In the form there's a word 'Hello', when I change it to 'Hello, World!', it successfully sends the data to $.post, but then resets the value to 'Hello'. I can't seem to find any function, neither php, nor javascript that changes the input. That's why I need to check what or who changes my input value back.
EDIT:
Including sample code.
editblock.php
} else if ($_POST['what'] == 'email') {
$sql = mysql_query("SELECT id, email, loggedin FROM users WHERE id = " . mres($_POST['id']) . " LIMIT 1");
$edit = mysql_fetch_array($sql);
$output .= '<div id="block-' . $_POST['what'] . '"><form method="post" id="form-' . $_POST['what'] . '">';
$output .= '<input type="hidden" name="id" value="' . mres($_POST['id']) .'" />';
$output .= '<input type="text" name="value" value="' . $edit['email'] .'" /> ';
$output .= '<input type="hidden" name="what" value="' . mres($_POST['what']) .'" />';
$output .= '<input type="submit" name="submit" value="OK" />';
$output .= '</form></div>';
$output .= '<script>
$("#form-' . $_POST['what'] . '").submit(function(event) {
event.preventDefault();
var $form = $( this ),
doval = $form.find( "input[name=\"value\"]" ).val(),
doid = $form.find( "input[name=\"id\"]" ).val(),
dowhat = $form.find( "input[name=\"what\"]" ).val();
$.post("/pages/profilis/doedit.php", { do: doval, id: doid, what: dowhat },
function( data ) {
$("#block-' . $_POST['what'] . '").empty().append( data );
$form.find("input[name=\"value\"]").val(doval);
}
);
});
</script>
';
}
doedit.php
else if ($_POST['what'] == 'email') {
if (empty($_POST['do'])) {
$error[] = 'err';
} else {
if ( ! preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $_POST['do'])) {
$error[] = "err";
}
$sql = mysql_query("SELECT `id` FROM `users` WHERE `email` = '" . mres($_POST['do']) . "' LIMIT 1");
if (mysql_num_rows($sql) == 1) {
$error[] = "err";
}
if ($edit['loggedin'] > 0) {
$error[] = "err";
}
if (sizeof($error) >= 1) {
echo join($error, '<br/>');
} else {
$sql = mysql_query("UPDATE users SET
email = '" . mres($_POST['do']) . "'
WHERE id = " .(int)$edit['id'] . "
LIMIT 1");
if ($sql) {
echo 'OK';
$logmsg = 'Changed email';
} else {
echo 'Error';
}
}
}
}
PHP function mres() escapes all the characters (for database injection protection - not really important here).
According to the situation which you explained. I would prefer you to use jqueryajax
in this Once the Post function is done you can change the value with the changed value
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg ); // portion where you can change the field value to the updated one.
});
Thanks and Regards,
Philemon Philip Kunjumon

Categories

Resources