$_REQUEST['url'] is getting wrong url - javascript

I have a form defined like this:
<table>
<form id="myForm" method="post">
<tr><td> Item Name: </td><td><input type="text" name="itemname" id="itemname"/></td></tr>
<tr><td> Description:</td><td> <input type="text" name="description" id="description"/></td></tr>
<tr><td> Sell Time:</td><td> <input type="test" name="selltime" id="selltime"/></td></tr>
<tr><td> Price:</td><td> <input type="test" name="price" id="price"/></td></tr>
<tr><td> Image URL:</td><td> <input type="test" name="url" id="url"/></td></tr>
<tr><td><input type="submit" value="Post" name="info" onclick="return post();"></td></tr>
</form>
</table>
As you can see, onclick it calls the function post(). Which in turn reads the file post.php and sends it the required parameters (itemname,description,selltime,price,url). And finally they get inserted to some table in a database.
Here's the beginning of the file post.php:
<?php
session_start();
mysql_connect("localhost","root","password") or die("couldnt connect");
mysql_select_db("mynewdb") or die("couladnt find");
$output = '';
if(isset($_REQUEST['itemname']) && isset($_REQUEST['description'])
&& isset($_REQUEST['selltime']) && isset($_REQUEST['price']) &&
isset($_REQUEST['url'])){
$url = $_REQUEST['url'];
...
?>
Problem is url is sometimes got wrong. For example if i enter this url: coca cola
http://www.comax.co.il/Max2000Upload/1443/Prt_Pic%5C1%5C864.jpg
I get this inserted instead:
http://www.comax.co.il/Max2000Upload/1443/Prt_Pic1864.jpg
Why is that?
edit:
As requested, following is the post() function:
<script>
function post()
{
var itemname = document.getElementById('itemname').value;
var description = document.getElementById('description').value;
var selltime = document.getElementById('selltime').value;
var price = document.getElementById('price').value;
var url = document.getElementById('url').value;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById("posted").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("POST","post.php?itemname="+itemname+ "&description="+description+ "&selltime="+selltime
+"&price="+price+"&url="+url,true);
xmlhttp.send();
return false;
}
</script>

The "%5C" stands for a "\" and it might be escaping the following numbers, try to replace them with a "\\", this should keep the backslash in the url.

Related

How to send data from HTML form to Google Spreadsheet using JavaScript?

I'm trying to build a webapp that records datas from a form in a Google Spreadsheet. To do this, I have to use JavaScript (JSON or AJAX requests will work as well), but I cannot use Google Apps Script because I need the user to keep using my pages and GAS doesn't allow it.
I'm not so much versed in JSON requests but I tried to make an append one: no surprise, it's not working and no surprise, I don't know why.
I'm not sure the URL I used to make the request and the code are correct, but not knowing very well how to proceed, it's quite difficult to know what's wrong in my code.
That's my form:
<form name="reqForm" id="reqForm" method="post" action="" accept-charset="UTF-8" enctype="application/json">
<input type="hidden" name="area" id="area" readonly/>
<input type="hidden" name="idN" id="idN" readonly/>
<input type="hidden" name="dataReq" id="dataReq" readonly />
<label for="nome">* Nome:</label>
<input type="text" id="nome" name="nome" placeholder="Il tuo nome" />
<label for="cognome">* Cognome:</label>
<input type="text" id="cognome" name="cognome" placeholder="Il tuo cognome" />
<label for="mat">* Matricola:</label>
<input type="text" id="mat" name="mat" placeholder="La tua matricola" />
<label for="mail">* E-mail:</label>
<input type="text" id="mail" name="mail" placeholder="La tua e-mail" />
<label for="testo">* Richiesta:</label>
<textarea id="testo" name="testo" placeholder="Che cosa vuoi chiedere?"></textarea>
<button type="button" value="Invia" onClick="check()">Invia</button>
</form>`
The hidden values are set to provide an ID Number and the user's path.
The check() function will check the form and (should) make the request and write in the GSpreadSheet
function check() {
document.getElementById('errorForm').innerHTML = "";
var a = document.getElementById('area').value;
var idN = document.getElementById('idN').value;
var n = document.getElementById('nome').value;
var c = document.getElementById('cognome').value;
var m = document.getElementById('mat').value;
var em= document.getElementById('mail').value;
var t = document.getElementById('testo').value;
// check the possible errors and set error messages.
// if msg is not empty, writes the messages in my page.
} else if(msg == "") {
var xhr = new XMLHttpRequest();
var key = mySheetKey, sName = mySheetName, url = "https://sheets.googleapis.com/v4/spreadsheets/"+key+"/values/"+ sName + ":append?valueInputOption=USER_ENTERED";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
}
// Here I should create the object made of my variables I read
// from my form at the beginning of the code and send the request that
// should append my datas to my Spreadsheet
xhr.send();
}
}
As I said before, my code look similar to several ones I found online but it's not working and I don't know how to understand what's wrong.
Could you please kindly give me some tips or advice or some example that could help me appending data to a Google Spreadsheet?
A simple spreadsheet contained web app example
$(function() {
$('#btn1').click(validate);
$('#txt4').val('');
$('#txt3').val('');
$('#txt2').val('');
$('#txt1').val('')
});
function validate()
{
var txt1 = document.getElementById('txt1').value || ' ';
var txt2 = document.getElementById('txt2').value || ' ';
var txt3 = document.getElementById('txt3').value || ' ';
var txt4 = document.getElementById('txt4').value || ' ';
var a = [txt1,txt2,txt3,txt4];
if(txt1 && txt2 && txt3 && txt4)
{
google.script.run
.withSuccessHandler(setResponse)
.getData(a);
return true;
}
else
{
alert('All fields must be completed.');
}
}
The entire example:
The HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="data">
<br />Text 1<input type="text" size="15" id="txt1" />
<br />Text 2<input type="text" size="15" id="txt2" />
<br />Text 3<input type="text" size="15" id="txt3" />
<br />Text 4<input type="text" size="15" id="txt4" />
<br /><input type="button" value="submit" id="btn1" />
</div>
<div id="resp" style="display:none;">
<h1>Response</h1>
<p>Your data has been received.</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#btn1').click(validate);
$('#txt4').val('');
$('#txt3').val('');
$('#txt2').val('');
$('#txt1').val('')
});
function setResponse(a)
{
if(a)
{
$('#data').css('display','none');
$('#resp').css('display','block');
}
}
function validate()
{
var txt1 = document.getElementById('txt1').value || ' ';
var txt2 = document.getElementById('txt2').value || ' ';
var txt3 = document.getElementById('txt3').value || ' ';
var txt4 = document.getElementById('txt4').value || ' ';
var a = [txt1,txt2,txt3,txt4];
if(txt1 && txt2 && txt3 && txt4)
{
google.script.run
.withSuccessHandler(setResponse)
.getData(a);
return true;
}
else
{
alert('All fields must be completed.');
}
}
function loadTxt(from,to)
{
document.getElementById(to).value = document.getElementById(from).value;
}
console.log('My Code');
</script>
</body>
</html>
The Apps Script:
function getData(a)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'HH:mm:ss");
a.push(ts);
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Login').appendRow(a);
return true;
}
function doGet()
{
var html = HtmlService.createHtmlOutputFromFile('index');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}
My simple spreadsheet:
The good news is that you're probably a lot better at using the Google Chrome debugger now than before you started.

How to add new data into XML

register.htm
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<script type="text/javascript" src="shoponline.js"></script>
<title>ShopOnline Register Page</title>
</head>
<body>
<H3>ShopOnline</H3>
<table width="100%">
<tr>
<td><button class="button" name="btnHome" value="Home" onclick="location.href='login.htm';">Home</button></td>
<td><button class="button" name="btnListing" value="Listing" onclick="location.href='listing.htm';">Listing</button></td>
<td><button class="button" name="btnBidding" value="Bidding" onclick="location.href='bidding.htm';">Bidding</button></td>
<td><button class="button" name="btnMaintenance" value="Maintenance" onclick="location.href='maintenance.htm';">Maintenance</button></td>
<td><button class="button" name="btnLogout" value="Logout" onclick="location.href='#';">Log Out</button></td>
</tr>
</table>
<hr><br><br>
<I>To register a new account with ShipOnline, please complete the registration form below.</I>
<br><br>
<form>
<div class="form">
<fieldset>
<legend>Registration Details</legend>
<p style="text-align:left;">* Required Fields</p>
<br>
<table>
<tr>
<td style="text-align:right;">First Name <label>*</label></td>
<td><input type="text" id="txtFName" name="txtFName" class="textbox" placeholder="Enter Your First Name"
oninvalid="this.setCustomValidity('Please Enter Your First Name!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td style="text-align:right;">Surname <label>*</label></td>
<td><input type="text" id="txtSurname" name="txtSurname" class="textbox" placeholder="Enter Your Surname"
oninvalid="this.setCustomValidity('Please Enter Your Surname!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td style="text-align:right;">Email <label>*</label></td>
<td><input type="email" id="txtEmail" name="txtEmail" class="textbox" placeholder="Enter Your Email Address"
oninvalid="this.setCustomValidity('Please Enter Your Email!')" oninput="setCustomValidity('')" required /></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" name="btnRegister" value="Register" onclick="register()" />
<input type="button" name="btnReset" value="Reset" onclick="reset('registerForm')" />
</td>
</tr>
</table>
</fieldset>
</div>
<form>
<div id="information"></div>
</body>
</HTML>
shoponline.js
var xHRObject = false;
if (window.XMLHttpRequest)
xHRObject = new XMLHttpRequest();
else if (window.ActiveXObject)
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
function reset(formID) {
switch (formID) {
case 'loginForm':
document.getElementById('txtEmail').value = "";
document.getElementById('txtPassword').value = "";
break;
case 'registerForm':
document.getElementById('txtFName').value = "";
document.getElementById('txtSurname').value = "";
document.getElementById('txtEmail').value = "";
break;
}
}
function login() {
var email = document.getElementById('txtEmail').value;
var pass = document.getElementById('txtPassword').value;
xHRObject.open("GET", "login.php?id=" + Number(new Date) + "&email=" + email + "&pass=" + pass, false);
xHRObject.send();
if (xHRObject.responseText == true)
document.location.href = "bidding.htm";
else
window.alert("Login Failure!");
}
function register() {
var isFound = false;
var email = document.getElementById('txtEmail').value;
var firstName = document.getElementById('txtFName').value;
var surName = document.getElementById('txtSurname').value;
xHRObject.open("GET", "register.php?id=" + Number(new Date) + "&email=" + email + "&firstName=" + firstName + "&surName=" + surName, false);
xHRObject.send();
if (xHRObject.responseText == true)
window.alert("Registration Failure!");
else
window.alert("Registration Success!");
}
customer.xml
<customers>
<customer>
<ID>C1</ID>
<FirstName>Jack</FirstName>
<SurName>Wong</SurName>
<Email>jack#hotmail.com</Email>
<Password>081292</Password>
</customer>
<customer>
<ID>C2</ID>
<FirstName>Ashley</FirstName>
<SurName>Rachael</SurName>
<Email>ashley#hotmail.com</Email>
<Password>081292</Password>
</customer>
<customer>
<ID>C3</ID>
<FirstName>Vongola</FirstName>
<SurName>Steve</SurName>
<Email>vongola#hotmail.com</Email>
<Password>081292</Password>
</customer>
</customers>
register.php
<?php
$xmlFile = "customer.xml";
$isFound = false;
$count = 0;
// Check the XML is exist or not.
// If does, do checking against the email address.
if (file_exists($xmlFile)) {
$dom = new DOMDocument();
$dom->load($xmlFile);
$customer = $dom->getElementsByTagName("customer");
foreach($customer as $node) {
$fName = $node->getElementsByTagName("FirstName");
$valueFName = $fName->item(0)->nodeValue;
$email = $node->getElementsByTagName("Email");
$valueEmail = $email->item(0)->nodeValue;
if($_GET["email"] == $valueEmail)
$GLOBALS["isFound"] = true;
$GLOBALS["count"]++;
}
if ($isFound != true) {
// UNIQUE EMAIL, START UPDATE XML & SEND MAIL
$firstName = $_GET["firstName"];
$surName = $_GET["surName"];
$email = $_GET["email"];
$password = random_password(8);
$xml = new SimpleXMLElement($xmlFile);
$customer = $xml->addChild("customer");
$customer->addChild("ID", "C" .($count + 1));
$customer->addChild("FirstName", $firstName);
$customer->addChild("SurName", $surName);
$customer->addChild("Email", $email);
$customer->addChild("Password", $password);
$xml->saveXML($xmlFile);
}
} else {
// XML FILES NOT EXIST. STRAIGHT AWAY CREATE A NEW ONE AND SEND EMAIL
}
ECHO ($isFound);
?>
Basically, I was used AJAX for server and client communication.
Therefore, when end-users finish input their information at register.htm and it will go to javascript file using XMLHttpsRequest.open to register.php for updating data on XML.
But it doesn't update my XML data.
Any advise will be appreciate.

Dynamic input fields and one javascript

i have this js code:
function tickname(str,inpt) {
if (str.length == 0) {
document.getElementById(inpt).value = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(inpt).value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "tck_name.php?q=" + str, true);
xmlhttp.send();
}
}
According to sql query data php dynamically creates input fields
<input type="text" name="event_name_de" size="80" onkeyup="tickname(this.value,tick_de)" required><br>
<input type="text" id="tick_de" name="ticket_name_de" size="80" value="" readonly>
<input type="text" name="event_name_en" size="80" onkeyup="tickname(this.value,tick_en)" required><br>
<input type="text" id="tick_en" name="ticket_name_en" size="80" value="" readonly>
etc...
The problem is when i type some text in first field (name="event_name_de") and then another (name="event_name_en"), value changes only in input (name="ticket_name_de"). How to fix code, that input value will change according to current script logic?
P.s. sorry for my broken english :)
I made a fiddle for the answer I gave in the comments
https://jsfiddle.net/ak00nta8/
<input type="text" name="event_name_de" size="80" onkeyup="tickname(this.value,'tick_de')" required><br>

Using AJAX to pass variable to PHP and get that variabel again

I want to pass values to a PHP script so i am using AJAX to pass those and that part works. But in the same function I want retrieve those values that I passed to the PHP script. The problem is I cannot retrieve any value from the PHP file. I have search high and low, but now come to you for answers. How can I store the variable passed on to the PHP script so that my ajax can retrieve it? My code is as follows:
This is my form :
<!-- file album.php -->
<html>
<head>
<?PHP
include ("conection/connect.php");
?>
<script type="text/javascript" src="jstbl/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function cekjumlah(tableID)
{
var hitung=document.getElementById(tableID).rows.length;
var jumlah = hitung-1;
document.getElementById("media").value=jumlah;
}
</script>
</head>
<title></title>
<body>
<form name="form1" id="form1" method="post">
Jumlah Inputan :
<input type="text" id="media" name="media" size="5">
<input type="text" id="data_barang" name="data_barang" size="60" onKeyPress="onEnterPenjualan(event);">
<br><br>
<table id="tabelimei" border="1">
<tr id="Last">
</tr>
</table>
<br><br>
<div id="menu">
<p>
<input type="submit" name="simpan" value="Simpan" onClick="cekjumlah('tabelimei')">
<input onClick="deleteRow('DivTambah')" name="button" type="submit" value="Hapus" />
</p>
<p id="hasil">hasil</p>
</div>
</form>
</body>
</html>
And this is my jquery :
function onEnterPenjualan(e){// => Digunakan untuk membaca karakter enter
var key=e.keyCode || e.which;
if(key==13){// => Karakter enter dikenali sebagai angka 13
$(function(){
var data_barang = $("#data_barang").val();
$.ajax({
url: "ambildatabarang.php",
data: "data_barang="+data_barang,
cache: false,
success: function(data){
console.log(data);
alert(data);
}
});
var nama = alert (data.$nama);
var baris = document.getElementById("data_barang").value;
var i = 1;
var row = $(document.createElement('tr')).attr("id", 'DivTambah' + i);
row = '<tr>'+
'<td>1</td>'+
'<td><input name="cek[0]" id="cek" type="checkbox" size="10" /></td>'+
'<td><input name="qty_penjualan[0]" type="text" id="qty_penjualan" value="1" size="10" required/></td>'+
'<td><input type="text" name="imei_penjualan[0]" id="imei_penjualan" size="60" value="'+baris+'" required/></td>'+
'<td><input type="text" name="nama_penjualan[0]" id="nama_penjualan" size="30" value = "'+nama+'"required/></td>'+
'<td><input type="text" name="hargajual_penjualan[0]" id="hargajual_penjualan" value="300000" size="15" required/></td>'+
'<td><input type="text" name="diskon_penjualan[0]" id="diskon_penjualan" size="15" value="0"/></td>'+
'<td><input type="text" name="total_penjualan[0]" id="total_penjualan" size="15" value="300000" required/></td>'+
'<td><button type="button" class="del">Del</button></td>'+
'</tr>';
$(row).insertBefore("#Last");
var hapus = "";
document.getElementById('data_barang').value=hapus;
document.getElementById('data_barang').value.focus();
i++;
});
$(".del").live('click', function(){
$(this).parent().parent().remove();
});
}}
And this is my PHP file :
<?php
if (isset($_GET['data_barang'])){
// Instructions if $_POST['value'] exist
include ("conection/koneksidb.php");
$databarang = $_GET['data_barang'];
$datalengkapbarang = mysql_query("SELECT i.id_imeibarang, jb.nama_jenisbarang, b.type_barang, b.hargajual_barang FROM jenisbarang jb, barang b, imeibarang i WHERE i.id_imeibarang='$databarang' and i.idbarang_imeibarang=b.id_barang and b.idjenis_barang=jb.id_jenisbarang");
$angka = 1;
while($k = mysql_fetch_array($datalengkapbarang)){
echo $no[$angka] = $angka;
echo $imei[$angka]=$k['id_imeibarang'];
echo $nama[$angka]=$k['nama_jenisbarang'].$k['type_barang'];
echo $harga[$angka]=$k['hargajual_barang'];
$angka = $angka+1;
}
}
?>
to send the some data to php and get the result of the php file to javascript synchronously, this is what you need
function sendData (data1,data2)
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("POST", "url.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send("data1=" + data1 + "&data2=" + data2);
return AJAX.responseText;
}
else
return null;
}
now, on your php file, you just get your data like this
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
once you work with the data in your php file, and then you echo the result, it is returned by the javascript function, so you just need to use it like this in your javascript file
var data_from_php = sendData(data1,data2);

Javascript clearing comments of swear words

I am creating a comments board and via Javascript i am attempting to implement a piece of script which will prevent the user from submitting a paragraph if it has a undesirable word(s) in it. I have looked online and struggled to find any examples. This is what i have so far but not sure if i should be using index.of
index.php
<div class="askComment">
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $post; ?>">
<input type="hidden" name="type" value="A">
<p>Hello <strong><?php echo $fname; ?></strong> what do you have to say</p>
<input type="hidden" name="fname" id="comment-name" value="<?php echo $fname; ?>" >
<input type="hidden" name="userid" id="comment-mail" value="<?php echo $UserId; ?>" >
<p>Your comment *</p>
<textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." ></textarea>
<div id="error"></div>
<input type="submit" id="submit-comment" name="submit" value="Submit Comment">
</form>
</div>
mod_comment.php
$(document).ready(function () {
document.getElementById("submit-comment").disabled = true;
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").change(function () {
var comment = $("#comment").val();
if (comment.indexOf('????') === -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
} else {
document.getElementById("loginsubmit").disabled = false;
}
});
});
One possible solution (similar to your, same logic, just few changes/additions).
http://jsfiddle.net/pK7DK/
$("#submit-comment").attr('disabled', true);
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").on("keyup", function () {
var comment = $("#comment").val();
word = comment.split(' ');
for (i = 0; i < word.length; i++) {
worda = word[i].trim();
worda = worda.replace(/\.|,|!|:| |;|\?|\r?\n/g, ''); // bad word + one of chars = bad word
console.log(worda);
if ($.inArray(worda, swear) != -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
$("#submit-comment").attr('disabled', true);
break;
} else {
$("#error").html('');
$("#submit-comment").attr('disabled', false);
}
}
});
I would rather use 'keyup' event, so user will get error message(s) as he type. However - as mentioned, this can be easily overriden, server-side checking is a must.
Take a look at this: http://www.w3schools.com/jsref/jsref_search.asp (searches an array inside of an array);
It may not be the most optimal option, but it will be a start for your code.
EDIT: A better option (not the best, maybe) could be separating the comment string by words into an array and doing an intersection between the two arrays, here's a question explaining how to do intersections between arrays in js Simplest code for array intersection in javascript

Categories

Resources