How to connect php and jquery - php

Is it possible to use php to compute something and use jquery to fetch the computed
value and display it back to the webpage without the need to submit the form.
I'm really having trouble using client-side to compute something that is using arrays. So I'm thinking of letting php do the computation.
<input type="hidden" name=ids[] value="<?php $id; ?>">
<input type="hidden" name=qoh[] value="<?php $qtyhand; ?>">
<input type="hidden" name=dprice[] value="<?php $dsprice; ?>">
<input type="hidden" name=sprice[] value="<?php $ssprice; ?>">
<td>$qtyhand</td>";
<td><input type="text" name=qbuys[] value="<?php echo $ssprice; ?>"></td>
<td><?php $ssprice; ?></td>";
<td><input type="text" name=disc[] value=""></td>
<td><input type="text" name=subtot[] value=""></td>
And here is the php file that is supposed to be used for computing.
<?php
$ctbill=0;
foreach ($_GET['ids'] as $k => $v) {
$id = (int)$v;
$qtyhnd = (int)$_GET['qoh'][$k];
$qtytbuy = (int)$_GET['qbuys'][$k];
$left = $qtyhnd - $qtytbuy;
$sellprice=(double)$_GET['sprice'][$k];
$dealerprice=(double)$_GET['dprice'][$k];
$finalvalue=.01;
$dis=(double)$_GET['disc'][$k];
$stotal=(double)$qtytbuy * $sellprice;
$cdizval=(double)$stotal * $dis * $finalvalue;
$cdstotal=$stotal-$cdizval;
$ctbill=(double)$ctbill + $cdstotal;
$dizval=$dis * $finalvalue;
$preprof=(($sellprice * $qtytbuy)-($dealerprice*$qtytbuy)) * $dizval;
$profit=(($sellprice * $qtytbuy)-($dealerprice*$qtytbuy)) - $preprof;
?>
Can you give me an idea on how to do it.

The loading itself is often as simple as
$("#output").load("compute.php?ids[]=1111&ids[]=2222");
The complexity in your case is assembling the various URL parameters from the form fields. Usually you can pass a simple Javascript array/hash as data parameter. But JS arrays and the default jQuery .load handler don't work well with repetetive PHP-style var[] field names that you have.
Your best bet is to build a loop and do that manually I think. (But there might be plugins for that, so try Google and jQuery plugin repository.)

Yes. Look at the jquery manual for examples of how to make ajax requests and show their results:
http://api.jquery.com/jQuery.ajax/

Use ajax and set those values in the callback.
jQuery's ajax functions include $.get, $.post, $.load, $.ajax . You should probably pass your parameters with POST bc it seems you want to pass some arrays and GET is not well suited for that. That PHP file should echo out the stuff you need, and depending on its complexity you may want it to be JSON used JSONencode instead of just a plain string.
$.post('/url.php', {data1: 'literal', data2: variable, ....}, function($x){--display==});
url.php is the PHP file that handles it
second argument is encoming data
third argument is a callback function, with $x being whatever url.php echos
http://api.jquery.com/category/ajax/
http://www.visualjquery.com

Related

using a variable name inside another variable name

I'm sorry for my English.
I have a dynamic php form connected to mysql DB. In stock array I save the mysql query results. I can access the name of the product[0] and its available quantity [4]. I use the name of the product[0] to set input name and available quantity to fix max parameter value, as it below:
<input type="number" name="<?php echo $stock[$i][0]?>" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em>
I don't kwow how many inputs will be created (and which, because it is dynamic), so I save the name of the input created in another array $_SESSION["INPUTS"] as show:
array_push($_SESSION["inputs"],$stock[$i][0]);
In the next page, I want to $REQUEST the value from the inputs. Now I have the problem, I need to call $REQUEST for the created inputs which names are saved inside $_SESSION["inputs"], I need something as:` $REQUEST["$_SESSION["inputs"]]. I try it different ways without exit.
Any idea? Any alternative?
thanks
I think the best approach is by naming the input name attribute like an array: eg: "name=stock[the product name]". This approach allows you to discard the usage of the $_SESSION["inputs"].
<input type="number" name="stock[<?php echo $stock[$i][0];?>]" min="0" max="<?php echo $stock[$i][4]; ?>" value="0" style="width:4em">
Then to read the values:
$stocks = $_REQUEST['stock'];
foreach($stocks as $productName => $quantity) {
//...
}
This works because the inputs are converted to a php array after being submitted.
You can even get the number of inputs by calling count:
echo count($_REQUEST['stock']);

PHP multiply Two fields

I am trying to multiply to fields together to obtain a total in PHP form.
<label for="190_mnth2"></label>
<div align="center">
<input name="190_mnth" type="text" id="190_mnth2" value="10" size="5" />
</div></td>
<td><div align="center">
<label for="190_rate"></label>
<input name="190_rate" type="text" id="190_rate" value="190.00" size="10" />
</div></td>
<td><div align="center">
<input name="total_190" type="text" id="total_190" value=<? echo '190_mnth2' * '190_rate' ?> size="10" />
The above is my current code but the answer is totally wrong it gives me 36100 What is wrong with my formula if anyone can assist?
First of all you cannot calculate the total like that, it's not Javascript, you need a form with a get/post request which will send a request to the server, server will process and throw the calculated value back to the user.. so wrap the fields around forms, set your method to post(preferred) and than you can write your PHP code like
<?php
if(isset($_POST['submit_button_name'])) { //Use $_GET if it's a GET request
//Save the values in variable
$mnth_190 = $_POST['190_mnth'];
$rate_190 = $_POST['190_rate'];
//Calculate here
$total = $mnth_190 * $rate_190;
/* Now you can use $total either to echo straight in your page,
or inside another input field */
}
?>
Also make sure you validate the data before the form is posted and is calculated, check whether the user input doesn't have string or any other special character.
The purpose of PHP is to generate HTML to display, not to update the HTML of the current page. You can create a POST request that submits your data for display on another page. If you want to dynamically update the total on the current page, you should use Javascript or another front end language.
<? echo '190_mnth2' * '190_rate' ?>
You're attempting to multiply two strings, which will probably be converted by PHP as 190 * 190.
In order to get this to work, you're going to have to do it in two separate steps (with PHP anyway). Because PHP is a server side language, you'll have to $_POST[''], or submit these two values as part of the query string and use $_GET[''] to calculate.
If you don't want to do it this way, then I'd suggest looking at some JavaScript to handle it instead.
I'm going to take a shot at doing something like this, as an example.
$190_mnth2 = 10;
$190_rate = 190;
$total = $190_mnth2 * $190_rate;
then using: value=<? echo '$total'; ?>

autofill this html field?

what would be the easiset way to autofill this field??
<input type="text" name="start_price" value="<?=$item_details['start_price'];?>" size="8"></td>
i need to keep the $item_details because it gets passed to some other code, but in some cases i want to autofill this as 0.00 to make it easier for me as i will be using 0.00 to list some auctions
i am editing a template that is being used by php to generate some code, so ideally i just want to make some changes to the templates without having to dive into the code itself
Something like this sounds like it might solve your problem:
<?php
// Whatever logic determines a "special case" stores a boolean value
// into the variable $special_case
$input_value = !$special_case ? $item_details['start_price'] : '0.00';
?>
<input type="text" name="start_price" value="<?php echo $input_value; ?>" size="8">

Echoing out variables in a function

I am trying to returning a string like this.
$col="<td><input ".$name." type='".$field['1']."' ".$id." ".$class." value='".eval( '?> '.$row[$field["2"]] .'<?php ')."'".$size." ".$maxlength." ".$disabled." ".$readonly." /></td>";
I need
value='".eval( '?>'.$row[$field["2"]] .'<?php ')."'
to be evaluated after the string is returned into the page so i can use my sql call
$row = $core->getRowById("email_users", $user->userid,"userid");
I include the row here.
<input type="text" readonly="readonly" disabled="disabled" size="55" value="<?= $row['username'];?>" class="inputbox" name="username">
It would then evaluate this
$row['username'];
How can I go about doing this? Do I use eval?
If I get your point:
You can't do that, PHP doesn't work in a multipass way. Your eval would be a plain string in output. You have to use either POST or GET back to this page, check whether $_POST or $_GET exists, and act accordingly.

Javascript mysql interface?

I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed

Categories