Hi I am creating a wordpress plugin and i am a little bit stack here. there's text box number 1 which is the order number and number 2 which is the order name. This is what i want. If the customer enters a number in textbox number 1 which is order number, the value he or she entered will check into the database and get the corresponding order name of that order number. Its realtime. No need to submit before it appears. Everytime they input something it will immediate check to the database and display it in text box number 2(order name). I research this and try using ajax in wordpress but i dont know how to use. Thanks.
Here's some boilerplate code to get you started....
<script type="text/javascript" charset="utf-8">
var req;
function handler_orderNumberField_onchange(fld) {
var text = fld.value;
if (text.length == 8) {
queryForOrderName(text);
}
}
function queryForOrderName(orderNumber) {
document.getElementById('orderNameField').value = "Please wait..."
req = new XMLHttpRequest();
var url = "http://www.mydomain.com/getordername.php?ordernumber=" + orderNumber;
req.onreadystatechange = function() {
var field = document.getElementById('orderNameField');
var rs = this.readyState;
var status = this.status;
if (rs == 4 && status == 200) {
field.value = req.responseText;
}
};
req.ontimeout = function() {
document.getElementById('orderNameField').value = 'Timeout.';
}
req.timeout = 10000;
req.open("GET", url, true);
req.send();
}
</script>
<p>Order Number: <input type="text" name="orderNumber" value="" id="orderNumberField" onchange="handler_orderNumberField_onchange(this)"></p>
<p>Order Name: <input type="text" name="orderName" value="" id="orderNameField"></p>
Note that you need to implement a getordername.php script yourself; example:
<?php
$ordernr = (int) $_GET["ordernumber"];
$result = sprintf("Testorder - Order Number %d", $ordernr);
header("Content-type: text/plain; charset=UTF-8");
echo $result;
exit;
?>
Related
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);
?>
I have an autocomplete jQuery menu, that output the name of all the users I have, from a MySQL database. I'm trying to link each selection to the proper profile. For that, the URL is something like: /profile.php?id=341, 341 that stands for the ID of the user selected.
The only problem, is that when I try to put the ID of a given user, ALL the ID of ALL the user are shown in the URL... and I want only the ID of the selected user!
I have tried with PHP, but I don't know what to add to the following line to make it work.
$req = mysql_query("select id, Username, EmailAddress from ***");
Should it be something like WHERE Username='username'....? Finally, I know that I should maybe try something else, without PHP, but I just want to test it that way! Thanks!
<input type="text" name="course" id="course" />
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#course").autocomplete("/test/test2.php", {
selectFirst: false,
formatItem: function(data, i, n, value) {
//make the suggestion look nice
return "<font color='#3399CC'>" + value.split("::")[0] + "</font>";
},
formatResult: function(data,value) {
//only show the suggestions and not the URLs in the list
return value.split("::")[0];
}
}).result(function(event, data, formatted) {
//redirect to the URL in the string
var pieces = formatted.split("::");
window.location.href = '/profile.php?id='+
<?php
mysql_connect ("***", "***","***") or die (mysql_error());
mysql_select_db ("***");
$req = mysql_query("select id, Username, EmailAddress from ***");
while($dnn = mysql_fetch_array($req))
{
echo $dnn['id'];
}
?>
;
console.log(data);
console.log(formatted);
});
});
</script>
Your MySQL query is true to every user in the database, so it returns all the users. If you want to go to "foo"'s profile, you need to tell the database to fetch "foo"'s id only. A unique row that the user has maybe there email and must be their username.
I assume you have an array in javascript which contains selected users:
var users = new Array("Daniel","Amy","Sandy");
then you need to use ajax to communicate to php:
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}//This can become an external file to link
</script>
so then you can post data to php:
<script>
var returnedStr = "";
function searchuser(){ //use searchuser function on a button to call
var usersStr = users.toString(); //the string that contain the users separated by ","
var ajax = ajaxObj("POST", "thisurl.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "fail"){ //i didn't include this in php, but you can add it yourself if you can't fetch from mysql
echo "Failed";
} else {
returnedStr = ajax.responseText;// when php echos
}
}
}
ajax.send("u="+usersStr);
}
</script>
then your php will need to handle the string:
<?php
if(isset($_POST["u"])){
$returnArr = array();
$returnStr = "";
$processedArr = explode(',', $_POST['u']); //Here the posted data will turn into an array
$lengthArr = count($processedArr);
for ($i=0; $i<=$lengthArr; $i++)
{
$req = mysql_query("SELECT id FROM xxx WHERE Username='$processedArr[$i]' LIMIT 1");
while($dnn = mysql_fetch_array($req))
{
array_push($returnArr, $dnn['id']);
}
}
$returnStr = implode(",",$returnArr);
echo ($returnStr);
}
?>
Now in Javascript returnedStr will hopefully be 1,2,3 or something like that.
Please comment if this doesn't work!
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);
I am writing code to make a basic chatroom. The code I have takes lines entered into the input textbox, then uses Ajax to write to a random filename, then I have javascript loop every second using setInterval to load and display from the text file.
After the user logs in with information that populates a MySQL database I want to have a basic welcoming message automatically saved to the text file upon entering the chat. I do this by calling my saveData function with username as 'Host' and then the welcoming message which is declared in a variable.
The function that sends the login information to the database and the function that saves the welcoming message are both called under the login() function. The login() function is called after submitting the info form.
Here is the problem: I cannot get the functions, saveLogin() and saveData(), to BOTH fully execute when called under login(). If I comment one out and NOT the other, the function will work fine. So they work independently, but not together. If both functions are called then saveData() works fine, but saveLogin() will not. I have no idea why.
I was able to narrow the problem down to the 'XMLHttpRequestObject.send' event under the saveLogin() function. The rest of that function appears to be executed. I thought maybe it was a problem with the variable names or something, so I tried some variations, but nothing has resolved the issue.
<script language = "javascript">
// loads XML HTTP per browser type
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
//create random string
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
}
rString = randomString(128);
filename = rString;
// loads chat lines from file using POST method with timer
function getData(geturl)
{
if(XMLHttpRequestObject) {
geturl = "getdata.php";
XMLHttpRequestObject.open("POST", geturl);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
document.formChat2.textarea1.value = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send("filename=" + filename);
}
}
// saves new chat line to file
function saveData(filename, username, newline)
{
if(XMLHttpRequestObject && document.formChat1.txtLine.value != "" || username == "Host") {
var url = "savedata.php";
XMLHttpRequestObject.open("POST", url);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
}
}
XMLHttpRequestObject.send("filename=" + filename + "&username=" + username + "&newline=" + newline);
document.formChat1.btnDisplay.click();
document.formChat1.txtLine.value = "";
}
}
// saves login info to database
function saveLogin(filename, username, email, phone, weburl)
{
if(XMLHttpRequestObject) {
var loginurl = "login.php";
XMLHttpRequestObject.open("POST", loginurl);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
}
}
XMLHttpRequestObject.send("filename=" + filename + "&username=" + username + "&email=" + email + "&phone=" + phone + "&weburl=" + weburl);
}
}
function login(divID) {
username = document.formLogin.txtLogin.value;
email = document.formLogin.txtEmail.value;
phone = document.formLogin.txtPhone.value;
weburl = document.formLogin.txtURL.value;
saveLogin(filename, username, email, phone, weburl);
var obj = document.getElementById(divID);
obj.innerHTML = "<div id='targetDiv'><form name='formChat1' method='POST' onSubmit='return false;'><input type='text' name='txtLine' id='txtLine' size='30'><input type='button' name='btnDisplay' value='Display Message' onclick=\"setInterval('getData(filename)', 1000);\"><input type='button' name='btnSave' value='Send Message' onclick='saveData(filename, username, txtLine.value)'></form><form name='formChat2'><textarea name='textarea1' id='textarea1' rows='10' cols='50'></textarea></form></div>";
welcome = "Welcome to the chat.";
saveData(filename, 'Host', welcome);
}
</script>
<div id="targetDiv">
<form name="formLogin" method="POST">
Please enter your info:<br>
<input type="text" name="txtLogin" id="txtLogin" size="50" value="Name (Required)" onfocus="document.formLogin.txtLogin.value=''"><br>
<input type="text" name="txtEmail" id="txtEmail" size="50" value="Email Address (Required)" onfocus="document.formLogin.txtEmail.value=''"><br>
<input type="text" name="txtPhone" id="txtPhone" size="50" value="Phone Number (Optional)" onfocus="document.formLogin.txtPhone.value=''"><br>
<input type="text" name="txtURL" id="txtURL" size="50" value="Website URL (Optional)" onfocus="document.formLogin.txtURL.value=''"><br>
<input type="button" name="btnLogin" value="Login"
onclick="login('targetDiv');">
</form>
</div>
You need to use different XHR objects, so that you can get both responses, since you're sending both AJAX requests at the same time.
Write a function like:
function getXHR() {
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
return XMLHttpRequestObject;
}
Then call it in each of the functions that performs AJAX requests, with:
var XHRObject = getXHR();
and use that within the function.
I have the following ajax.js, which I must use:
var xmlRequest = null;
function ajax(url, parametersArray, callbackFunction, fcnVars) {
if (xmlRequest != null) {
if (xmlRequest.readyState == 2 || xmlRequest.readyState == 3) {
xmlRequest.abort();
xmlRequest = null;
}
}
if (parametersArray == null)
parameters = "";
else
parameters = formatParameters(parametersArray);
if (window.XMLHttpRequest)
xmlRequest = new XMLHttpRequest();
else
xmlRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
xmlRequest.open("POST", url, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
if (xmlRequest.responseText) {
callbackFunction(xmlRequest.responseText, fcnVars);
}
}
}
xmlRequest.setRequestHeader("Content-length", parameters.length);
xmlRequest.setRequestHeader("Connection", "close");
xmlRequest.send(parameters);
}
function formatParameters(parameters) {
var i = 0;
var param = "";
for (index in parameters) {
if (i==0) {
param += index+"="+urlencode(parameters[index]);
} else {
param += "&"+index+"="+urlencode(parameters[index]);
}
i++;
}
return param;
}
function urlencode(clearString) {
clearString = encodeURI(clearString);
clearString = clearString.replace('&', '%26');
return clearString;
}
and I have the following mysql table:
CREATE TABLE `dictionary` (
`word` varchar(64) NOT NULL,
PRIMARY KEY (`word`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
on the end, here is my search page:
<div id = "search">
<form id="searchform" method="post">
Search for Word:
</select>
<input type="text" id="search_term" name="search_term" />
<input type="submit" id="cmdSearch" value="Search" />
</form>
<div id="search_results"></div>
</div>
Now, I have to create a php function which will return an array with the words found in the table, using the above ajax.js
Results should be shown within the search_results div using ajax.
Of course, I will need a javascript code as well.
Anyone can help me to start to build this? I have done similar things with jquery,but now I must use this script, and I have no other way to do it.
Goal is to display the results in the php page without refresh.
Any help will be deeply appreciated
Update:
Here is my php code:
<?php
// add encoding here
header("Content-Type: text/html; charset=iso-8859-7");
// include the database connection here
include 'config.php';
include 'openDb.php';
function findWords(){
// sanitaze the user input
$term = strip_tags(substr($_POST['search_term'],0, 100));
$term = mysql_escape_string($term);
// query the database. one fileld only, so nothing to optimize here
$sql = "SELECT word FROM dictionary WHERE word like '%$term%'";
$result = mysql_query($sql);
// set the string variable
$string = '';
// if resulta are found then populate the string variable
if (mysql_num_rows($result) > 0){
while($row = mysql_fetch_object($result)){
// display the results here in bold and add a new line or break after each result
$string[] = "<b>".$row->user_name."</b><br/>\n";
}
} else {
// if no results are found, inform the visitors...
$string[] = "No matches!";
}
// output the string
return $string[];
Here is the javascript:
<script type='text/javascript'>
ajax("findWord.php", {id:search_term}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:search_term});
</script>
You will have to rely on the ajax function which lets you access whatever it loaded in the callback function:
callbackFunction(xmlRequest.responseText, fcnVars);
And ajax explains how it should be called itself:
ajax(url, parametersArray, callbackFunction, fcnVars)
Even though parametersArray should actually be an object ({index:value, i1:v2,...}) rather than an array ([val1, val2,...]). fcnVars can be an object containing anything that you want passed on to the callback function.
This should work:
ajax("add_page.php", {id:535}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:535});