how to send 2 values on javascript keyUp event - php

I want to use javascript to compute values without pressing on the submit button. Using the javascript onkeyup event.
Is it possible to send 2 or more values from an html form to a javascript function?
This is the code for the loading of the necessary details on a table:
echo "<input type=\"hidden\" name=\"ids[]\" value=\"$id\">";
echo "<input type=\"hidden\" name=\"qoh[]\" value=\"$qtyhand\">";
echo "<td><input type=\"text\" name=\"qbuys[]\" id=\"qbuys\" value=\"$qtytbuy\" onKeyUp=\"proc(this.value)\"></td>";
I tried (which I only made up), but didn't work, what's the proper way of doing this,is it possible?:
onKeyUp=\"proc(this.value && document.cartform.qbuys[].value);\"
And this is the javascript that acts as a mediator between the form and the php file that computes the subtotal:
function proc(str,str2)
{
if (str=="")
{
document.getElementById("compz").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("compz").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","compz.php?qbuys="+str&prodid="+str2,true);
xmlhttp.send();
}
Although I'm not really sure if it works, since I'm only using 1 parameter for the function before.

First of all, I would recommend using jQuery instead of rolling your own AJAX interface. It's tried and tested and used by the giants of the Internet. Here's a simple example from the jQuery documentation adapted to your structure:
$('#compz').load('some_page.php');
That line would load any content returned by "some_page.php" into your "compz" DIV. So let's re-write your function:
proc = function(str1) {
var str2 = $('#FormVariableThatContainsProdID').value;
$('#compz').load('compz.php?qbuys=' + str1 + '&prodid=' + str2);
}
That way your PHP remains unchanged.

Comma seperates function parameters.
onKeyUp=\"proc(this.value, document.cartform.qbuys[].value);\"

Related

Passing Unique ID to AJAX Script

I'm working on my first AJAX script with some PHP pages - it's my first time with AJAX and I've finally got the script to work. I'm also a bit of a Javascript newbie too.
I have a PHP website that allows users to search a library catalog and then select/add books to a shopping cart. We've now changed the "Select" link to load via AJAX so the search results page doesn't refresh.
To finish the AJAX changes I now need to pass a unique ID for each of the table cells that has the AJAX link to the script. I'm using PHP to generate a unique ID for each table cell by using the $bookID variable as follows:
<td class="hidden-narrow" id="<?php echo 'selectRecord'.$bookID; ?>">
<?php
if (in_array($bookID, $_SESSION['selectedBooks'])) {
echo "Selected";
} else {
echo 'Select';
}
?>
</td>
I now need to update my script to work with the unique ID's - to get it working I hardcoded it to an ID named "selectRecord" using an example script that I found. Here's my script:
function selectRecord(id) {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("selectRecord").innerHTML="Selected";
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
xmlhttp.send("id="+id);
return false; // Do not follow hyperlink
I gather I need to change this line:
document.getElementById("selectRecord").innerHTML="Selected";
but not sure of the syntax to handle unique ID's for each table row cell.
You can pass the id to the getElementById function:
document.getElementById("selectRecord" + id).innerHTML="Selected";
Have you tried
document.getElementById(id).innerHTML="Selected";
? id should get enclosed by the readystate function and keep its value.

Pass DOM element values to PHP using AJAX

I'm trying to use AJAX, HTML and PHP all together to provide a seamless experience to the user. I'm having trouble passing the variable to the PHP form right now. It's a little complicated the way I went about it, I'm not sure if there is an easier way as this is my first experiment with AJAX.
To explain in detail:
<div class="block" id="articles"></div>
I have this division which loads the details and loads the article. Inside of this division I'm trying to allow the user to add comments relating to the article.
function viewDets(str) {
if(str == "") {
document.getElementById("articles").innerHTML = "";
return;
}
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) {
document.getElementById("articles").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "viewDets.php?q=" + str, true);
xmlhttp.send();
}
Using this is passes the variable to viewDets which then adds another container:
while($row = mysql_fetch_array($result)) {
$count++;
$taskComments = $row['Annotation'];
$userName = $row['Username'];
$timeStamp = $row['Time'];
echo "Comments";
echo "<p class=\"meta\">$count. $taskComments ($userName) -- $timeStamp</p>";
}
echo "</div></div></div></div></div></div>
<form name=\"inputCom\" method=\"get\">
<div class=\"four column\">
<div class=\"column_content\" id=\"commentInsert\">
<label>Enter Comment</label>
<input type=\"text\" id=\"comment\"value=\"\"></input>
<input type=\"hidden\" id=\"Uname\" value=\"$user\"></input>
<input type=\"hidden\" id = \"taskID\" name=\"taskID\" value=\"$q\" />
<button type=\"button\" id = \"commentSub\" onClick=\"insertComm(comment, Uname, taskID)\" />Enter Comment</button>
</div>
</div>
</form>";
The name of this division is commentInsert and I've set up the AJAX so that on click, it should push the variables to a PHP function that inserts into my database for comments.
The issue that I'm running into is that I can't get the comment to pass to that PHP function.
function insertComm(str, uname, id) {
insertC();
if(str == "") {
document.getElementById("commentInsert").innerHTML = "";
return;
}
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) {
document.getElementById("commentInsert").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "subCom.php?q=" + str, true);
xmlhttp.send();
};
I have been playing around with this function by trying to call things like document.getElementByID and calling that function as insertC(); but with or without the insertC() function I am still having issue passing the 3 variables in the Javascript function to the PHP function, I tried it with just one variable and I still have trouble getting it to pass.
Any help would be greatly appreciated. Sorry for the long post.
I think your problem is onClick=\"insertComm(comment, Uname, taskID)\" assumes that these 3 variables are automatically set based on id. They are not.
Instead, you need to read them from the DOM, for example:
var str = document.getElementById("comment").value;
var uname = document.getElementById("Uname").value;
var id = document.getElementById("taskID").value;
If you add these to the start of insertComm, then you won't need to bother passing in the arguments.
If you want your PHP script to have access to all 3 of these, you'll need to pass in uname and id as well as str when sending your request to subCom.php. Note: it's best practice to encode these parameters using encodeURIComponent, in case the user inserts unexpected characters (like &) which may mess up your request.
... onClick=\"insertComm(comment, Uname, taskID)\" ...
When the button is clicked, comment, Uname and taskID are resolved by document because you're using inline code; although this really shouldn't be relied upon, it works like this:
comment = document.getElementById('comment');
// etc
As such, your function insertComm() is called with DOM elements instead of actual strings. To use them inside your function you would use comment.value for instance:
xmlhttp.open("GET", "subCom.php?q=" + encodeURIComponent(str.value), true);
Also note that I'm using encodeURIComponent() to prevent malformed URL's caused by spaces in the string value for example.
However, it would be considered better if you would pass the identifiers in the HTML like this:
... onClick=\"insertComm('comment', 'Uname', 'taskID')\" ...
And inside your insertComm():
var str = document.getElementById(comment).value;
xmlhttp.open("GET", "subCom.php?q=" + encodeURIComponent(str), true);

add a mysql_query into an onclick function

I want to make it so that new input boxes only appear if information in the previous box is correct, by checking it with a mysql_query can I adapt this code
function show(id){
if(document.getElementById(id+"-link").style.display=="none") {
document.getElementById(id+"-link").style.display="block";
document.getElementById(id+"-input").style.display="block";
}
}
<tr>
<td><input type="text" id="a1" name="em_1"></td>
<td>and</td>
</tr><tr>
<td><input type="text" id="b1-input" name="em_2" style="display:none"></td>
<td><a href="#null" style="display:none" id="b1-link"</a></td>
</tr><tr>
so somewhere in here I need to add :
$userCheck=mysql_query(SELECT email FROM users WHERE name = "em_1")
$row=mysql_num_rows($usercheck)
if($row!==0){"show('b1')";}
or something to that affect, without refreshing the page. Is this possible?
Ajax:
function XMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// xmlhttp.responseText -> return value from php file , so from here you can do your action
}
};
xmlhttp.open("POST","yourfile.php?email={value}",true); // from here send value to check in server side
xmlhttp.send();
}
Php:
if (isset($_POST['email'])){ // which is variable from `yourfile.php?email`
$userCheck=mysql_query("SELECT email FROM users WHERE name = 'em_1'");
$row=mysql_num_rows($usercheck);
if ($row==0){
echo "no";
} else {
echo "yes";
}
}
Pass in yourfile URL of your server side script which checks if email exists or not and return for example yes or no => Then with help of Ajax it will be return in current document
Note: Don't use mysql extension , use mysqli or PDO instead
Yes it is possible, but you need to know how to use ajax or jquery-ajax
which will help you get the data from php to javascript and then appended to html.
You need AJAX to make this work without a refresh. Check out this page on W3Schools:
http://www.w3schools.com/php/php_ajax_database.asp
It's almost exactly what you want, but instead of returning a block of text, just enliven the b1 pieces.

Form Processing Ajax

I have a very simple form.I want to insert the form data in mysql database.using ajax.
I need to pick data from form and send them as xml to the server.
the form is as :
<form>
Name:<input type="text" id=name/>
Contact<input type="text" id=contact/>
</form>
And i am picking the data from my form using js as :
function GetData(form)
{
var name=document.getelementbyid('name');
vat contact=document.getelementbyid('contact');
}
function Ajax
{
" Here i want to send the form datas as an xml to the server"
}
Can any one help me how to do this .And also how to receive the the request from server as xml and insert to database.
Just give me the proper way.Not Query string or json or jquery.I want to use xml using ajax
Thanks,
function GetData(form)
{
var name=document.getelementbyid('name');
var contact=document.getelementbyid('contact');
Ajax(name,contact);
}
function Ajax(name,contact)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response=xmlhttp.responseText;
}
}
//var datas='?name='+name+'&contact='+contact;
var xmlval='<name>'+name+'</name><contact>'+contact+'</contact>';
var datas='?xmlvalue='+xmlval;
xmlhttp.open("GET",'phpfile.php'+datas,true);
xmlhttp.send();
}
Important question: Why do you need XML to submit?
Also, to use XML, look up SimpleXML, and to save to database, there are a lot tutorials.
Update: if you meant the response as XML? That's just like the same as in JS. And to use it in JS, look at this. However, in that case, uncomment the commented line and comment the next 2.

Passing PHP variables back to JavaScript variables on original page as Ajax

I have some Ajax which passes a javascript variable to getfirstvals.php which then does its thing with the DB and echos out a table of values depending on the javascript variable I input. I now want to pass back these PHP variables which are being echoed, back to the original page that the javascript is being sent from in order to convert them into javascript variables to do calculations on. I'm not sure how to do this.
Below is how it works so far.
A range "slider" to select the values:
echo "<input id='slider' type='range'
min=\"$vartime[0]\" max=\"$timemax\" value=\"$vartime[0]\" step='any' />
<span id='range'> </span>"
......
selectslider.onchange=function changecolour(){
showValue(selectslider.value)
.....
<script type="text/javascript">
function showValue(str) {
if (str == "") {
document.getElementById("datatable").innerHTML = "";
return;
}
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) {
document.getElementById("datatable").innerHTML = xmlhttp.responseText;
}
}
if (floorchoice!=0 && floorchoice!=1){
if (floorchoice==2)
{
xmlhttp.open("GET", "getfirstvals.php?q=" + str, true);
xmlhttp.send();
......
This sends "q" to getfirstvals.php which finds values matching q in th DB and echoes out all values in the same row as it. In this way, as q changes the echoed values change. As I mentioned above, I would like these values not only to be echoed, but to be passed back to javascript variables on the original page which can then be used for calculations. Below is what I mean by the values being echoed:
echo "<td>" . $FFlrOpenPlanTemp . "&#8451</td>";
echo "<td>" . $FFlrPCRoomTemp . "&#8451</td>";
echo "<td>" . $FFlrStudyRm6Temp . "&#8451</td>";
echo "<td>" . $FFlrStudyRm8Temp . "&#8451</td>";
Take a look at JSON. PHP has a function: json_encode which will take a PHP data object (ie array, but doesn't have to be an array) and encode it in javascript object notion.
In your JS you can then evaluate (tip: do not use eval, modern browsers have json parsers) to get the JSON data into Javascript object.
Example
If I have the following array in PHP:
$array = array( "test1" => 1, "test2" => 2, 3, array( 4, 5, 6 ));
And I json_encode that array, I wind up with the following string:
{"test1":1,"test2":2,"0":3,"1":[4,5,6]}
This is what you return back to JS (aka, echo out). You can parse this via the native parsing function JSON.parse in Javascript:
var obj = JSON.parse(phpReturnStr);
Voila. You have an object in JS passed in from PHP.
First, you could use a Javascript library to make it simpler and cross-browser. Then, I'd suggest you to pass your variables from PHP to JS with json_encode(). Just take a minute to see how jQuery.getJSON works, and it will be a child's play.

Categories