I need to write a word in database, and i cant couse i get an error that: ReferenceError: Patikrinta is not defined Here is my ajax script which sends data to php file. Bellow there is php script if you need it. Cant find solution in stackowerflow.
$s .= "\n\t<td>";
$canEdit = getPermission('tasks', 'edit', $a['task_id']);
$canViewLog = getPermission('task_log', 'view', $a['task_id']);
$currentTasken=$a['task_id'];
$currentUser=$AppUI->user_id;
$currentPercent="5";
$currentDescription="Patikrinta";
if ($canEdit) {
$s .= ("\n\t\t".'<a href="#">'
. "\n\t\t\t".'<img src="./images/icons/tick.png" alt="' . $AppUI->_('Check')
. '" border="0" width="12" height="12" onclick="javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', '.$currentDescription.')" />' . "\n\t\t</a>");
}
$s .= "\n\t</td>";
?>
<script type="text/javascript">
// Note that you should use `json_encode` to make sure the data is escaped properly.
var currentTasken = <?php echo json_encode($currentTasken=$a['task_id']); ?>;
var currentUser = <?php echo json_encode($currentUser=$AppUI->user_id); ?>;
function insertData(currentTasken, currentUser, currentPercent, currentDescription)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","modules/tasks/datafile.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// Here, use the JS variables but, likewise, make sure they are escaped properly with `encodeURIComponent`
xmlhttp.send("currentUser=" + encodeURIComponent(currentUser) + "¤tTasken=" + encodeURIComponent(currentTasken) + "¤tPercent=" + encodeURIComponent(currentPercent)+ "¤tDescription=" + encodeURIComponent(currentDescription));
}
</script>
Here is my php script:
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$currentDescription = isset($_POST['currentDescription']) ? $_POST['currentDescription'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task, task_log_description) VALUES ('$currentUser' , '$currentTasken', '$currentDescription')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("UPDATE dotp_tasks SET task_percent_complete = '$currentPercent' WHERE task_id='$currentTasken'") ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
Have you tried adding quotes around the function arguments which are strings? JS is looking for a reference to 'Patikrinta' because you are not adding quotes around the string. It should be a bit more like this:
javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', \''.$currentDescription.'\')" />' . "\n\t\t</a>");
The other arguments work because they are being passed as numbers and Javascript interprets them as such. The difference here is the value of $currentDescription is Patikrinta which is not a number and so JS looks for a variable or object called that.
As a side note - it's worth switching to use MySQLi if you can. MySQL_* functions are deprecated.
Related
I'm new to AJAX and I'm trying to create two dropdownlists of options from a database depending on what the user selects in two previous dropdowns. I've checked every way shape and form I've looked up but one dropdownlist doesn't return any values and the other says internal server error 500.
This is where the onChange event is, triggering the AJAX functions:
<select required="true" id="oficinaLoc" name="oficinaLoc" onchange="getAgent(this.value); selClub(this.value)">
<option value="">Seleccione Unidad</option>
<option value="680 - Centro de Tecnología de Información">680 - Centro de Tecnología de Información</option>
<option value="681 - Educación Agrícola">681 - Educación Agrícola</option>
<option value="682 - Planificación y Evaluación">682 - Planificación y Evaluación</option>
<option value="683 - Medios Educativos e Información">683 - Medios Educativos e Información</option>
<option value="684 - Ciencias de la Familia y el Consumidor">684 - Ciencias de la Familia y el Consumidor</option>
etc...
These are my AJAX functions:
function getAgent(str) {
if (str == "") {
document.getElementById("dispAgente").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("dispAgente").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getagent.php?q="+str,true);
xmlhttp.send();
}
}
function selClub(unidad) {
if (unidad == "") {
document.getElementById("dispNombre").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("dispNombre").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnombre.php?j="+unidad,true);
xmlhttp.send();
}
}
And these are the PHP pages it calls to through the XMLHttpRequest respectively:
getagent.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$q = ($_GET['q']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombre FROM personal4h WHERE unidadProg LIKE '%".$q."%'";
$result = mysqli_query($con,$sql);
echo '<select name="agenteExt"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
getnombre.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$j = ($_GET['j']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombreClub FROM club4h WHERE oficinaLoc LIKE '%".$j."%'";
$result = mysqli_query($con,$sql);
echo '<select name="nombreClub"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombreClub'] . ">" . $row['nombreClub'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
The getAgent function doesn't return any options in the dropdownlist even though it creates the empty select. The selClub function gives me a 500 internal server error on the xmlhttp.open("GET","getagent.php?q="+str,true); line. I really don't know what else to do, I've followed every online article I've found about this to the dot.
A 500 error is a server error, so that means the problem will be in PHP and I'm seeing alot of issues there. I'm not sure that this is a complete list,...you'll need to debug it yourself, but here's a couple that aren't helping.
$j = ($_GET['j']);
$j = $_GET['j'];
//dump the ()
echo '<select name="nombreClub"';
echo '<select name="nombreClub">';
//closing > is missing
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
echo "<option value=\"".$row['nombre']."\">".$row['nombre']."</option>";
//quotes around the value are missing
If you view the errors thrown by the PHP files, then you'll be on your way.
Good luck
I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.
setInterval(function () {sendRequest()}, 5000);
function sendRequest(){
var xmlhttp;
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){
console.log("yay");
}
}
xmlhttp.open("GET","getTweets.php",true);
xmlhttp.send();
}
My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:
$conn = mysqli_connect("localhost", "*", "*", "*");
if (!$conn) {
echo("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM tweets;";
$results = mysqli_query($conn, $query);
while($list = mysqli_fetch_assoc($results)){
echo '<div class="tweet-containter">';
echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">#'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';
echo '</div>';
}
This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
And Status Code
200: "OK"
404: Page not found
with that said, try doing this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}
ryandonohue,
PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).
Though, for your intermediate purposes you might not notice an immediate difference.
For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.
Modification:
function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
initialization: ( returns an array so you need to json encode)
getall('table',
Array(
'*'
),
null, 5, null);
AJAX:
function ajax(file,type, params, func){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//xmlhttp.responseText
func(xmlhttp.responseText);
}
}
if(type.toLowerCase() != "post"){
xmlhttp.open(
type, file + "?" + params_to_get(params),
true
);
xmlhttp.send();
}else{
xmlhttp.open(
type, file,
true
);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params_to_get(params));
Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.
check out this POST for more information about headers:
Ajax call to PHP is returning nothing
So basically I have a drop down list that displays data from a MySQL table(accounts) that would display user accounts. When the user selects one of the accounts I want it to display all facilities(facility table) that are owned by that account.
I have the drop down displaying the accounts, but it will not run the onChange() function to load my table. Here is everything I have, can someone tell me why my function is not getting triggered at all?
Index.php
<?php
require_once('sessionstart');
require_once('header.php');
require_once('dbconn.php');
//Accounts
require_once('getaccounts.php');
//Facility
echo "<div id='facilities'>";
require_once('getfacility.php');
echo "</div>";
?>
<?php
require_once 'footer.php';
?>
getaccounts.php
<?php
//require files
require_once('sessionstart.php');
require_once('dbconn.php');
//clear options variable
$options = "";
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT account_id, account_name FROM accounts";
$data = mysqli_query($dbc, $sql);
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
$options .="<option>" . $row['account_name'] . "</option>";
}
//account drop down form
$accountDropDown="<form id='account' name='account' method='post' action='getaccounts.php'>
<label>Accounts: </label>
<select name='account' id='account' onchange='showFacilities(this.value)'>
<option selected='selected' disabled='disabled' value=''>Select account</option>
" . $options . "
</select>
</form>";
//echo out account form
echo $accountDropDown;
?>
This works how I need it to and displays all accounts within the drop down. However I can't seem to get the showFacilities() function to work.
getfacility.php
<?php
require_once('dbconn.php');
$q = intval($_GET['q']);
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM facility "
. "INNER JOIN accounts ON accounts.account_id = facility.account_id "
. "WHERE facility.account_id = '".$q."'";
$data = mysqli_query($dbc, $sql);
echo "<table>
<tr>
<th>Facility Number</th>
<th>Facility Name</th>
<th>Facility Address</th>
<th>Facility City</th>
</tr>";
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
echo "<tr>";
echo "<td>" . $row['facility_number'] . "</td>";
echo "<td>" . $row['facility_name'] . "</td>";
echo "<td>" . $row['facility_address'] . "</td>";
echo "<td>" . $row['facility_city'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
footer.php (includes showFacilities())
<script>
function showFacilities(account){
//I wrote this to test and see if this function was even being triggered.
document.alert("test");
if(account == ""){
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("facilities").innerHTML = xmlhttp.responseText;
}
}
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
}
</script>
<footer>
<p>Copyright ©</p>
</footer>
</body>
</html>
Please tell me if I am doing this all wrong, am I laying everything out properly? Why is this function not being hit?
I have tried to a bunch of different things, and I just can't seem to get this to work, any help or advice or even a push in the proper direction will be very appreciated, thanks.
Your if else clauses don't add up (so your script is generating a script error, most likely a syntax error).
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
This piece doesn't have an IF to accompany it.
This would be correct:
if(account == ""){
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("facilities").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
On a sidenote: Why create a form wrapper around your select (the one that where you can load accounts) when you use an onchange event to fire an XmlHTTPRequest?
i am trying to change the select query on click or on change of the button,
the table name field names in the table general are equal to the fragment after page = (About, ContactInformation)
i'm not getting any error nor getting any result
index page code
<script>
function selectQuery(str) {
if (str == "") {
document.getElementById("editor").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("editor").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","queries.php?page="+str,true);
xmlhttp.send();
}
}
</script>
<ul>
<li><i class="fa fa-file-text"></i> About us</li>
<li><i class="fa fa-list-alt"></i> Contact us</li>
</ul>
queries.php page
<?php
$page = intval($_GET['page']);
$result = mysql_query("SELECT general.'".$page."' ".
"FROM general") or trigger_error(mysql_error());
echo $result;
?>
i tried to echo $page in the queries.php file directly but also it is not showing, seems its not even getting here,
so can anyone help pls
You aren't fetching those results. You need to use mysql_fetch_* functions to get those rows. Now the next part is whether you would like to get a JSON response or just output an HTML markup that can be used directly.
Here's what the fetching would look like:
<?php
$page = $_GET['page'];
$data = array();
$result = mysql_query("SELECT general.".$page." FROM general") or trigger_error(mysql_error());
while($row = mysql_fetch_assoc($result)) {
// fetch the results
$data[] = $row;
}
echo json_encode($data);
?>
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a version with mysqli:
<?php
$default_columns = array('About', 'ContactInformation', 'Others', 'Home');
if(isset($_GET['page']) && in_array($_GET['page'], $default_columns)) {
$return_value = array();
$page = $_GET['page'];
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = "SELECT $page FROM general";
$query = $db->query($sql);
while($row = $query_fetch_assoc()) {
$return_value[] = $row[$page];
}
echo implode(' ', $return_value);
}
?>
I have a script that rotates some images from their current position, there are 4 available rotations(positions) of the image and they are present by the values 0,1,2,3. My problem is that I need two variables from the database in my AJAX call to make this happen. I need the rotation and the src. My PHP currently look like this; Please notice the query where I take out rotation and src.
<?php
$item_number = -1; //This value is -1 in order to make the list start on 0
$rowsize = 12;
$itemArray = array();
$finalArray = array();
$results = 0;
for ($i = 0; $i < $rowsize; $i++) {
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, rotation, src, name FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE house_room1.ref_id = ?');
$stmt->bind_param('i', $i
);
if ($stmt->execute()) {
$stmt->bind_result($z, $rotation, $src, $name);
while($stmt->fetch()) {
$results = 1;
$itemArray['number'] = $item_number;
$itemArray['name'] = $name;
$itemArray['ref_id'] = $z;
$itemArray['rotation'] = $rotation;
$itemArray['src'] = $src;
array_push($finalArray, $itemArray);
}
}
else {
echo 'Something went terribly wrong' . $mysqli->error;
}
$stmt->close();
$item_number++;
}
if($results == 1){
aasort($finalArray,"ref_id");
foreach($finalArray as $arr){
echo '<li id="item-' . $arr['number'] . '" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $arr['name'] . '
<img class="rotate" id="img_'.$arr['number'].'" src="images/house/other/settings.jpg" onclick="rotateObject(this)" alt="'. $src.'">';
}
}
//create a function for sorting
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
?>
It then makes an AJAX call to this file:
function rotateObject(e)
{
//e is handler which contains info about the item clicked. From that we can obtain the image id.
//since the id are of the form img_123(some number), we need to extract only the number.
var img_id = e.id.split("_")[1];
var xmlhttp;
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)
{
var getEle = document.getElementsByClassName('item' + img_id)[0];
var imagePath ="images/house/objects/stone_chair_1.png"; //This has to be
getEle.src = imagePath + xmlhttp.responseText;
}
}
xmlhttp.open("POST","database/update_settings_rotate.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("item_id="+encodeURIComponent(img_id));
}
This code is then supposed to have the imagePath equal to src. and then the rotation after it, but I don't know how I can get the src for that specific image from the database query made in the PHP file.
Any suggestions or advice on how I can pass that value? Thanks in advance.
One way to pass variables from php to javascript is:
<script>
var myJavascriptVariable = <?php echo $myPhpVariable; ?>
</script>
Hope this help you