I've have created a custom table in mysql. I've entered a bit of test data just to see if I can pull some results. The query was successful when I ran it just in the template, so I know it works. As I have tried to convert it into a Ajax request seems that no data is being passed. I'm not sure what it is I am missing, or possibly an error I have entered somewhere, but it seems when I try to turn it into an Ajax request nothing happens.
Any ideas?
PHP
$q = intval($_GET['q']);
$pull = $wpdb->get_results(
"
SELECT ID, department, contact, forms
FROM referrals
WHERE ID = '$q'
"
);
foreach ( $pull as $requestdata)
{
echo $requestdata->department;
echo '<br />';
echo $requestdata->contact;
echo '<br />';
echo $requestdata->forms;
}
AJAX
<script>
function displayData(str) {
if (str=="") {
document.getElementById("txt").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo content_url(); ?>/themes/child/get-referral.php?q="+str, true);
xmlhttp.send();
}
</script>
HTML
<select name="users" onchange="displayData(this.value)">
<option value="">Select a person:</option>
<option value="1">Test 1</option>
<option value="2"Test 2</option>
</select>
<br>
<div id="txt"></div>
You need to change your ajax request to wp-admin/admin.ajax.php.
If you open that file you will find there is a constant setting named DOING_AJAX. Only the requests to this link can avoid the normal header being sent to browser because of setting DOING_AJAX to ture.
Actually you can debug like this: visit <?php echo content_url(); ?>/themes/child/get-referral.php?q=xx, you will find there are other info sent. thats why that ajax doesnt work.
Switched to this. Hopefully it helps someone else out.
HTML
<select id="mySelect" onchange="pullData()">
<option value="">Select</option>
<option value="options">options</option>
<option value="someother1">someother1</option>
<option value="someother_2">someother_2</option>
</select>
<div id="referral">Test</div>
AJAX / JS
<script>
function pullData() {
var xhttp;
//url variables
var url = "/wp-content/referrals/";
var selectedValueIs = document.getElementById("mySelect").value;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("referral").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url+selectedValueIs+'.txt' , true);
xhttp.send();
}
</script>
Related
I am trying to make easy-to-use form for the users who are using our internal application. Basicly I have a select element. What I want is when I choose anything I want to fill specified text boxes.
Codes are below. That works fine but fill only 1 box.Pls do not forget normally I am getting data from the mySQL db.
html file:
<script src="choose.js"></script>
<select onchange="ChooseGuest(this.value)">
<option value="1">guest 1</option>
<option value="2">guest 2</option>
<option value="3">guest 3</option>
</select>
<input type="text" id="guestdetails"/>
<input type="text" id="guestdetails2"/>
php data file:
$AskForIt = $_GET["q"];
If ($AskForIt == "1") {
echo "guest 1 data";
} Elseif ($AskForIt == "2") {
echo "guest 2 data";
} Elseif ($AskForIt == "3") {
echo "guest 3 data";
}
js file:
var xmlHttp
function ChooseGuest(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("upgrade your browser");
return;
}
var url="guests.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("guestdetails").value=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
From what I understand, you are trying to fill the input boxes with data pulled from your DB and have the appropriate data shown depending on which drop down is selected. PHP is server side only. Once the page loads the PHP will only run once and not again until the page is reloaded. So, you'll need to access those vars using JS. This is probably why only the first selection is being filled.
If this is so, you will need to go into your PHP file and create JS vars that are equal to the data accessed from the DB. Simply set your JS vars equal to a PHP echo of the vars from your php:
PHP Data File
<?php
var somePHPvar = "DB Value";
?>
<script>
var someVar = <?php echo somePHPvar; ?>;
</script>
If this is all done on the same PHP file, don't forget to include it on the page and call these JS vars. From there you'll be able to fill those values using JS.
Here is a way you can do this with just jQuery.
Example: https://jsfiddle.net/Twisty/u2gqwfL4/
JavaScript
var myData = [
"guest 1 data",
"guest 2 data",
"guest 3 data"
];
$(function() {
function ChooseGuest(v, str) {
// Example AJAX Post call in jQuery
// Replace '/echo/json/' with 'guests.php'
// or use $.get() in the same way
$.post("/echo/json/", {
json: JSON.stringify(myData),
q: str
}, function(results) {
console.log(results, v);
$("#guestdetails" + v).val(results[v - 1]);
});
}
$("#guestSelect option").click(function() {
var selVal = parseInt($(this).val());
var selText = $(this).html();
ChooseGuest(selVal, selText);
});
});
Your code will be a bit different due to the nature of jsfiddle and the way exampled are made. I would suggest:
function ChooseGuest(v, str) {
$.get("guests.php", {
q: str,
sid: Math.random()
}, function(results) {
console.log(results, v);
$("#guestdetails" + v).val(results);
});
}
I am relatively new to PHP and I am (trying to) developing my first AJAX code...
I am trying to pass an attribute from a select with several options, each option with its very own unique attribute "values" that is a String.
The PHP file GETs the value and does something with it (for instance prints it out). And the generated file is then returned to my main HTML page.
Here is the source code...
Here is my javaScript:
function showUser(myElement) {
var str = myElement.options[myElement.selectedIndex].getAttribute("values");
if (str == "") {
document.getElementById("myResponse").innerHTML = "";
return;
} else {
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("myResponse").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
}
My HTML is as following:
<form>
<select name="users" onchange="showUser(this)">
<option values="">Select a person:</option>
<option values="Rasmus Lerdorf">Creator of PHP</option>
<option values="Linus Torvalds">Developed Linux</option>
<option values="Dennis Ritchie">Developper of C</option>
</select>
</form>
<br>
<div id="myResponse"><b>Person info will be listed here...</b></div>
My PHP is:
<?php
$q = intval($_GET['q']);
echo $q;
?>
I get 0 instead of the text string, what is wrong with my code?
Silly me,
I copied and pasted a basic example from a tutorial and I did not realize that the PHP code was casting the string that was sent over the GET to an integer.
$q = intval($_GET['q']);
The code should be :
$q = $_GET['q'];
On my earlier stage of the development I was indeed passing an integer, so the code was working.
The code returned 0 instead of an error because the intval of a string is 0 on failure.
Writing down the question here I realized the mistake...
I try to pass a variable from Javascript (when choosing some option in a form) to a PHP file which calls a SQL query.
The SQL query (a string) should be handed over to a Javascript function and the function should be executed. Everything in one click. Is that somehow possible?
I tried that with a AJAX request but when I use this for my last step:
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
I get the exception: Uncaught TypeError: Cannot set property 'innerHTML' of null
And it prints out "undefined"
.HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
if (time=="") {
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getstring.php?q="+time,true);
xmlhttp.send();
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
document.write(javascriptstring);
}
</script>
</head>
<body>
<form>
<select name="somestring" onchange="showString(this.value)">
<option value="">No string selected</option>
<option value="1">String 1</option>
</select>
</form>
<br>
<div id="txtHint"><b>String will be listed here...</b></div>
</body>
</html>
PHP
<?php
$q = intval($_GET['q']);
$con = pg_connect("host=localhost port=5432 dbname=Twitter user=postgres password=****");
if (!$con) {
die('Could not connect: ' . pg_errormessage($con));
}
$sql="SELECT * FROM tswholeworld WHERE createdat > (NOW() - INTERVAL '".$q."hour');";
$result = pg_query($con,$sql);
$string = "";
while($row = pg_fetch_assoc($result)){
$lat = $row['latitude'];
$lon = $row['longitude'];
$string .= "new google.maps.LatLng({$lat}, {$lon}), ";
}
echo '{"value": "'.$string.'"}';
pg_close($con);
?>
I guess this much amount of AJAX should suffice. Actually document.write replaces the whole DOM with the current. I have removed that and modified your function. Also I have removed the native Ajax code since you already have jQuery so no point in adding that big code. This small function will get the JSON data and print the value that the server is sending
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
if (time=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
$.getJSON('getstring.php?q='+time, function(data) {
document.getElementById("txtHint").innerHTML = data.value;
});
}
</script>
Edit: Please close the external script tags
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
//your script
</script>
Keep the Javascript function definition in head or before the select tag. like below -
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
if (time=="") {
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getstring.php?q="+time,true);
xmlhttp.send();
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
document.write(javascriptstring);
}
</script>
</head>
<body>
<form>
<select name="somestring" onchange="showString(this.value)">
<option value="">No string selected</option>
<option value="1">String 1</option>
</select>
</form>
</body>
</html>
You forget to close script tag
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>// close include external javascript tag
Then you call your function inside script tag
<script>
function showString(time) {
-----Your code----
</script>
i am developing my final year project on codeigniter and facing problem i want to click a drop-down value and then it will return table from db but alas i can't do
this is plain php code that i want to convert into codeigniter please help me
thanks in advance.
<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
You need to separate the code in Controller, View and Model:
Model for DDBB operations.
Controller: control where the data goes and how it can be displayed, and other logic.
View, here is where the form is rendered.
Codeigniter has a great documentation to learn how to do it.
Controllers
Views
Models has the same url, but for models, i've not reputation enough to post 3 links, sorry
You can do like this
$(document).on("change","#select",function(){
$.ajax({
url:""// path to your controller function. here keep all the code which is present in your getuser.php in to a function in controller
data:{"key":value,"key":value}
dataType:"HTML",
success:function(data){
$("#txtHint").html(data)// this you can do 2 things, either manipulate all your data in controller
//and directly change the html of the div, or u can get the required data
}
})
});
I don't know ajax very well but have the following function:
function saveViaAJAX() {
var canvasData = $("#wPaint").wPaint("image");
var postData = "canvasData="+canvasData;
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function() {
if (ajax.readyState == 4) {
document.getElementById("debugFilenameConsole").innerHTML="Saved as<br><a target='_blank' href='"+ajax.responseText+"'>"+ajax.responseText+" </a><br>Reload this page to generate new image or click the filename to open the image file in a new window.";
}
}
ajax.send(postData);
}
This works fine but I have another variable i want to pass to testSave.php
<select id="website_string" name="website_string">
<option value="" selected="selected"></option>
<option value="A4">A4</option>
<option value="A5">A5</option>
</select>
I'm trying to pass this in the same function but it's ("Content-type", "application/x-www-form-urlencoded") I think.