Adjusting a pre-made URL shortening script - javascript

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.

Related

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.

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

AJAX/PHP/JS readyState = 1 and Status = 0 ALWAYS. No response text

I've been trying lately to use this sample of AJAX to compare form data to an SQL database from one http://www.example.com domain. My issue is that the readyState is always 1 and my Status is always 0. It is expecting 4 and 200 respectively. It also always returns responseText="" I've looked all over StackOverflow but have unsuccessfully found anything helpful.
I've boggled my mind over what could be the issue, but I just can't seem to get it to work.
*I've also tried to set file permissions on both the JS and PHP, but it functions the same.
*I'm using a dedicated web server to host all this, and I have no problem running most scripts.
//HTML GenerateRep.html
Excuse the lack of < and > tags missing, the code won't appear without them.
form id="formgen" onsubmit="GenRep(this)"
....form stuff....
button id="submit" type="submit">Submit</button
//JAVASCRIPT GenerateRep.js
function GenRep(formgen) {
var email = formgen['repemail'];
var hash = formgen['reppass'];
var first = formgen['firstname'];
var last = formgen['lastname'];
var territory = formgen['territory'];
hash.value = CryptoJS.SHA256(hash.value);
var login = email + ";" + hash.value + ";" + first + ";" + last + ";" + territory;
Login(login);
}
function Login(login) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText == "VALID") {
window.location.href = "success.html";
} else if (xhttp.responseText == "INVALID") {
$("#login_error").text("Failed! Plese check your info.");
} else {
window.location.href = "error.php";
}
}
};
xhttp.open("GET", "Validate.php?q=" + login, true);
xhttp.send();
}
//PHP Validate.php
<?php
header('Access-Control-Allow-Origin: *');
include ("ConnectDB.php");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//THIS IS A TEST TO SEE IF reponseText FUNCTIONS. IT DOES NOT.
//echo "testecho";
$whole = $_REQUEST['q'];
$userPass = explode (";", $whole);
$sql1 = "SELECT UName FROM Reps WHERE UName = '$userPass[0]'";
$result = $conn->query($sql1);
if ($result->num_rows > 0) {
$conn->close();
echo "INVALID";
} else {
$sql = "INSERT INTO Reps (UName, Pass, FName, LName, Territory) VALUES ('$userPass[0]', '$userPass[1]', '$userPass[2]', '$userPass[3]', $userPass[4])";
if ($conn->query($sql) === FALSE) {
$conn->close();
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "VALID";
}
?>
I previously "commented" instead of creating an "Answer" because I wasn't suggesting a fix, just a debug step to make sure what you thought was happening, was actually happening.
Since my suggestion helped you figure out the problem, I created this "Answer" in case you want to give me "credit". :-)

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

How to use OnComplete?

I'm trying to use a Javascript/AJAX function that send an email (using a PHP page).
The function is:
new Request({
method: "post",
data: this,
onRequest: function() {
$('amCallMeBackForm').empty().addClass('amCallMeBackWait');
$('callback').setStyle('background', 'url(\'http://www.mysite.it/modules/mod_amcallmeback/assets/sfondo_callback.png\') no-repeat transparent');
$('callback').setStyle('height', '73px');
},
onComplete: function(response) {
$('amCallMeBackForm').removeClass('amCallMeBackWait');
$('amCallMeBackForm').addClass('amCallMeBackSent');
alert(response);
}
}).send();
});
It works fine, but i cannot manage the response from PHP page, where i've this code:
<?php
class modAmCallMeBackHelper
{
function send($params) {
// Check for request forgeries
JRequest::checkToken() or die( 'Invalid Token' );
// get data
$name = JRequest::getVar('name', '');
$rif = JRequest::getVar('rif', '');
$phone = JRequest::getVar('phone', '');
$uri = JRequest::getVar('uri', '');
// get module params
$subject = $params->get('mail_subject');
$reciptient = explode(',', $params->get('receipt_email'));
$app = JFactory::getApplication();
$sender = array($app->getCfg('mailfrom'), $app->getCfg('fromname'));
// make email
$Body = '<strong>Azienda:</strong> '.$name."<br />";
$Body .= '<strong>Riferimento:</strong> '.$rif."<br />";
$Body .= '<strong>Numero di telefono:</strong> '.$phone."<br />";
$Body .= '<strong>Pagina da cui รจ stato richiesto il contatto:</strong> <a href='.$uri.'>'.$uri."</a>";
$mailer =& JFactory::getMailer();
$mailer->setSender($sender);
$mailer->addRecipient($reciptient);
$mailer->setSubject($subject);
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($Body);
if ($name == '' || $rif == '' || $phone == '' || $name == 'Azienda' || $rif == 'Riferimento' || $phone == 'Telefono') {
} else {
$send =& $mailer->Send();
}
if ($send != true) {
return 'no';
} else {
return 'ok';
}
}
}
?>
When alert(response) is displayed i can see the whole html code ( included) from the page, but I'm not able to show only the "return" from the PHP page.
What am I doing wrong?
You can check an example of my problem here: http://www.sevenit.it (check at the top right of the page after 3 seconds)
Thanks
alert(response.responseText);
would be the way to go i believe.
EDIT:
Or what you might be wanting to do is:
$('#amCallMeBackForm').html(response.responseText)
Not 100% sure what you're asking.

Categories

Resources