I'm currently learning AJAX and I've run into this error in which results from MySQL query is not being displayed.
The following snippet is of the javascript :
<script type="text/javascript">
function showCustomers()
{
var zip = document.getElementById('zipcode').value;
var st = document.getElementById('stname').value;
if ((zip=="")&&(st=="")){
document.getElementById("showCustResults").innerHTML="";
return;
}
mlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("showCustResults").innerHTML=xmlhttp.responseText;
}
}
var querystring = "?zip" + zip + "&st" + st ;
xmlhttp.open("POST","findCustomers.php" + querystring, true);
xmlhttp.send();
}
The following is the form in which the information is being pulled from :
<form id="search_customers" class="appnitro" method="post" action="">
<ul>
<li id="li_2" >
<label class="description" for="zipcode">Zip Code </label>
<div><input id="zipcode" name="zip_code" class="element text small" type="text" maxlength="10" value=""/> </div>
<p class="guidelines" id="guide_2"><small>Please enter a Zip Code</small></p>
</li>
<li id="li_1" >
<label class="description" for="stname">Street Name </label>
<div><input id="stname" name="st_name" class="element text medium" type="text" maxlength="50" value=""/></div>
<p class="guidelines" id="guide_1"><small>Please Enter the Street Name</small></p>
</li>
<li class="buttons">
<input id="findCust" class="button_text" onclick="showCustomers()" type="submit" name="find"/>
</li>
</ul>
</form>
<div id="showCustResults"><!-- Eventually search results will appear here --></div>
And the PHP that is pulling the cod is the following:
<?php
include 'functions.php'; #Library that holds all the functions
#Sanitizing strings for SQL entry
$zip = mysqli_real_escape_string($db, $_POST['zip']);
$st = mysqli_real_escape_string($db, $_POST['st']);
$db = db_connect(); #Connecting to the database
#Querying the database to find any matches
#ALSO: We might need to add another column to
$sql = "SELECT CustomerName, ServiceAddress, BillingAddress FROM enrollment_users WHERE UserName = '$username' AND Password = '$password'";
$res = mysqli_query($db, $sql);
#Creating the table to shoot out the information
#First the header...
echo "<table border='1'>";
echo " <tr>";
echo " <th>Customer</th>";
echo " <th>Address 1</th>";
echo " <th>Address 2</th>";
echo " <th>Status</th>";
echo " </tr>";
#Now the actualy information
while($row = mysqli_fetch_assoc($res)){
echo " <tr>";
echo " <td>" . $row['CustomerName'] . "</td>";
echo " <td>" . $row['ServiceAddress'] . "</td>";
echo " <td>" . $row['BillingAddress'] . "</td>";
echo " <td></td>";
}
echo"</table>";
db_close($db); #Closing the database
?>
I've been trying to figure this out for the past day with no avail. Hopefully someone can see what I cannot.
Thanks ahead.
To send post data you have to put it in the send method not the url, they have to be in key=value pairs and you should also encode them with encodeURIComponent, also you have to set the content type to application/x-www-form-urlencoded
var querystring = "zip=" + encodeURIComponent(zip) + "&st=" + encodeURIComponent(phone) ;
xmlhttp.open("POST","findCustomers.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(querystring);
mlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
I did not attempt to run your code but at first glance it looks like you have a typo declaring your xmlhttp variable.
var querystring = "?zip" + zip + "&st" + phone ;
I also see that it would seem your query string is incorrect. AJAX stands for asynchronous javascript and xml (now most commonly replaced with JSON)
you should format your query string with a : between the key and value pairs.
http://www.json.org/
I cannot be sure that these will fix your issue as I have not tried the code but I will give a couple of pointers.
If this is in fact the problem, that would tell me a couple of things.
1. you do not use your browsers developer tools because if you did you would see that an httprequest is never fired if that variable is incorrect.
2. you are developing in a text editor and not an IDE. (this is preferential I am only saying this as an observation not a recommendation necessarily)
I do not know what the purpose of this work is but im assuming you are not allowed to use jquery because the $.ajax method will allow you to clean this code up quite a bit and accomplish what you want in many fewer lines.
Related
I am new to php and mysql so it may be that I am missing something obvious but here goes:
I am setting up a database to store items with stock. Each item is assigned an amount of stock (e.g. 5). Each item is displayed on my webpage with buttons next to it to manually add or remove stock from the database:
$query = "SELECT * FROM classes";
// This uses a mysql function that act upon our $query variable above
$result = mysql_query($query);
// This is a loop that says "while there is data to display...keep looping round and displaying that data".
while($class_data = mysql_fetch_array($result)) {
// Now we are going to echo that data
echo
"<div class=\"classmanagertablecontent\">" . $class_data['name'] . "</div>
<div class=\"classmanagertablecontent\">" . $date['date'] . "</div>
<div class=\"classmanagertablecontent\">" . $class_data['stock'] . "</div>
<div class=\"classmanagertablecontent\">" . $class_data['button_paypal'] . "</div>";
<form action="../url.php" method="post">
<input type="hidden" name="button_paypal_fromform" value="<?php echo $class_data['button_paypal'] ?>">
<input type="submit" value="remove stock" name="remove stock">
</form>
<form action="../url.php" method="post">
<input type="hidden" name="button_paypal_fromform" value="<?php echo $class_data['button_paypal'] ?>">
<input type="submit" value="add to stock" name="add to stock" >
</form>
</div>
}
The code in the url that the "add to stock" button posts to is as follows:
<?php
$button_paypal = $_POST['button_paypal_fromform'];
mysql_query("UPDATE classes SET stock = stock+1 WHERE button_paypal = ". $button_paypal ."");
?>
For whatever reason WHERE button_paypal = "a number" it works...
...but if button_paypal = "a string" it does nothing.
I cannot get my head around this. The paypal hosted buttons I will be using are made up of letter and numbers so it need to work with a combination of the two.
I have tried...
echo "$button_paypal";
...on my url.php page and the button reads fine (e.g. SD76S9SFGV)
in my database "button_paypal" is a TEXT field but i have also tried VARCHAR. STOCK is an INT.
If anyone can help then I will be very grateful. Thanks. #hopethismakessense
All you need to do is wrap your string value in single quotes:
<?php
mysql_query( "UPDATE classes SET stock = stock+1
WHERE button_paypal = '{$_POST['button_paypal_fromform']}' ");
I wrapped the array variable in {} brackets, so you can include directly within your double-quoted query (no need to concatenate like " . $var . ", and also no need to create a second variable when you can reference this directly)
I want to change the value of an html text box using javascript. i tried the .value but it doesn't work. then i change the id with no underscore id and change the value and changed the id back to original one value is same as original value no change.
<input id="_item1govt_id" class=" required-entry input-text required-entry input-text required-entry" type="text" value="1" name="address[1][govt_id]" style="display: none;">
echo "<script> function setFunc".$rs['entity_id']."(obj)
{
var e = document.getElementById('_item".$rs['entity_id']."govt_id');
e.id = 'ape".$rs['entity_id']."';
e.value = obj.value;
alert(e.value);
e.id = '_item".$rs['entity_id']."govt_id';
}
</script> "
You can do it using document.getElementById("ID").value = "new value";
It will work even if your id contains _ or number.
Please check if your id in html amd id you used in javascript matches.
If you want to change the html of your text box, then it can be done as follow by using javascript
document.getElementById('textbox_id').innerHTML="New text";
For more info, juct check the basic here.
I think it will help you.
Running your code like below worked fine, have you actually called the function anywhere?
<input id="_item2govt_id" class=" required-entry input-text required-entry input-text required-entry" type="text" value="1" name="address[1][govt_id]" style="display: none;">
<?php
$rs = array('entity_id' => 2);
echo "<script> function setFunc" . $rs['entity_id'] . "(obj)
{
var e = document.getElementById('_item" . $rs['entity_id'] . "govt_id');
e.id = 'ape" . $rs['entity_id'] . "';
e.value = obj.value;
alert(e.value);
e.id = '_item" . $rs['entity_id'] . "govt_id';
}
setFunc" . $rs['entity_id'] . "({value:\"test\"});
</script>";
Note at the bottom I call the setFunc2() method.
Edit
See here for php fiddle working example: http://phpfiddle.org/main/code/7em-jwq
$("#yourTextBoxIdName").val('newValue');
What I am trying to do is use php to pull a variable number of records from a database. I want to let the user to be able to click on the text and it will switch the text out for an input box and will update the database on submit.
I am aware of how to do this with the onclick attribute, and passing the javascript function the id number that corresponds to the row in the mySQL database. I am trying to determine how I could do this using Unobstrusive Javascript techniques.
Here is the portion of the code that creates the divs, when the user clicks on the zone, account_number, dv or address fields it will switch out the text for the input box as I said above.
while($row = mysql_fetch_array($query)) {
$business_name = $row['business_name'];
$resource_id = $row['resource_id'];
$totaldv += $row['dv'];
if(!in_array($row['zone'], $zoneArray)) {
$zones .= $row['zone'] . " ";
array_push($zoneArray, $row['zone']);
}
$account_numbers .= "
<div>". $row['zone'] . "</div>
<div>" . $row['account_number'] . "</div>
<div>" . number_format($row['dv']) . " kW</div>
<div>" . $row['street_address'] . " " . $row['city'] . ", " . $row['state'] . "</div>
";
}
The problem I am encountering lies in that a customer could have 1 account, or 83 accounts and I need to be able to switch out the correct text for an input box and pass the id of the row from the database to the form. I was thinking of maybe using applying a class to the certain fields?
I have done something like this before, but it was always a static # of inputs, so I was able to hide the text and show the input box which was generated when the page was loaded. Something along the lines of this (granted it was not Unobtrusive)
$content .= "
<tr>
<td width=35><IMG SRC=images/$i.png height=20></td>
<td width=35 id=rank".$i.">$rankImages</td>
<td width=380>
<span id=text".$i." style=\"cursor:pointer;\" onclick=\"editItem($i);\">".$itemArray[$i]."</span>
<span id=$i"."input>
<input id=$i type=text value=".$itemArray[$i].">
<IMG SRC=images/save.png style=\"cursor:pointer;\" onclick=\"saveItem($i);\">
<IMG SRC=images/cancel.png style=\"cursor:pointer;\" onclick=\"cancelEdit($i);\">
</span>
</td>
</tr>";
function editItem(line_num) {
$("#text" + line_num).hide();
$("#" + line_num + "input").show();
}
The way I would go about it would be to use data-* attributes and then access that data using jQuery's .data() function. A shorter, but similar-looking, example of how your HTML might look:
<div class="editable-row" data-row-id="1">
<span class="uneditable">row one</span>
<input type="text" value="row one" />
</div>
<div class="editable-row" data-row-id="2">
<span class="uneditable">row two</span>
<input type="text" value="row two" />
</div>
<div class="editable-row" data-row-id="3">
<span class="uneditable">row three</span>
<input type="text" value="row three" />
</div>
<div class="editable-row" data-row-id="4">
<span class="uneditable">row four</span>
<input type="text" value="row four" />
</div>
And your JavaScript would look like this:
$(document).ready(function () {
$(".editable-row").on("click", function () {
var $this = $(this),
rowId = parseInt($this.data("rowId"), 10);
$this.find("input").show();
$this.find(".uneditable").hide();
// do something with rowId
});
});
i am capturing the value of changed fields via JS Event and capturing that data into temp1 array, say, if u change field name "name", then it will get the field name "id" and will store it into temp1. but the main problem is how can i pass this array to a php form processing page, where i can get the value of this temp1.
i tried using JSON but it's not helping me out.
the code which i tried was: $.post('/somepage.php', temp1); but it didnt work.
please help me out with this.
and i included jquery.js lib in the page.
<script type="text/javascript">
var temp1 = new Array();
function onChangeTest(changeVal)
{
//alert("Field u changed was: " + changeVal.id)
temp1.push(changeVal.id);
tmsg = "Fields u changed so far are:"
for(var i=0;i<temp1.length;i++)
{
//document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>");
tmsg = tmsg + " " + temp1[i];
}
alert(tmsg);
}
//$.post('/somepage.php', temp1);
</script>
The problem looks quite simple to me , try below code and let me know the outcome..
function onChangeTest(changeVal)
{
//alert("Field u changed was: " + changeVal.id)
var temp1 = new Array();
temp1.push(changeVal);
tmsg = "Fields u changed so far are:"
for(var i=0;i<temp1.length;i++){
//document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>");
//tmsg = tmsg + " " + temp1[i];
var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'outArray[]';
newHidInp.value = temp1[i];
document.frm.appendChild(newHidInp);
}
return false;
}
HTML:
<form name="frm" action="" method="POST" >
<tr>
<td><font color="red">*</font>Name:<input type="text" name="name" id="name" size="25" onkeyup="onChangeTest('name')" /></td>
<td><font color="red">*</font>Age<input type="text" name="age" id="age" size="25" onkeyup="onChangeTest('age')" />
<input type="submit" name="submit" value="SUBMIT">
</td>
</form>
</body>
</html>
PHP:
<?php
print("<pre>");
print_r(array_unique($_POST['outArray']));
?>
What you need is:
$.post("/somepage.php", { 'temp1[]': temp1 });
See here in the official documentation as well, there are examples with all kinds of data.
Change the way you store the changes. If you store the Field IDs as Object Keys (e.g. temp1["username"] = true) you can easily use $.post("/somepage.php", temp1) and read the values via $_POST["username"] etc. in PHP.
i have been working on this code !
and i couldn't done it right .
what i want is the text box to be enabled when the corresponding checkbox is checked .
but when apply the function nothing happens :(
in my code the text and check boxes are dynamically generated from database using php .
here is my code :
<div><div class="ac-container">
<div id="accordion">
<?php
$qry="SELECT * FROM catalog";
$result= mysql_query($qry);
if($result){
while($info = mysql_fetch_array($result))
{
print "<h3> cat:".$info['name']."</h3><div>";
$qryitem="SELECT * FROM item WHERE Id=". $info['Cid'];
$resultitem=mysql_query($qryitem);
if($resultitem){
?>
<form name="form1" id="form" method="post" action="manage_item_action.php" >
<?php
while($info=mysql_fetch_array($resultitem))
{
?>
<input type="checkbox" id="checkB" name="op[]" value="<?php echo $info['Id'];?>" /> <?php echo $info['name'];?>
<label> Quantity <input disabled="disabled" id="textB" type="text"
name="Quantit[]" value="<?php echo $info['Quantity'];?>"/>
</label>
<script>
checkBoxes=document.form1.elements['op[]'];
textBoxes=document.form1.elements['Quantit[]'];
for(var i=0 ; i<checkBoxes.length;i++){
checkBoxes[i].onchange = function() {
textBoxes[i].disabled =!(this.checked);};
}
</script>
<br/>
<?php
}
}
else echo "There are no items.";
print "</div>";
}
}
?>
</div>
<input type="submit" value="update" name="submit"/>
<input type=reset value="clear"></td></tr> </form>
The problem you are having is that inside your event handler the variable i is not defined. To overcome this problem, you could add a property to each checkbox to save what index they are referring to:
checkBoxes=document.form1.elements['op[]'];
textBoxes=document.form1.elements['Quantit[]'];
for(var i=0 ; i<checkBoxes.length;i++)
{
checkBoxes[i].myIndex = i;
checkBoxes[i].onchange = function() {
textBoxes[this.myIndex].disabled =!(this.checked);
};
}
Other methods to solve this problem: http://www.howtocreate.co.uk/referencedvariables.html
Your code is still pretty messed up. For instance you are generating too many closing <div/>-tags with your first print-statement. I would suggest you just remove the PHP-code from your question, as the question is only related to html and javascript.
I would also suggest to use a library for manipulating DOM elements like jQuery.
When writing and debugging javascript, you should always make sure that you get error messages. "nothing happens" is a sign that you are just ignoring errors. For Firefox download the addon Firebug. Safari also has developer tools that you can activate in the settings. Using these tools will make it very easy to spot and solve problems like this.