How can I merge 2 search forms together? - php

I am doing my website on Wordpress.
I have 2 search forms that appear separate on my website and I was wondering how could I merge them into one.
The first search form searches for products First search form
The second one searches for the location of the products Second search form
Sorry for asking this silly question and thank you for your help :D

Javascript is what you need to start learning. It is the essential other half of webpage design. With Javascript you can get the value from anything on the page. Here's the basic code for pulling the values from the inputs of two different forms and posting them to your PHP file.
<!--first form-->
<form>
<input type="text" id="product" name="product">
</form>
<!--second form-->
<form>
<input type="text" id="city" name="city">
</form>
<button onclick="continuePost()">Submit Both</button>
<div id="result"></div>
<script>
function continuePost() {
var product = encodeURIComponent(document.getElementById("product").value);
var city = encodeURIComponent(document.getElementById("city").value);
var params = "product="+product+"&city="+city;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myResponse = JSON.parse(this.responseText); //send a JSON response back from your PHP file
if(myResponse.hasOwnProperty('error')){
document.getElementById("result").innerHTML = myResponse.error;
}else{
var result1 = myResponse.myResult1;
var result2 = myResponse.myResult2[0]; //or whatever key and value pairs that you used in the JSON response that you sent back from you PHP file
document.getElementById("result").innerHTML = result1;
}
}else{
window.setTimeout(failed(), 3000);
}
};
xhttp.open("POST", "yourPHPfile.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
function failed(){
document.getElementById("result").innerHTML = 'Failed to connect to server.';
}
</script>
yourPHPfile.php
<?php
$obj = new stdClass();
$obj->dateread = date("D M j G:i:s T Y");
if(!isset($_POST["product"])){
$obj->error = 'No product.';
echo json_encode($obj);
exit;
}else {
$product=$_POST["product"];
}
if(!isset($_POST["city"])){
$obj->error = 'No city.';
echo json_encode($obj);
exit;
}else {
$city=$_POST["city"];
}
$obj->myResult1 = 'Info you want back from your PHP file.';
$obj->myResult2 = ['array', 'of', 'info', 'you', 'want'];
echo json_encode($obj);
?>

Related

php upload progress not working, $_SESSION[$key] is empty

I am trying to create a progress bar for multiple file i upload to a server!!! I am able to upload the files but when i try to fetch the upload progress information the session array is empty. Please do help!!! Please find below the information:
Firstly my main php page where i upload the files:
********************************************Main.php********************************
<?php session_start();?>//top of the page
<div id = "centerMain" align="center">
<iframe name="targetIframe" src="" style="width:50%;height:30%;position:relative;"></iframe>
<div id="addNewBlock" class="emboss blockPart" style="z-index:50000;padding:2%;position:relative;width:50%;left:25%;top:35%;border:1px solid black;">
<form method="POST" action="handleItemAddition.php" target="targetIframe" enctype = "multipart/form-data" onSubmit="return checkAndStartUpload()">
<!--VERY IMPORTANT:the hidden element should come first before any element within the form--> <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" id="hidUpProg" value="upFilesInfo" />
<script type ="text/javascript">
var upProgName = "<?php echo ini_get("session.upload_progress.name"); ?>";
//alert(document.getElementById("hidUpProg").value);
</script>
<div class="stayLeft">Upload Photo:</div><input style="width:40%;" type="file" name = "itemImage[]" id="fileUp" class = "stayRight" multiple/><br/><br/>
<input type="button" id = "closeBut" style="width:20%;" value = "close" onclick="closeBlock()" class="utsaaBut stayLeft"/>
<input type="submit" id = "AddBut" style="width:20%;" value = "Done" class="utsaaBut stayRight"/>
</form>
</div>
</div>
********************************************Main.php********************************
find below the javscript function which gets called onSubmit = "checkAndStartUpload()" from above
******************************************Javascript function****************************
function checkAndStartUpload()
{
var tmp = document.getElementById("fileUp");
if(tmp.files.length == 0)
{
alert("No file selected. Kindly select a file");
return false
}
$progressPtr = setInterval(handleProgress,50);
return true;
}
var it = 0;
function handleProgress()
{
//alert("handleProgress");
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
//alert("response");
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//alert("value:"+xmlhttp.responseText["content_length"]);
var res = xmlhttp.responseText;
alert("Response:"+res);
it++;
if(it == 25)
{
it = 0;
clearInterval($progressPtr);
}
}
}
xmlhttp.open("POST","handleProgressValue.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(upProgName+"=upFilesInfo");
}
******************************************Javascript function*******************
Next is the file which returns session value through ajax
******************************************ajax progress return*******************
<?php
$key = ini_get("session.upload_progress.prefix") .$_POST[ini_get("session.upload_progress.name")];
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo "Current".$current."$total".$total;
//echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo "100"; //IT ALWAYS RETURNS 100 MEANING$_SESSION[$key] IS ALWAYS EMPTY
}
/*session_start();
$key = ini_get("session.upload_progress.prefix").$_POST[ini_get("session.upload_progress.name")];
//var_dump($_SESSION[$key]);
$tmp = $_SESSION[$key];
echo $tmp["bytes_processed"];*/
?>
******************************************ajax progress return*******************
And finally handleItemAddition.php successfully uploads the images.
I also disabled ;session.upload_progress.cleanup = On just for testing purpose so that if upload gets completed fast it should not clear the values.
Still i am getting empty array .
Hey guys sorry i forgot to update. I fixed the issue sometime back.
I had put session_start(); on top of all files but in handleProgressValue.php i had commented it while changing the code once i uncommented it worked.
However when i am uploading 28 files say, why does
count($_SESSION[$key]["files"])
return increasing values??? It first returned 10 then 17,24,28 and then $_SESSION got unset

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

Retrieve HTML drop down list value with AJAX

I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<script type="text/javascript">
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];

Is there a way to send html id attribute to a function?

My code is below.I want to send id=content to the function mr. And then write result to the passed id=result.Although it is only for this html file,I want to make this function available for another html pages, and want to add this function in another util.js file.
Add Item:
<input type="text" name="name" id="content">
<br>
<button onclick="javascript:mr('POST',content,result,'post.php');"
type="button"
id="btn1">
Submit
</button>
<br>
<button onclick="javascript:mr('GET',content,result,'get.php');" type="button"
id="btn2" >
List Jobs
</button>
<div id="result"></div>
The function mr is like this.It is for ajax post and get operations:
function mr(type,content,result,URL) {
var hr = new XMLHttpRequest();
//var content = document.getElementById("content").value;
var vars = "content=" +content;
if (type == 'GET')
URL = URL + '?' + vars;
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("result").innerHTML = return_data;
}
}
hr.open(type, URL, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
switch(type) {
case 'GET':
hr.send();
break;
case 'POST':
hr.send(vars);
break;
}
document.getElementById("result").innerHTML = "Processing...";
}
</script>
post.php
<?php echo "POST\n"; if(isset($_POST)) print_r($_POST); ?>
get.php
<?php echo "GET\n"; if(isset($_GET)) print_r($_GET); ?>
When I click submit ,I got the following output.
POST Array ( [content] => [object HTMLInputElement] )
And clicking list button the output:
GET Array ( [content] => [object HTMLInputElement] )
It's because of this line:
var vars = "content=" +content;
You're sending the actual <input> element instead of it's value or id. You were on the right track with the commented out line above it.
To send the value, not the input object:
var content = document.getElementById("content");
var vars = "content=" + content.value;
To send the id:
var content = document.getElementById("content");
var vars = "content=" + content.id;

XMLHttpRequest returning in FF but not IE

I'm trying to do an AJAX call to pull back data to popluate a drop down box based off the select of another drop down box. My code is working fine in FF 9.0.1 (used for firebug), but failing in IE 7 (which is my company standard). I've tried several ways to show the data, and I don't have the time right now to learn how to do this in jQuery. I'm sure this will be a head smacker, but what about IE is causing this issue?
Here are my code pages. First is the trimmed down version of the form calling the JavaScript.
<html>
<head>
<script language="JavaScript" src="/includes/Transaction_Update.js"></script>
<form id="submit" name="submit" action="Transaction_Process.php" method="post">
<table align='left'>
<tr>
<td class='reporttd'>Vendor</td>
<td>
<select name='selVendorCode' id='selVendorCode' onChange="getServiceCode()">
<option value='' selected='selected'></option>
<?php echo $vendorOptionList; ?>
</select>
</td>
</tr>
<tr>
<td class='reporttd'>Service Code</td>
<td class='reporttd'>
<select name='selServiceCode' id='selServiceCode'>
<option value='' selected='selected'></option>
</select>
</td>
</tr>
</table>
</div>
</div>
</form>
JavaScript page
//setup xmlHttp request for Ajax call
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlhttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for (var i=0; i<xmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new Activexobject(xmlHttpVersions[i]);
}
catch(e) {}
}
}
if (!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
//Call page to get all service codes for a vendor.
function getServiceCode(){
if (xmlHttp){
try{
var vCode = document.getElementById("selVendorCode").value;
var parms = "vCode=" + vCode;
//Call Transaction_AJAX.php to pass back an XML.
xmlHttp.open("GET", "Transaction_AJAX.php?" + parms, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
catch(e){
alert("Can't connect to server:\n" + e.toString());
}
}
}
//Checks state of the HTTP request call, and proceed if status is ready
function handleRequestStateChange(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
handleServerResponse();
}
catch(e){
alert("Error reading the response: " + e.toString());
}
}
else{
alert("There was a problem retrieving the data:\n" + xmlHttp.StatusText);
}
}
}
//Handles response from the server
function handleServerResponse(){
var xmlResponse = xmlHttp.responseXML;
if (!xmlResponse || !xmlResponse.documentElement){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
var rootNodeName = xmlResponse.documentElement.nodeName;
if(rootNodeName == "parsererror"){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
xmlRoot = xmlResponse.documentElement;
if(rootNodeName != "root" || !xmlRoot.firstChild){
throw("Invalid XML structure:\n" + xmlHttp.responseText);
}
//Get response and load it into drop down
responseText = xmlRoot;
var sel = document.getElementById("selServiceCode");
sel.options.length = 0;
var opt = document.createElement("option");
document.getElementById("selServiceCode").options.add(opt);
for(var i=0; i < responseText.childElementCount; i++){
var newOpt = new Option(responseText.childNodes[i].childNodes[1].textContent,responseText.childNodes[i].childNodes[0].textContent);
sel.options[sel.options.length] = newOpt;
}
}
The PHP page creating the XML file
<?php
header('content-type:text/xml; charset=utf-8');
include("../includes/DBConn.php");
$vCode = $_GET['vCode'];
///Setup cursers and proc command
$curs = OCI_New_Cursor($c);
$stmt = OCI_Parse($c,"begin schema.package.procedure(:var_code, :expected_cv); end;");
OCI_Bind_By_Name($stmt, ":var_code", $vCode);
OCI_Bind_By_Name($stmt,":expected_cv",&$curs,-1,OCI_B_CURSOR);
//execute statment and cursors
oci_execute($stmt);
oci_execute($curs);
//Create xml document
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('root');
$root = $dom->appendChild($root);
//loop through results of Proc
while (ocifetchinto($curs,&$vendor_cv )) {
//Add node for each row
$occ = $dom->createElement("cell");
$occ = $root->appendChild($occ);
//Id Value
$id = "value";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
//Id text
$id = "text";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
}
//Close xml tags and save.
$xmlString = $dom->saveXML();
//Echo XML back to Transaction_Update.js
echo $xmlString;
?>
Here is how you do it in jQuery
1) Include jQuery library in your head section of the page. (here i am refering it from the google cdn)
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
In your javascript
$("#stateDropDown").change(function(){
var stateId=$("#stateDropDown").val();
$.ajax({
url: 'getcities.php?stateid='+stateId,
success: function(data) {
$("cityDropDown").html(data);
}
});
});
Assuming you have a HTML select element with id "stateDropDown" for states and another one with id "cityDropDown" for cities.
The above code will do the follolwing
1) When the value of state dropdown changes, it executes the inside code.
2 ) Reade the selected item value and store it in a variable called stateId.
3) Using the jQuery ajax method , it makes a call to getcities.php page with a query string key called stateid
4) when we get a response from the ajax call, the control flow will be in the part called "success" handler. there we are receiving the response in a variable called data.
5) setting the received response (data) as the inner html of the city dropdown.
Assuming the getcities.php page will return some output like this
<option value='1'>Ann Arbor</option>
<option value='2'>Dexter</option>
<option value='3'>Novi</option>
jQuery will take care of your cross browser issues. Yes its is well tested and everybody is using it.
http://www.jquery.com
You can change your for loop in handleServerResponse to the following to fix this issue:
for(var i=0; i < responseText.childNodes.length; i++){
var node = responseText.childNodes[i];
var text = node.childNodes[1].text ? node.childNodes[1].text : node.childNodes[1].textContent;
var value = node.childNodes[0].text ? node.childNodes[0].text : node.childNodes[0].textContent;
var newOpt = new Option(text,value);
sel.options[sel.options.length] = newOpt;
}

Categories