Form Validation not working as expected - javascript

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 />

Related

How to build a php array with user input values?

**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.

Refresh page without form resubmit

this is probably very simple but im really new to php and js
i made a comment system for my site but i have an issue that i cant figure out
//comment section
$commentsArray = array();
$commentQuery_run = mysqli_query($con, "SELECT * FROM comments WHERE PostID='$userPostId'");
if (mysqli_num_rows($commentQuery_run) > 0) {
echo "<b id='commcount'>Comments:".mysqli_num_rows($commentQuery_run).
"</b>";
while ($commentRow = mysqli_fetch_assoc($commentQuery_run)) {
$commentID = $commentRow['id'];
$commentUsername = $commentRow['username'];
$commentUserPfpPath = $commentRow['path'];
$commentContent = $commentRow['text'];
$commentDate = $commentRow['date'];
$commentsArray[] = $commentContent;
echo "html for displaying the comments";
}
} else {
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
if ($isLoggedIn === true) {
echo "<form id='commForm' method='POST' action=''> <
input id = 'commTextInp'
type = 'text'
placeholder = 'Your comment...'
name = 'commentText' > < br >
<
input id = 'commSubmInp'
type = 'submit'
name = 'commentSubmit'
value = 'Post Comment' >
<
/form>";
} else {
echo "<b id='commcount'>Please Login In to comment!</b>";
}
//comment section
//coment process
if (isset($_POST['commentSubmit'])) {
if (isset($_POST['commentText']) && !empty($_POST['commentText'])) {
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if (!in_array($postCommentContents, $commentsArray)) {
$postCommentQuery_run = mysqli_query($con, "INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if ($postCommentQuery_run === true) {
echo "<script> window.location.reload() </script>";
} else {
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
} else {
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
}
} else {
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
}
}
echo "</center>";
//comment process
every time i submit the form i get the "please dont repeat yourself/other users" error. why? does the window.location.reload() function also re-submit the form? or im I doing something completely wrong? and is there any better method for reloading the site? as it might be obvious i need to reload the page so that the new comment shows up. again, im really new to php/js/html so please explain why my code isnt working the way its supposed to. my guess is that the reload() method resubmits the form (excuse my bad english)
You better should place your POST-processing code in header of file, and you will be able to use header() redirect. To show error, you can use some flag; see:
// here we store all our comments
$commentsArray = [];
$commentQuery_run = mysqli_query($con,"SELECT * FROM comments WHERE PostID='$userPostId'");
while($commentRow = mysqli_fetch_assoc($commentQuery_run)){
$commentsArray[] = $commentRow;
}
//coment process
if(isset($_POST['commentSubmit'])){
if(isset($_POST['commentText']) && !empty($_POST['commentText'])){
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if(! array_search($postCommentContents, array_column($commentsArray, 'text')) ){
$postCommentQuery_run = mysqli_query($con,"INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if($postCommentQuery_run === true){
header("Location: " . $_SERVER['PHP_SELF']);
}
else {
$is_error = 'ERROR';
}
}
else{
$is_error = 'DUPLICATE';
}
}
else{
$is_error = 'NO_DATA';
}
}
and next, in the old place (in the middle of page) you can show error:
if(isset($is_error)) {
switch($is_error) {
case 'DUPLICATE':
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
break;
case 'NO_DATA':
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
break;
default:
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
}
// ...........
// PRINT ALL COMMENTS HERE
if(count($commentsArray)>0){
echo "<b id='commcount'>Comments:" . count($commentsArray) . "</b>";
foreach($commentsArray as $comment){
// $comment contains all your db-fields
echo "html for displaying the comments";
}
}
else{
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
every time i submit the form i get the "please dont repeat yourself/other users" error. why?
if(! in_array($postCommentContents, $commentsArray))
for first comment is true because:
if(mysqli_num_rows($commentQuery_run) > 0)
for first comment is false and commentsArray is empty.

Download brochure depends on the hidden field value

I have an html website and using brochure download option with form. I have many forms for every project. I need only one form that downloads the brochure depends on the hidden input value of the project.
jQuery(".form-js-pop-vedam").submit(function () {
var thisform = jQuery(this);
jQuery('.required-error',thisform).remove();
var pmail = jQuery("#pmail").val();
var pphone = jQuery("#pphone").val();
var psubject = jQuery("#psubject").val();
var data = {'pmail':pmail,'pphone':pphone,'psubject':psubject}
if (pmail == "") {
jQuery("#pmail").after('<span class="form-description required-error">Required field.</span>');
}else {
jQuery("#pmail").parent().find('.required-error').remove();
}
if (pphone == "") {
jQuery("#pphone").after('<span class="form-description required-error">Required field.</span>');
}else {
jQuery("#pphone").parent().find('.required-error').remove();
}
if ( pmail != "" && pphone != "" ) {
jQuery.post("contact_us_pop-vedam.php",data,function (result) {
if (result == "done") {
thisform.prepend("<div class='alert-message success-amairo'><i class='icon-ok'></i><p><span>Vedam brochure was sent to your mail. Thank you!</span></p></div>");
jQuery("#pmail").val("");
jQuery("#pphone").val("");
}
});
}
return false;
});
<form class="form-style form-js-pop-vedam" action="contact_us_pop-vedam.php" method=post>
<input type="hidden" name="psubject" id="psubject" value="Brochure Download from Vedam Page">
<div class="col-md-6" ><input type=email class=required-item id=pmail name=pmail value="" aria-required=true placeholder="Your Email*"></div>
<div class="col-md-6 " ><input class=required-item aria-required=true id=pphone name=pphone value="" placeholder="Your Phone*"></div>
<div class="col-md-6 " ><input name=submit type=submit value="Download Now >" class="submit_buttom buttonColor-side" id="Brochure_Download"></div>
</form>
<!-- language: lang-php -->
<?php
function clean_text($text='') {
$text = trim($text);
$text = strip_tags($text);
$text = addslashes($text);
$text = htmlspecialchars($text);
return $text;
}
if (!$_POST) {
die();
}else {
if (empty($_POST["pphone"]) && empty($_POST["pmail"]) ) {
echo "all_empty";
}else if (empty($_POST["pmail"])) {
echo "empty_mail";
}else if (empty($_POST["pphone"])) {
echo "empty_phone";
}else {
// edit this only :)
$your_email = "me#myweb.com";
$pmail = clean_text($_POST["pmail"]);
$pphone = clean_text($_POST["pphone"]);
$psubject = clean_text($_POST["psubject"]);
$subject = "$psubject";
$headers = "From: leads#website.in" . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8'. "\r\n";
$msg = "New Brochure Download \n<br />";
$msg .= "Email : \t $pmail \r\n<br />";
$msg .= "Phone : \t $pphone \r\n<br />";
echo "done";
$done = #mail($your_email, $subject, $msg, $headers);
}if($done)
{
if(($pmail)) {
$headerRep = "From: Website <info#website.in>";
$subjectRep = "Greetings from website!";
$messageRep = "Hi, \n\r
Thanks for showing interest in our property \n\r";
$messageRep .="You can download the brochure here http://www.example.in/pdf/brochure.pdf";
#mail($pmail, $subjectRep, $messageRep, $headerRep);
}
}
}
?>
<!-- end snippet -->
Lets talk generally about word (hidden) .. We have 2 cases
1st case: the input with type="hidden" you can use a selector like this
in css
input[type="hidden"]{}
and in js
$('input[type="hidden"]') // you can use .val() or .attr() depending on data you want from it
to check if the form has input with type hidden
if($('form').find('input[type="hidden"]').length > 0){ // in submit event use $(this).find instead if $('form').find
// yes this is input with type hidden here
}else{
// no input with type hidden here
}
and while you said (depends on the hidden input value) you can check that with
if($('form').find('input[type="hidden"]').val() == 'something'){ // in submit event use $(this).find instead if $('form').find
// type input hidden value = something
}else{
// type input hidden value not = something
}
2nd case: :hidden and :visible and that's about element is visible or not which I don't think you will need it here

JavaScript for form validation desn't seem to be getting called

I'm trying to validate a form with JavaScript. It prints error messages when input fields are empty. The problem I'm having is that the code doesn't fire on submit.
http://jsfiddle.net/LHaav/
Here is the HTML code:
<head>
...
<script type="text/javascript" src="./js/validate.js"></script>
....
</head>
...
<form name="submitForm" method="post" id="submitBetaForm" onsubmit="return(validate())" action="validate.php" class="form-style">
<label for="email">Email:</label>
<input type="text" id="email-beta" name="email" placeholder="Enter Email"/>
<label for="firstName">Name:</label>
<input type="text" id="firstName" class="half-width" name="messageName" placeholder="First name"/>
...
Here is the JavaScript code:
function validate()
{
var email = document.submitForm.email;
var first = document.submitForm.firstName;
var last = document.submitForm.lastName;
var message = document.getElementById('warning');
message.innerHTML = 'This is working!';
var newLineCharNum = 0, poemContentArray = 0;
//check to make sure that there is actually new line in the
//text area. Ensure that code doesn't blow up.
if(textarea.value.match(/\n/g) != null)
{
newLineCharNum = textarea.value.match(/\n/g).length;
poemContentArray = textarea.value.split("\n");
}
//check for email, firstName, lastName
//focus puts the cursor on the element that needs to be corrected.
var lineNum = newLineCharNum + 1;
// if(email.value.length > 30)
// {
// message.innerHTML = 'Email should be less than 30 character';
// title.focus();
// return false;
// }
else if(email.value.length == 0 || title == "")
{
message.innerHTML = 'Please enter your email';
title.focus();
return false;
}
if (firstName.value.length > 30)
{
message.innerHTML = 'First name should be less than 30 character';
authorName.focus();
return false;
}
else if(firstName.value.length == 0 ||authorName == "")
{
message.innerHTML = 'Please enter your first name';
authorName.focus();
return false;
}
if (lastName.value.length > 30)
{
message.innerHTML = 'Last name should be less than 30 character';
authorName.focus();
return false;
}
else if(lastName.value.length == 0 ||authorName == "")
{
message.innerHTML = 'Please enter your last name';
authorName.focus();
return false;
}
}
And PHP here:
<?php
session_start();
include('connection.php');
if(isset($_POST['SEND'])){
//get information from the form
$email = $_POST['email'];
$first_name = $_POST['messageName'];
$last_name = $_POST['messageLast'];
$interest = $_POST['interest'];
$country = $_POST['country'];
// Check connection
if ($con)
{
$insert_query = "INSERT INTO `user` (`id`, `first_name`, `last_name`, `interest`, `country`, `time`, `email`)
VALUES (NULL, '$first_name', '$last_name', '$interest', '$country', CURRENT_TIMESTAMP, '$email')";
$con->query($insert_query);
$con->close();
echo "here";
}
else{
echo "ERROR!";
}
//store informationn in the sessiont for later use
$_SESSION['email'] = $email;
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['interest'] = $interest;
$_SESSION['country'] = $country;
}
?>
It turns out that your example is full of bad variable names and references. Your using firstNmae when you should be using first, for instance.
I've corrected some of them and it's apparently working: http://jsfiddle.net/LHaav/1/
You just have to be aware of the JS errors in your browser console and you'll be fine. ;)
You got a good few problems in your Javascript - undefined variables everywhere. But the main problem is that your Javascript in that fiddle is not being executed at all. If you change your form handler to onsubmit="return validate()" you'll see that validate is not defined, although this may be down to how the JS is loaded in the fiddle.
Regardless, to alleviate this problem move your script out of the head and put it in the bottom of the page, just the before the closing body tag. You'll at least now hopefully hit the validate method.
http://jsfiddle.net/LHaav/2/
Now you'll have to take care of all those undefined variables.

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.

Categories

Resources