Parsing Javascript Variable into php query - php

I am newbie in php and still learn javascript function.
I have a problem with, include javascript variable into php query.
I want to create transaction code according count of part code which have different type. then i must get value with count.
<script language="javascript" type="text/javascript">
function getCode(){
var v =document.forms["form1"]["part_code"].value;
<?php
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = "<script>v;</script>"");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
?>
var getPartCode = <? echo $code_part['count'];?>;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
<?
}
?>
</script>
The result like that 1/CPU/JKT/2013
I call that function with button onClick="getCode()" no submit.
Anyone can help me.

You can't do it by the way you tried.There are two better ways to do it
Use Ajax.
Use Cookies
The best way here is to use Ajax. Here, iam using javascript and ajax.And i am creating a new file to create response(say newfile.php) Try this,
function getCode(){
var v =document.forms["form1"]["part_code"].value;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var getPartCode=xmlhttp.responseText; //Getting the response from php file
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
}
}
xmlhttp.open("GET","newFile.php?q="+v,true); //Sending request to newfile.php
xmlhttp.send();
}
</script>
newfile.php
<?php
$value = $_GET["q"]; //getting the value sent through tthe ajax request
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = '$value'");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
echo $code_part['count'];
}
?>

Best Method is Ajax
Otherwise Use Cookies
For Eg:
<script type="text/javascript">
document.cookie = "cookieName=cookieValue";
</script>
<?php
$phpVar = $_COOKIE['cookieName'];
echo $phpVar;
?>
Your code
<script language="javascript" type="text/javascript">
function getCode(){
var v =document.forms["form1"]["part_code"].value;
document.cookie = "cookieName="+v;
<?php
$phpVar = $_COOKIE['cookieName'];
$query = mysql_query("SELECT COUNT(*)+1 as count FROM TB_TRANSACTION where part_code = '$phpVar'");
$i=-1;
while ($code_part = mysql_fetch_array($query))
{
$i++;
?>
var getPartCode = <? echo $code_part['count'];?>;
var x = document.forms["form1"]["part_code"].value;
var y = document.forms["form1"]["location_code"].value;
var z = document.forms["form1"]["date"].value;
var a = (getPartCode + '/'+x +'/'+ y +'/'+ z);
document.forms["form1"]["invent_code"].value = a;
<?
}
?>
</script>
Updated
Check this
function getCode(){
var v = 12;
document.cookie = "cookieName="+v;
var getPartCode = <?php echo $_COOKIE['cookieName']; ?>
alert(getPartCode);
}

Related

unable to pass variable to other page using ajax

I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>

Alternative to innerHTML for IE select box

I have a problem that is php data not showing in select box. innerhtml not working in Internet Explorer. long_description_detail_list data not showing in select box.please help me
first page:
<div id="long_description_detail_list" style="display:none;">
<option value="0">Select..</option>
<?php
include_once('Model/Language.php');
$r = new Language();
$a = $r->Select();
for($i = 0; $i < count($a); $i++)
{
print '<option value="'.$a[$i][0].'">'.$a[$i][1].'</option>';
}
?>
</div>
<script language="javascript" type="text/javascript">
//Browser Support Code
function create_long_description_detail_div(){
if(count_table_long_description_detail() >=3) {
alert("You can not add more than 3 long_description Details");
}
else {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var blank_long_description_detail = ajaxRequest.responseText;
document.getElementById('long_description_detail_counter').value ++;
$('#my-all-long_description_details-here').append(blank_long_description_detail);
set_new_height_of_step_2('inc');
var long_description_list_counter = document.getElementById('long_description_detail_counter').value;
var long_description_detail_list = document.getElementById('long_description_detail_list').innerHTML;
document.getElementById('llanguage[' + long_description_list_counter + ']').innerHTML = long_description_detail_list;
}
}
var long_description_detail_counter = document.getElementById('long_description_detail_counter').value;
var queryString = "?long_description_detail_counter=" + long_description_detail_counter;
ajaxRequest.open("GET", "Views/User/long_description/add_long_descriptions_detail.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
data not showing here in second page named add_long_descriptions_detail.php:
<select id="llanguage[<?php echo $counter; ?>]" name="llanguage[<?php echo $counter; ?>]" class="txtBox">
<option value="0">Select..</option>
</select>
IE doesn’t support updating the elements of a <select> with innerHTML, but what you can do is use the DOM, which is always the right way to go about things anyways.
Make your server-side script return a JSON array of options; it’ll make everything a lot easier.
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState === 4) {
// Parse the response
var options = eval('(' + ajaxRequest.responseText + ')');
// Get the box; I have no clue what this is
var box = document.getElementById('llanguage[' + long_description_list_counter + ']');
// Clear any current elements
while(box.childNodes.length > 0) {
box.removeChild(box.firstChild);
}
// Add new ones
for(var i = 0; i < options.length; i++) {
var newOption = document.createElement('option');
newOption.value = options[i].value;
newOption.appendChild(document.createTextNode(options[i].text));
}
}
};
(This is a little trimmed-down from your original code, but I’m sure you can fit it in.)
It’s also probably a good idea to use an old-IE-compatible JSON parser instead of eval.
The JSON should look like this:
[
{ "text": "Some text", "value": "some-value" }
]
You can use json_encode to produce it conveniently from a PHP array.

Update several elements via Ajax from PHP array result

I am trying to generate some invoices based on user's input (date selection). That is something like this:
The invoice.php file would let the user select a date from a form, and based on that selection the contents of the invoice (like amount, customer, etc.) on that same page would be updated through Ajax.
The ajaxInvoice.php would generate a MySQL query and in the end create an array with the corresponding table row based on date selection and merchant (unique row).
invoice.php
...
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var date = document.getElementById('date').value;
var merchant = document.getElementById('merchant').value;
var queryString = "?date=" + date + "&merchant=" + merchant;
ajaxRequest.open("GET", "ajaxInvoice.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
...
<form name="invoiceDate">
<input type="hidden" id="merchant" value="<?php echo $merchant; ?>" />
Date: <select id="date">
<option>2013-07-23</option>
<option>2013-07-25</option>
</select>
<input type="button" onclick="ajaxFunction()" value="Select Date" />
</form>
...
<div id="field_1">FIELD 1</div>
...
<div id="field_2">FIELD 2</div>
...
<div id="field_3">FIELD 3</div>
...
ajaxInvoice.php
include_once('includes/db.php');
$merchant = $_GET['merchant'];
$date = $_GET['date'];
$merchant = mysql_real_escape_string($merchant);
$date = mysql_real_escape_string($date);
$query = "SELECT * FROM settlements WHERE datePayment = '$date' AND merchant = '$merchant'";
$result = mysql_query($query) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
I was wondering if I could have access to that array this way:
echo $array[0]['fieldName'];
and update selected elements on the page based on different row fields. Not sure if getElementById or getElementByName should be used.
My question would be how to actually access the php array within the script part and also within the rest of the page, so that I can update the various div elements with the corresponding data obtained from the DB query after the user selects the date from the form.
In fact, if only one div has to be updated, the code works just fine, but I don't know how to extend the logic to update more than one div.
Any help or hints on the syntax or code logic would be greatly appreciated.
Thank you very much in advance!
I usually use JSON:
PHP at the server: echo json_encode($array)
JavaScript on the client: var response = JSON.parse(ajaxRequest.responseText)
Implemented:
invoice.php
...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = JSON.parse(ajaxRequest.responseText);
// Now you can use:
response[0]['fieldName'];
// Like this
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = response[0]['field_1'];
}
}
...
ajaxInvoice.php
...
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
// Encode to JSON
echo json_encode($array);

sending js variables to php page - not working

This is what my javascript looks like:
print "<script>function newpage(){
xmlhttp=new XMLHttpRequest();
var PageToSendTo = 'select_db.php?';
var MyVariable = 'variableData';
var VariablePlaceholder = 'variableName=';
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable + '&tweet_id='" . $id_num;
print "xmlhttp.open('GET', UrlToSend);
xmlhttp.send();
}</script>";
(it is in a php file hence the print statement)
This is what my form submission looks like: (again in a php statement)
print "<form action=\"select_db.php\" onSubmit=\"return newpage()\">";
The function newpage is not working.. I expected the variables to be sent over in the URL but the resulting URL is just select_db.php?
help, please.
You are missing the initial <script> tag...
print "<script>function newpage(){
xmlhttp=new XMLHttpRequest();
var PageToSendTo = 'select_db.php?';
var MyVariable = 'variableData';
var VariablePlaceholder = 'variableName=';
var UrlToSend = PageToSendTo + VariablePlaceholder + VariablePlaceholder + '$tweet_id='" . $id_num;
print "xmlhttp.open('GET', UrlToSend);
xmlhttp.send();
}</script>";
does that solve your problem ?
try this onSubmit=\"newpage(); return false; \"

Sending Checkbox Values to PHP page using javascript Ajax and not jQuery

I have a situation in which i need to do insert queries for every check box selected through an ajax request sent to a php script which would do the insert in mysql.
i know how to do it without an ajax call via the simple form submission with a variable like groups[] as an array and running the foreach loop in php for every value in the array.
How do i send the array a via post ajax request?
a sample code:
<input type='checkbox' name='groups[]' value='1'>Group A
<input type='checkbox' name='groups[]' value='2'>Group B
<input type='checkbox' name='groups[]' value='3'>Group C
Please help, i know this might be easy but i am just not getting it. and guys, please don't give any example of jquery or the likes as i want pure html, javascript and php solution.
Thanks community...
Here's the Javascript function:
<script type='text/javascript'>
function addResp(tid){
a = encodeURIComponent(document.getElementById('course_add_resp').value);
b = encodeURIComponent(document.getElementById('term_add_resp').value);
c = encodeURIComponent(document.getElementById('paper_add_resp').value);
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&grp="+data;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.removeChild(document.getElementById('respBackground'));
document.body.removeChild(document.getElementById('respBox'));
contents = xmlhttp.responseText;
if(contents == "done"){
window.location = "teachers.php";
} else{
document.getElementById("studentBox").innerHTML = "There was a problem serving the request.";
}
}
}
xmlhttp.open("POST","assignresp.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
</script>
and the php script:
<?php
$tid = mysql_real_escape_string($_POST['tid']);
$cid = mysql_real_escape_string($_POST['course']);
$sem = mysql_real_escape_string($_POST['sem']);
$paper = mysql_real_escape_string($_POST['paper']);
$session = 12;
$type = 1;
$groups = $_POST['grp'];
foreach ($groups as $value ) {
$q1 = "insert into iars(sessionid,teacherid,courseid,semester,paperid,groupid,type) values('$session','$tid','$cid','$sem','$paper','$value','$type')";
$r1 = mysql_query($q1) or die(mysql_error());
if(mysql_affected_rows() > 0){
echo "done";
}
else{
echo "fail";
}
}
?>
var elements = document.getElementsByName('groups[]');
var data = [];
for (var i = 0; i < elements.length; i++){
if (elements[i].checked){
data.push('groups[]='+elements[i].value);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data.join('&'));
//for get
//xmlhttp.open("GET",url+"?"+data.join('&'),true);
//xmlhttp.send();
EDIT
Change these two lines.
params = "tid="+tid+"&course="+a+"&sem="+b+"&paper="+c+"&"+data.join('&');
$groups = $_POST['groups'];
you can do this with two way,
you can use the post type ajax call
You can get the all selected checkbox values with JavaScript make comma separated string and just pass it in one variable
that's all you can do .... :)

Categories