I ran into an issue for which I cannot find the answer, I rarely ask questions here, but I am rather stumped. Any assistance shall be appreciated.
This is the PHP that receives the Ajax call.
<?php
session_start();
$_SESSION["my_data"] = $_POST['action'];
$DB_HOSTNAME = 'localhost';
$DB_USERNAME = 'username';
$DB_PASSWORD = 'password';
$link2 = mysqli_connect($DB_HOSTNAME,$DB_USERNAME,$DB_PASSWORD) or die('Unable to establish a DB1 connection');
mysqli_select_db($link2, '$DB_USERNAME');
$orderQuery = mysqli_query($link2, "SELECT * FROM table WHERE id='".$_SESSION['my_data']."'");
$orderQuery = mysqli_fetch_assoc($orderQuery);
$orderInfo = "
<table class='table table-striped'>
<tbody>
<tr>
<td>#: </td>
<td>". $_SESSION['my_data'] ."</td>
</tr>
<tr>
<td> Full name: </td>
<td>". $orderQuery['firstname'] . " " . $orderQuery['lastname'] ."</td>
</tr>
<tr>
<td> Address: </td>
<td> ". $orderQuery['shipping_address_1'] ."<br> ". $orderQuery['shipping_city'] . " " . $orderQuery['shipping_zone'] . " " . $orderQuery['shipping_postcode'] ." </td>
</tr>
<tr>
<td> Card Expiry Date Month: </td>
<td> 08 </td>
</tr>
</tbody>
</table><br>
";
echo $orderInfo/* . $_POST['action']*/; ?>
And this is the script that makes the call.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var myWindow;
function myFunction() {
myWindow = window.open('', '_blank');
myWindow.document.write("<link rel='stylesheet' type='text/css' href='stylesheet.css'>");
var orderNum;
orderNum = document.getElementsByClassName('summary_value')[0].innerHTML;
orderNum = orderNum.replace("#", "");
$.ajax( { type : 'POST',
data : {'action':orderNum},
url : 'process.php',
success: function ( data ) {
myWindow.document.write( data );
},
error: function ( xhr ) {
alert( "error" );
}
});
myWindow.document.write("<br>");
myWindow.document.write(document.getElementById("payInfor").innerHTML);
}
</script>
<button onclick='myFunction()' class="btn btn-default">Print Pay Info</button>
It could be a simple issue, but I can't see it.
I know the Ajax is working because it displays some of the information ($_SESSION['my_data']), so I am thinking it's something with my SQL statements, but the syntax looks correct.
At first glance i think that mysqli_select_db($link2, '$DB_USERNAME'); here is the error.
it must be mysqli_select_db($link2, $DB_USERNAME); or mysqli_select_db($link2, $DB_NAME);
mysqli_select_db() expects parameter one to be the connection and parameter two to be the database name. In your case you are passing '$DB_USERNAME'. So your code will look to connect to database named '$DB_USERNAME' because of the single quotes. Change it to the database name instead. Either $DB_NAME or 'database_name' should work. While in development mode, try enabling error_reporting(E_ALL) to catch errors like this.
try to replace this mysqli_fetch_assoc with mysqli_fetch_array
and ($link2, "SELECT * FROM table WHERE id='".$_SESSION['my_data']."'")
with ($link2, "SELECT * FROM table WHERE id=".$_SESSION['my_data']."")
note: remove single quote (' ') for id
Related
This is about a script that I've used for a while now. I have a website where this code still works without any errors (I even copied the code from that project's scripts, because why reinvent the wheel once you've already done it right?), but for some reason now on my new project, I'm getting some very nasty errors! I'd post an image directly on here, but I don't have enough reputation for that it seems. XD https://rellawings.com/error.JPG The important details of what's in the image left are below:
Highlighted Above: var res = JSON.parse(response);
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
success https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/:2045
jQuery 6
<anonymous> https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/:2038
dispatch jQuery
h https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:6
f https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:15
c https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:6
c https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/ line 507 > injectedScript:5
jQuery 8
<anonymous> https://rellawings.com/books/2/Superluminal/1/1.01-What-is-Love?/:2027
1.01-What-is-Love:2045:28
I know that the problem is with this particular line/function: var res = JSON.parse(response);
But this feels so out of left field to suddenly have problems with it while coding my project. It's very strange since it's always worked flawlessly and still does on my other site. This AJAX script is simple and easy to use... at least until you get errors while coding with it in 2022. XD
The jQuery version used is the same as my other site. The only difference is that I'm not including jQuery UI, which frankly should not make a difference, right? The newest version is commented out, because I've tried switching them. But that doesn't change anything that I can see.
This is included in the header html script.
<!---<script src="https://code.jquery.com/jquery-3.6.0.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
And here's the 'problematic' AJAX script that's always worked for me:
<script>
$("#postbtn").click(function(event){
var b_id = "'.$b_id.'";
var c_id = "'.$c_id.'";
var parent = "0";
var message = $("#commentsbox").html();
console.log("Book ID: '.$b_id.'");
console.log("Chapter ID: '.$c_id.'");
console.log("Is A Child?: " + parent);
console.log("MSG: " + message);
jQuery.ajax({
method: "POST",
url: "post-comment.php",
data: {b_id: b_id, c_id: c_id, parent: parent, message: message},
dataType: "text",
cache: false,
success: function(response){
var res = JSON.parse(response);
if (res.return === "1") {
$("#allcomments").html(res.contentrefresh);
} else {
$("#errorbox").html("There was a problem and your comment could not be posted.").show().delay(8000).fadeOut();
}
}
});
});
</script>
And lastly, here's the AJAX PHP script. I'm not 100% sure it's error-free, but I can't get any response from the AJAX under the circumstances.
With this, I'm experimenting to see if I can feed back html formatted content to refresh the comments on the page. If so, I can implement a refresh button that does the same thing, just updating the divs. I've reduced the shared code because if I put up everything that generates comments (and shouldn't be relevant to resolving this issue), this request for help would be longer than necessary.
<?php
include "dbcon.php"; include "functions.php"; session_start();
if($_SESSION['theme'] == "dark"){
$bordercolor = "#DEDEDE";
}
if($_SESSION['theme'] == "light"){
$bordercolor = "#000000";
}
if($_SESSION['theme'] == "sepia"){
$bordercolor = "#5F4B32";
}
$commentsQ = "SELECT * FROM `comments` WHERE `b_id` = '$b_id' && `c_id` = '$c_id' && `parent` = '0' ORDER BY COALESCE(NULLIF(`upvote` - `downvote`,'0'), `updated`) DESC LIMIT 10";
$commentsR = $conn->query($commentsQ);
$commentsnum = $commentsR->num_rows;
$contentrefresh = '';
while($comment = $commentsR->fetch_assoc()){
$likes = $comment[upvote] - $comment[downvote];
if($likes == 0){
$likes = "";
}else{
$likes = " · '.$likes.' Upvotes";
}
$time = date('m/d/y',$comment['updated']);
$contentrefresh .= '
<div style="width:98%;padding-top:10px;padding-bottom:10px;">
<table style="width:100%;min-height:160px;">
<tr>
<td rowspan="3" valign="top" align="center" width="75px" style="max-width:80px;min-height:160px;padding-right:15px;">
<img src="https://rellawings.com/avatars/'.$comment[uiden].'/'.$comment[avatar].'" class="avatars" title="'.$comment[uname].'" alt="'.$comment[uname].'" />
</td>
<td style="font-size:1.3em;text-align:center;height:50px;" valign="top">
<span style="float:left;font-weight:bold;">'.$comment[uname].'</span><span style="float:right;">'.$time.'</span>
</td>
</tr>
<tr>
<td style="padding-bottom:15px;font-size:1.3em;line-height: 1.8;height:80%;" valign="top">
'.parseemoji($comment[message]).'
</td>
</tr>
<tr>
<td style="font-size:1.3em;cursor:pointer;">
<a id="reply-'.$comment[id].'" title="Reply" alt="Reply">Reply</a>'.$likes.' · <span class="material-icons" style="position:relative;top:4px;">thumb_up</span> · <span class="material-icons" style="position:relative;top:4px;">thumb_down</span>
</td>
</tr>';
/* If There Are Any Replies */
$comments2Q = "SELECT * FROM `comments` WHERE `b_id` = '$b_id' && `c_id` = '$c_id' && `parent` > '0' ORDER BY `updated` DESC LIMIT 10";
$comments2R = $conn->query($comments2Q);
$comment2 = $comments2R->fetch_assoc();
$commentsnum2 = $comments2R->num_rows;
if($comment['id'] == $comment2['parent']){
while($comment2 = $comments2R->fetch_assoc()){
$likes = $comment2[upvote] - $comment2[downvote];
if($likes == 0){
$likes = "";
}else{
$likes = " · '.$likes.' Upvotes";
}
$time = date('m/d/y',$comment2['updated']);
$body .= '
<div style="width:98%;padding-top:10px;padding-bottom:10px;">
<table style="width:100%;min-height:160px;">
<tr>
<td rowspan="3" valign="top" align="center" width="75px" style="max-width:80px;min-height:160px;padding-right:15px;">
<img src="https://rellawings.com/avatars/'.$comment2[uiden].'/'.$comment2[avatar].'" class="avatars" title="'.$comment2[uname].'" alt="'.$comment2[uname].'" />
</td>
<td style="font-size:1.3em;text-align:center;height:50px;" valign="top">
<span style="float:left;font-weight:bold;">'.$comment2[uname].'</span><span style="float:right;">'.$time.'</span>
</td>
</tr>
<tr>
<td style="padding-bottom:15px;font-size:1.3em;line-height: 1.8;height:80%;" valign="top">
'.parseemoji($comment2[message]).'
</td>
</tr>
<tr>
<td style="font-size:1.3em;cursor:pointer;">
<a id="reply-'.$comment2[id].'" title="Reply" alt="Reply">Reply</a>'.$likes.' · <span class="material-icons" style="position:relative;top:4px;">thumb_up</span> · <span class="material-icons" style="position:relative;top:4px;">thumb_down</span>
</td>
</tr>
</table>
</div>
';
}
}
$contentrefresh .= '
</table>
</div>
';
}
$b_id = htmlentities(trim($_POST['b_id']), ENT_NOQUOTES);
$c_id = htmlentities(trim($_POST['c_id']), ENT_NOQUOTES);
$parent = htmlentities(trim($_POST['parent']), ENT_NOQUOTES);
$message = htmlentities(trim($_POST['message']), ENT_NOQUOTES);
if(empty($parent)){
$parent = "0";
}
if(isset($_SESSION['uname'])){
$uiden = $_SESSION['uiden']; $uname = $_SESSION['uname']; $avatar = $_SESSION['avatar'];
$posted = time(); $updated = $posted;
$update = "INSERT INTO `comments` (`b_id`, `c_id`, `parent`, `uiden`, `uname`, `avatar`, `message`, `posted`, `updated`)
VALUES ('$b_id', '$c_id', '$parent', '$uiden', '$uname', '$avatar', '$message', '$posted', '$updated')";
if ($conn->query($update) === TRUE) {
$response = ['return'=>'1', 'contentrefresh'=>$contentrefresh];
echo json_encode($response);
}else{
$response = ['return'=>'0', 'contentrefresh'=>$contentrefresh];
echo json_encode($response);
}
}
?>
I really hope that I don't have to implement some needlessly complex pure javascript solution to get the job done. What is going on with jQuery and it's lovely simplification of the language?
This is the first time I've tinkered with .htaccess and doing symlinking. So my site uses fake directories so it doesn't show ugly ?mode=etc etc... But this comes with some caveats. XD I have to link directly to MANY resources. Including AJAX php scripts! LOL! How hilarious! This actually got rid of the error and now I have a response! It'll be up to debugging the AJAX PHP script next. '^^
Thanks for replying! I think our conversation led to my getting a moment of eureka here.
jQuery.ajax({
method: "POST",
url: "https://rellawings.com/post-comment.php",
data: {b_id: b_id, c_id: c_id, parent: parent, message: message},
dataType: "text",
cache: false,
success: function(response){
console.log(response);
var res = JSON.parse(response);
if (res.return === "1") {
$("#allcomments").html(res.contentrefresh);
} else {
$("#errorbox").html("There was a problem and your comment could not be posted.").show().delay(8000).fadeOut();
}
}
});
I have a question that might have another answer than what I'm thinking of doing.
So, I have a text area that is populated by a DB. I'm allowing the users use it as a notepad and whatnot.
Some of these notes can get pretty big and potentially exceed the URL Character limit. I also have to encode (I'm using encodeURIComponent ) the strings which cuts into the amount of characters too.
I thought the best way would be to convert the text area into a file and then post the file towards my handler php file where it gets uploaded into the db and whatnot. I'm not certain how to do this with JQuery/Javascript or if there was another way to handle this.
Thanks in advance!
-- Table Code --
echo "<table class='content' id='quick-notes-list'>
<tr style='border-bottom:2pt solid #DFEFFC'>
<td colspan='2'>Note Name</td>
<td>Last Updated</td>
</tr>";
$i = 0;
while ( $Notes = mysql_fetch_array($getNotes) )
{
$style = ( $i % 2 ? 'ui-state-default row' : 'altrow row'); $i++;
$noteDate = date("M, d Y", strtotime($Notes['updated']));
$noteTime = date("g:i a", strtotime($Notes['updated']));
echo "
<tr class='noteName' onMouseOver=\"this.className='ui-widget-header row'\" onMouseOut=\"this.className='$style'\" >
<td valign='top'>
<a href='{$Notes['note_id']}'></a>
<b>{$Notes['note_name']}</b>
<br />
<i id='summary{$Notes['note_id']}'>" . substr($Notes['note_body'], 0, 150) . "...</i>
</td>
<td width='160' valign='top'>" . str_replace(" ", " ", $Contact['name']) . "</td>
<td width='120' valign='top'>
<i>" . str_replace(" ", " ", " {$noteDate} - {$noteTime}") . "</i>
</td>
</tr>
<tr id='note{$Notes['note_id']}' style='display: none' onMouseOver=\"this.className='ui-widget-header row'\" onMouseOut=\"this.className='$style'\">
<td colspan='2'>
<textarea id='note-body-{$Notes['note_id']}'>{$Notes['note_body']}</textarea>
</td>
<td style='text-align: right;'>
<button id='saveNote' value='{$Notes['note_id']}' class='ui-state-focus'>Save</button>
<button id='deleteNote' value='{$Notes['note_id']}' class='ui-state-focus'>Delete</button>
</td>
</tr>
";
}
-- AJAX Function Below --
$('#saveNote').click(function() {
noteID = $(this).attr('value');
newText = encodeURIComponent($('#note-body-' + noteID).val());
$.ajax({
url : "manage-save-quick-notes.php",
type : "POST",
data : data,
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
It's probably not a good idea to have file upload where you don't really need. It will be just a security concern
If you are sending the data through a POST request, the size won't actually be a problem since it's limit is set Server side, on your Apache configs.
To increase the limit POST size limit:
Increasing the maximum post size
I want to call a JavaScript function inside PHP code,This function return a number, the Result for example is : http://localhost/1.php?id=fn(3)
as you see this function cannot be interpreted by the browser I already tried ' ' or " " But I get the same problem, normally I must receive for example http://localhost/1.php?id=3
Any help on this problem would be greatly appreciated! Thank you in advance!
<body>
<script type="text/javascript">
function fn(a)
{
var table = document.getElementsByTagName("table")[0];
var res=table.rows[a].cells[0].innerHTML;
return res;
}
</script>
<table class="table " id="tableId">
<?php
$bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
$reponse = $bdd->query('SELECT * from jeux_video');
while ($donnees = $reponse->fetch()){
echo "
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
";
?>
<td id="td1"><?php echo $donnees['ID']?></td>
<td><?php echo $donnees['nom']?></td>
<td><?php echo $donnees['possesseur']?></td>
<td><?php echo $donnees['prix']?></td>
</tr>
<?php } $reponse ->closeCursor(); ?>
</table>
</body>
The string you're putting on the href won't be parsed as a javascript expression, but just as a string.
You need to output a valid javascript statement for the fn call to execute:
echo "<tr onclick=\"location.href='1.php?id=' + fn(".$donnees[ID].")\">";
This will output:
<tr onclick="location.href='1.php?id=' + fn(3)">
PHP runs on the server, and Javascript on the client. That's the rule. If you want PHP to output a value anywhere in your document, you need to do it with PHP:
echo "<tr onclick=\"location.href='1.php?id=' + fn(" . $donnees[ID] . ")'\">"; // ...
As it is, this is likely the exact markup that is being output:
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
Which, to Javascript, makes no sense.
This doesn't do what you think it does:
location.href = '1.php?id=fn(3)'
JavaScript isn't going to automatically evaluate code inside of a string. You have to execute the code itself and concatenate its result to the string. Something like this:
location.href = '1.php?id=' + fn(3)
I'm trying to make an HTML table dynamically. I'm just testing with sample, but It's not working as well as I expected. So, I'm asking this question. Let me show you this simple table, it is MySQL database. and I create HTML table.
What I want to do is when I click some node, like a '250', this number will be editable. Edited data will be saved to the MySQL database. So I use the contenteditable="true" attribute value, and when this node loses focus, run some JavaScript function that new data will be saved.
But... It's not working well. Honestly I don't know what the problem is exactly. Google chrome spit up "Uncaught Syntax Error, Unexpected token } ", But I couldn't find what the actual problem is. I'm newbie on this... Could you some guys help me?
sample.html
<body>
<?php
require_once("db_connect.php");
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
?>
<table border="1" style="border-collapse:collapse;">
<thead>
<tr><th>name</th><th>price</th></tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc()){
echo
"<tr>
<td contenteditable='true' onBlur='saveToDatabase(this,'name','$id')'>{$row['name']}</td>
<td contenteditable='true' onBlur='saveToDatabase(this,'price','$id')'>{$row['price']}</td>
</tr>\n";
}
?>
</tbody>
</table>
<script>
function saveToDatabase(editableObj, column, id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
</body>
</html>
saveedit.php
<?php
require_once("db_connect.php");
$result = mysql_query("UPDATE test SET ". $_POST["column"]. " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);
?>
You made it contenteditable but PHP needs an parameter. For example
<input type="text" name="parameter">
will send as $_POST['parameter'] but in your code <td> elements don't have a name. So PHP doesn't know if there is a parameter or what name is.
Maybe you can write your own editable function in Javascript like this:
function doTextArea(i) {
document.getElementById(i).innerHTML="<input type='text' name='table_value'>ssss.";
}
and your php loop can be like this ( I assume it is for loop):
for ($i = 1; $i <= 10; $i++) {
echo
"<tr>
<td><p id=$i ondblclick='doTextArea($i)'> sadasdasdasd</p></td>
</tr>\n";
}
I'm working on a MySQL update form and struggle to make a drop down selectbox that will autofill the rest of the form with data from mysql. Basically its a table that consist of users and their credentials. When updating a second table with this form i want to be able to select the username from a drop menu and let that selection autofill the rest of the credentials before moving on to the rest of the form.
Here is some of the code for setting up the select and input:
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" />
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" /> </td>
</tr>
And then some javascript
<script>
function populateData()
{
//alert('in populateData');
y = document.getElementById("selectbox");
document.getElementById("klasse").value = [y.selectedIndex];
document.getElementById("klubb").value = [y.selectedIndex];
}
</script>
The result here is a number in the <td>klubb and <td>klasse based on my selection in the drop menu.
How can i connect the arrays with that index number in the javascript so that it will show the actual data from the array ?
I've been seeking an answers for a few days now but can't find anything that answers my question.
Thanks for any help!
Well you can use AJAX for that.
For a tutorial on how to use AJAX and PHP script with Mysql This can help you.
First you need to create a PHP script that will gather the data you need for filling up the forms.
Setup the AJAX to be triggered everytime you choose something in your Drop Down List and pass its value on the PHP script you created.
On your AJAX script configure it to call the PHP script you created for retrieving the data (a value will be thrown in this script based on your drop down list).
Once you receive a response from your AJAX call just use a simple Javascript to fill up the forms based on the data your received.
Another tip is to use JQuery since it is easier for you to setup your AJAX request.
Use AJAX here.
In the populateData() function, use ajax to send the request to retrieve the user credentials & through Javascript, populate your textboxes with the retrieved values.
You could echo the two php arrays as javascript objects, and then access those in your populate function (this is the quick solution). But a better way is to ajax in the actual data
<script>
var klasse = <?=json_encode($klasse)?>
var klubb = <?=json_encode($klubb)?>
</script>
Well you can use Ajax. Make this as your form.
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<div id="some_container">
</div>
Your AJAX request :-
<script type="text/javascript">
$('select').on('change', function() {
var selectedVal = this.value; // or $(this).val()
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?selectedVal="+selectedVal,
dataType: "html", //expect html to be returned
success: function(response){
$("#some_container").html(response);
}
});
});
});
</script>
file.php
<?php
echo '
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" value="$phpValueHere"/>
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" value="$phpValueHere> </td>
</tr>';
?>
In your file.php, get the value of selectedVal via $_GET['selectedVal'] and then extract data from table, after extracting echo the data in those input boxes.