It's probably super-simple, but I want to update the PHP variables by getting a new random record from the SQL server, and then pass those variables into JavaScript to use them, however the PHP function I've called only works once and then stops working. I don't know if something is wrong with the function call or with the function itself.
<?php
function getQuestion(){
$conn = mysqli_connect("localhost", "root", "pass", "projectDB");
$sql = "SELECT question, answerA, answerB, answerC, answerD,
correctAns FROM questionTable ORDER BY rand() LIMIT 3";
global $result, $row, $question, $answerA, $answerB, $answerC,
$answerD, $correctAns;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$question = $row["question"];
$answerA = $row["answerA"];
$answerB = $row["answerB"];
$answerC = $row["answerC"];
$answerD = $row["answerD"];
$correctAns = $row["correctAns"];
mysqli_close($conn);
}
getQuestion();
?>
<script>
var answerA = "<?php echo $answerA; ?>";
var answerB = "<?php echo $answerB; ?>";
var answerC = "<?php echo $answerC; ?>";
var answerD = "<?php echo $answerD; ?>";
var question = "<?php echo $question; ?>";
var correctAnswer = "<?php echo $correctAns; ?>";
function newQuestion(){
<?php getQuestion(); ?>
question = "<?php echo $question; ?>";
answerA = "<?php echo $answerA; ?>";
answerB = "<?php echo $answerB; ?>";
answerC = "<?php echo $answerC; ?>";
answerD = "<?php echo $answerD; ?>";
correctAnswer = "<?php echo $correctAns; ?>";
}
else if (targetHit == true){
reset();
newQuestion();
tick = 0;
}
</script>
The first time the variables are defined and getQuestion() is used in the top PHP, they get correct values, and the first time newQuestion() is called they get updated with different correct values, however after that, calling newQuestion() does not change any of the values like it should.
Thanks.
Its not a correct way to write php code in javascript even we should not write php code in javascript. better to retrieve value from database and store value on javascript variable by ajax request. its give you sql result every time.
make a php file to retrieve data and another php or js file to ajax request.
here a code for
php files as wrote
function getQuestion(){
$conn = mysqli_connect("localhost", "root", "pass", "projectDB");
$sql = "SELECT question, answerA, answerB, answerC, answerD,
correctAns FROM questionTable ORDER BY rand() LIMIT 3";
global $result, $row, $question, $answerA, $answerB, $answerC,
$answerD, $correctAns;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$question = $row["question"];
$answerA = $row["answerA"];
$answerB = $row["answerB"];
$answerC = $row["answerC"];
$answerD = $row["answerD"];
$correctAns = $row["correctAns"];
mysqli_close($conn);
return $correctAns;}
echo json_encode(getQuestion());
here ajax request to get result
$.ajax({
type: 'post',
url: 'phpfilename.php',
success: function ( data ) {
alert(JSON.parse(data));
},
error:function(error){
console.log(error);
}
});
Related
Here is my code, and while running it's not giving anything in the console.
This is how I am trying to check the data. If the data correctly I want the mentioned console in success code. But if it is not then I want else code to run. But the if-else conditions are not working properly. I am including PHP code and ajax code which I have tried. Am I doing it right?
<?php
$host = "dpydaldermt01.******.com";
$username = "test";
$password = "Test";
$database_name = "test";
$conn = mysqli_connect($host, $username, $password, $database_name) or die("Connection failed: " . mysqli_error());
$sql = "select ID, user_email from ci_iwp_wp_users limit 10";
$result = mysqli_query($conn, $sql);
$users = array();
?>
<script>
(function($) {
<?php
while($row = mysqli_fetch_assoc($result)) {
$email = $row['user_email'];
?>
var mail = "<?php echo $email ?>";
$.ajax({
type:'POST',
url:'http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr='+mail,
dataType:'someData',
success: function(data) {
if(data === '# rc=0, count=0, message=Success') {
console.log(data);
}
}
});
<?php
$users[]=$row;
}
?>
});
</script>
<?php
echo json_encode($users);
?>
Just Remove dataType:'someData', from your code because it always request and response in json so you dont have to declare separately.
I am trying to set up a select box that would show up the cities depending on the prior selection of the state.
Basically, I am using ajax to run my php.file to populate my <option>. In the php file I successfully passed the pre-selected state to query the database. However, now, to populate the <option> I am using ajax success to call the php file, however, whenever I try to pass the variable containing the php code it shows up commented with !-- and --.
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
I expect to populate my select options by looping through the table city in the php file. The tag <?php include_once 'fillcity.php' ?> was used to populate the state select. Probably, there may be a more direct way to populate accordingly, but as I am new to programming, I am trying to figure things out on my own. But please, feel free to recommend other methods as I am not sure if what I am planning to do will gonna work. Thanks!
You can try this one. You can modify it later for improvement.
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetState"){
//SAMPLE QUERY
$sql = "SELECT StateID,StateName from State";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetCity"){
$StateID= $_POST["StateID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT CityID,CityName from City where StateID = '".$StateID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="state"></select>
<select id="city"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadState();
function LoadState(){
$.ajax({
url:"read.php?type=GetState",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
State</option>";
for(var i in data){
options += "<option value='"+data[i].StateID+"'>" + data[i].StateName+ "</option>";
}
$("#state").html(options);
}
});
}
function LoadCity(StateID){
$.ajax({
url:"read.php?type=GetCity",
type:"POST",
data:{
StateID: StateID
},
success:function(data){
var options = "<option selected disabled value="">Select City</option>";
for(var i in data){
options += "<option value='"+data[i].CityID+"'>" + data[i].CityName+ "</option>";
}
$("#city").html(options);
}
});
}
$("#city").change(function(){
LoadCity(this.value);
});
You don't need to include 'fillcity.php. The AJAX call runs that script, and the response is the output. It will be in the parameter of the success function.
function fillSelectCity () {
var getState = $("#selectState").val();
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (tag){
$('#select-city').html(tag);
}
});
}
My php invoicing system uses jQuery autocomplete to lookup a customer's name from my database. The layout of the pages is like this:
invoice.php - contains the variable 'customers' and the php database select script
invoice.js - this contains the jQuery on focus command
In Safari everything works fine. I have used the console to see the variables logged - example (CUSTOMERS – ["Paul Smith"] (1))
But in Chrome and Firefox the console shows: "CUSTOMERS" Array [ ]
My code for invoice.php:
var arr_customers = new Array();
<?php $result = mysql_query("select * from customer where breaker='".$_SESSION['breaker_id']."'");?>
<?php $str = ""; $i = 0; while ($row = mysql_fetch_array($result)) { ?>
arr_customers[<?php echo $i;?>] = new Array();
arr_customers[<?php echo $i;?>][0] = "<?php echo $row['customer_name']; ?>";
arr_customers[<?php echo $i;?>][1] = "<?php echo $row['customer_code']; ?>";
arr_customers[<?php echo $i;?>][2] = "<?php echo $row['address']; ?>";
arr_customers[<?php echo $i;?>][3] = "<?php echo $row['uid']; ?>";
<?php if ($i == 0) {
$str = "'" . $row['customer_name'] . "'";
} else {
$str = $str . ",'" . $row['customer_name'] . "'";
}?>
<?php $i++;
} ?>
var customers =<?php echo ("[" . $str . "]") ?>;
and for the invoice.js:
jQuery(document).ready(function($) {
$("#customer_name").on('focus', function() {
console.log("CUSTOMERS", customers);
$( "#customer_name" ).autocomplete({
source: customers
});
});
});
I know I should be using prepared statements as well!
I check if the user is logged in with, if they are then i pull their details from the database, i then want to auto fill this data into part of my form.
while(OCIFetch($stmt)) {
if(OCIResult($stmt,"PASSWORD")==$Password) {
$flag=true;
$First=OCIResult($stmt,"FIRSTNAME");
$Sur=OCIResult($stmt,"SURNAME");
$Email=OCIResult($stmt,"EMAIL");
$Phone=OCIResult($stmt,"PHONE");
$Address=OCIResult($stmt,"ADDRESS");
$City=OCIResult($stmt, "CITY");
$Post=OCIResult($stmt, "POSTCODE");
//set up session - Declare session variables and assign their corresponding values
session_start();
$_SESSION['RegUser'] = OCIResult($stmt,"USERNAME");
$_SESSION['RegFirst'] = $First;
$_SESSION['RegSur'] = $Sur;
$_SESSION['RegEmail'] = $Email;
$_SESSION['RegPhone'] = $Phone;
$_SESSION['RegAdd'] = $Address;
$_SESSION['RegCity'] = $City;
$_SESSION['RegPost'] = $Post;
}
This is the code im currently attempting to use to auto fill but the fields still appear blank
//Autofill the details if the user is logged in
window.onload = function() {
document.forms['Order']['RegFirst'].value = "<?php echo $First?>";
document.forms['Order']['RegSur'].value = "<?php echo $Sur?>";
document.forms['Order']['RegEmail'].value = "<?php echo $Email?>";
document.forms['Order']['RegPhone'].value = "<?php echo $Phone?>";
document.forms['Order']['RegAdd'].value = "<?php echo $Address?>";
document.forms['Order']['RegCity'].value = "<?php echo $City?>";
document.forms['Order']['RegPost'].value = "<?php echo $Post?>";
}
You don't need javascript for this, just echo the values into your html form fields
<input id="example" value="<?php echo $Post?>" />
Rinse and repeat for all other form fields.
Try this,
//Autofill the details if the user is logged in
window.onload = function() {
document.forms['Order']['RegFirst'].value = "<?php echo $_SESSION['RegFirst'];?>";
document.forms['Order']['RegSur'].value = "<?php echo $_SESSION['RegSur'];?>";
document.forms['Order']['RegEmail'].value = "<?php echo $_SESSION['RegPhone'];?>";
document.forms['Order']['RegPhone'].value = "<?php echo $_SESSION['RegPhone'];?>";
document.forms['Order']['RegAdd'].value = "<?php echo $_SESSION['RegAdd'];?>";
document.forms['Order']['RegCity'].value = "<?php echo$_SESSION['RegCity'];?>";
document.forms['Order']['RegPost'].value = "<?php echo $_SESSION['RegPost'];?>";
}
Ive been trying this for hours now but it wont quite get there.
I have a database which amongst other things contains geocodes, lat and lon. I have accessed these using the following PHP
<?php
mysql_connect("localhost", "tompublic", "public") or die(mysql_error());
mysql_select_db("first_section") or die(mysql_error());
$data = mysql_query("SELECT geo_lat, geo_lon FROM first_page_data")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)){
$lat[] = $row['geo_lat'];
$lon[] = $row['geo_lon'];
}
?>
These values in $lat and $lon then need to be put into an array in a javascript function like so:
var latit = [];
var longi = [];
latit = '<?php echo $lat[]; ?>';
longi = '<?php echo $lon[]; ?>';
But it wont work! Any ideas?
Try:
var latit = <?php echo json_encode($lat); ?>;
var longi = <?php echo json_encode($lon); ?>;
Edit: Also, the mysql_ functions are deprecated.
You could try this:
var latit = [<?php echo implode(",",$lat) ?>];
var longi = [<?php echo implode(",",$lon) ?>];
First thing is first try to switch to MySQLi due to the fact that Mysql is depreciated.
But try
var latit = <?php echo json_encode($lat); ?>;
var longi = <?php echo json_encode($lon); ?>;
You can either do as #Robbert stated
OR
Using php json_encode convert it to JSON string and you need to JSON.parse() it to convert it to javascript object
var latit = JSON.parse("<?php echo json_encode($lat); ?>");
var longi = JSON.parse("<?php echo json_encode($lon); ?>");
JavaScript arrays are created using a comma separated list surrounded by brackets
var latit = [];
To use your PHP values
var latit = [<?PHP echo implode(",",$lat); ?>];
This assumes your values are numbers. If not, you'll need to include quotes.
var latit = ['<?PHP echo implode("','",$lat); ?>'];
Finally, json_encode is a good option as many of the other answers indicate.
Try this:
<?php
mysql_connect("localhost", "tompublic", "public") or die(mysql_error());
mysql_select_db("first_section") or die(mysql_error());
$data = mysql_query("SELECT geo_lat, geo_lon FROM first_page_data")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)){
$lat[] = $row['geo_lat'];
$lon[] = $row['geo_lon'];
}
echo '
<script type="text/javascript">
var latit = '.json_encode($lat).';
var longi = '.json_encode($lon).';
</script>
';
?>