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

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);

Related

HTML textbox.value not updating in JavaScript function

I have a PHP project containing textboxes to visualize STACK data structure concept; as seen in the screenshot below:
I am passing PHP values to JavaScript function and adding value only to the index number where there is no value (i.e Top of stack)
Below is the code:
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Structure Visualization</title>
<link rel=stylesheet href=StackStyleSheet.css>
<script type="text/javascript">
function addElement($id, $value)
{
var id = $id;
var value = $value;
//correct id and value is passed here.
var textbox = document.getElementById(id);
//this LOC does not execute and returns to the php code
textbox.value = value;
}
</script>
<body>
<?php include 'header.php'; ?>
<form method="POST" action="">
<div id ="container">
<div id="top">
<h3>STACK (ARRAY IMPLEMENTATION)</h3>
</div>
<div id="bottom">
<input id="inputBox" type="text" name="inputNumber" value="">
<button id="pushButton" type="submit" class="button button1" name = "PUSH">Push</button>
<button id="popButton" type="submit" class="button button2" name = "POP">Pop</button>
<button id="clearButton" type="submit" class="button button3" name = "CLEAR">Clear Stack</button>
</div>
<div id="operation">
<input type="text" name="5E" value="" class="operation1 obutton6">
<input type="text" name="4E" value="" class="operation1 obutton5">
<input type="text" name="3E" value="" class="operation1 obutton4">
<input type="text" name="2E" value="" class="operation1 obutton3">
<input type="text" name="1E" value="" class="operation1 obutton2">
<input type="text" name="0E" value="" class="operation1 obutton1">
</div>
</div>
</form>
<?php
include 'footer.php';
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['PUSH']))
{
$val0E = (int)$_POST['0E'];
$val1E = (int)$_POST['1E'];
$val2E = (int)$_POST['2E'];
$val3E = (int)$_POST['3E'];
$val4E = (int)$_POST['4E'];
$val5E = (int)$_POST['5E'];
//creating an associative array to store/add/delete values in the index locations
$elementsindex = array("0E"=>$val0E ,"1E"=>$val1E,"2E"=>$val2E, "3E"=>$val3E, "4E"=>$val4E, "5E"=>$val5E);
foreach ($elementsindex as $key => $value)
{
if(($elementsindex[$key])==null)
{
//value copied from textbox
$id = $key;
$value = $_POST['inputNumber'];
//value pushed in
$elementsindex[$key] = $value; //saves value against element index
//value reflected on screen box
echo '<script type="text/javascript">';
echo 'addElement("'.$id.'", "'.$value.'");';
echo '</script>';
break;
}
else if(($elementsindex[$key])!=null)
{
continue;
}
}
}
}
</body>
</html>
In the foreach loop, if the value at bottom index i.e index = 0E is null/zero, then a new value is added to it, after which we exit from the loop using break;
But, at the JavaScript function addElement(), the following code does not execute and immediately returns and no value is filled in the textbox.
var textbox = document.getElementById(id);
//this LOC does not execute and returns to the php code
textbox.value = value;
Where is the code wrong?

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.

Uncaught ReferenceError: function is not defined

I've been having a problem calling a function declared in an external .js file.
I've made an include of the .js file in the main page, but apparently it works in part (Just one function it is called correctly, the others generate an "Uncaught ReferenceError: function is not defined ")
Here's the Js file:`
<script type="text/javascript">
var maxAmount = 170;
// Modify the counter textField by given the textField to control and his counter
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount){
countDisplay.value = maxAmount - nameLenght;
}
else{
countDisplay.value = "0";
}
function titleShow(){
theTitle = val('title').replace(/^\s+|\s+$/g,"");
get('out_title').innerHTML = theTitle;
if(get('check_bold').checked == true){
highlightTerms('out_title');
}
}
function snippetShow(){
console.log("I've entered here");
theSnippet = val('description').replace(/^\s+|\s+$/g,"");
if(theSnippet.length + dateLength <= 156){
get('out_snippet').innerHTML = theSnippet;}
else{
var snipLimit = 153 - dateLength;
snippetSpace = theSnippet.lastIndexOf(" ",snipLimit);
get('out_snippet').innerHTML = theSnippet.substring(0,snippetSpace).concat(ellipsis.bold());}
}
function urlFunction(){
var theURL = val('in_url');
theURL = theURL.replace('http://','');
theURL = theURL.replace(/^\s+|\s+$/g,"");
get('out_url').innerHTML = theURL;
if(get('check_bold').checked == true){
highlightURL();}}
And here's the Main page: '
<?php
include('Code/Php_code.php');
include('Code/Js_code.js');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<form action="Database_Interface.php" method="post"><br>
Title:<br>
<input type="text" id="title" name="title" size="150" maxlength="150" value="<?php echo $title ?>" onKeyUp='textCounter("title","countDisplay");'><br>
<input readonly type="text" id="countDisplay" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Description:<br>
<input type="text" id="description" name="description" size="150" value="<?php echo $tags['description'] ?>" onKeyUp='textCounter("description","countDisplay2");'><br>
<input readonly type="text" id="countDisplay2" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Keywords:<br>
<input type="text" id="keywords" name="keywords" size="150" value="<?php echo $tags['keywords'] ?>" onKeyUp='textCounter("keywords","countDisplay3");'><br>
<input readonly type="text" id="countDisplay3" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
<input type="submit" value="Carica sul database">
<input type="button" value="see" onclick='snippetShow();'>
</form><br>
<div style="background-color:#f2f2f2; border:1px solid; border-color: black; position:relative;">
<h3><span id="out_title"></span></h3>
<div>
<cite><span id="out_url" ><?php echo $site ?></span></cite>
</div>
<div>
<span id="out_snippet">sdsdsdfvbfbf</span>
</div>
</div>
The answer is: why just the first method is called successfully while the other two generate an error?
Your first function seems to lack a closing } bracket. The last bracket is from the else block. Fixed:
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount) {
countDisplay.value = maxAmount - nameLenght;
}
else {
countDisplay.value = "0";
}
}
First of all close <script> tage at end of your js.php file byv </script>
Do not include js file before <doctype> tag.
include it in <head> tag OR before </body>

$_REQUEST['url'] is getting wrong url

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.

Add form fields dynamically populated dropdown list with php

I'm trying to make 3 form fields (a dropdown list dynamically populated by a .php script and 2 text fields) and also with a button add 3 more and 3 more and so on (as user clicks the button) I have tried several ways but nothing seems to work for me. (I'm noob in JS, AJAX, jQuery so I mostly tried scripts I've found on the internet).
Here's the code of these form fields:
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $sql = "SELECT common FROM species";
$speciesq = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($speciesq))
{
echo "<option value=\"" . $row['common'] ."\">" . $row['common'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
and after this form there's the code:
<script type="text/javascript">
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
}, "json");
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
getlist.php is a simple script that populates the dropdown list and sends the data:
<?php
include("dbcon.php");
$sql = mysqli_query ($con, "SELECT common FROM species");
$result = array();
while ($row = mysqli_fetch_array($sql)){
$result[] = array(
'value' => $row['common'],
);
}
echo json_encode($result);
?>
So when I click the "+" button (to add the row) nothing happens.
SOLVED: for those who come here please read also the comments below the answer.
You just have some code in the wrong spot:
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
needs to be moved into the post return function like this:
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1');
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}

Categories

Resources