jquery adding attributes to multiple select drop-downs - php

I have code (edited, after Brad Christie suggestions):
drupal_add_js('
jQuery(document).ready(function(){
jQuery("#selFinishes option").each(function(index) {
if (jQuery(this).val() == ' . $filter_color . ') {
jQuery(this).attr("selected","selected")
}
})
});
', "inline");
And it sucessfully adds "selected" attribute ($filter_color is added via PHP) to the selected value. But when i target multiple select fields like this:
drupal_add_js('
jQuery(document).ready(function(){
jQuery("#selFinishes option").each(function(index) {
if (jQuery(this).val() == ' . $filter_color . ') {
jQuery(this).attr("selected","selected")
}
})
jQuery("#selThemes option").each(function(index) {
if (jQuery(this).val() == ' . $filter_theme . ') {
jQuery(this).attr("selected","selected")
}
})
});
', "inline");
Both of loops fail to work!
Thanks for tips!

The code above is apparently mixed javascript and php, but it not possible to tell what might be wrong with it. You should check (by viewing source in the browser) whether the resulting javascript code is what you intended. If possible post the resulting javascript here.

My educated guess is that the resulting JavaScript is invalid when it's output. Guessing by the variable names ($filter_color & $filter_theme) one (or both) of them is/are most likely a string making the test if (...val() == string) fail which in terns make the entire block of JavaScript result in a syntax error and fail entirely.
Try changing your output to encase the value in a string (maybe something like the following):
[snip].val() == "' . $filter_theme . '") {[/snip]
Notice I added double quotes on either side of the variable before and after the PHP concatenation. This should fix the syntax would should intern make it work again.
Again, too little information in your question but this would be my guess at the solution

Related

output value of json array and then sent another get request with the values

i am really new to stackoverflow and actually dont have any clue about php.
I have a json array which looks like
[{"betreff":"h"},{"betreff":"VS Code fehlt"}]
i´ve created (copied :D) a foreach loop
to output the "h" and "VS Code fehlt"
function display_array_recursive($json_rec){
if($json_rec){
foreach($json_rec as $key=> $value){
if(is_array($value)){
display_array_recursive($value);
}else{
echo '<a href="#" onClick="test("'.$value.'")">';
}
}
}
As we can see now the "h" and "VS Code fehlt" parts are being outputted as links. I want to make it so that whenever I click on the link a new get requests should be sent out with the giving value.
function test($value){when pressed = send new file_get_contents request to localhost/api/ticket/{$value}}
i hope i could describe good enough what i want.
Thanks in advance, please inform me if anything is unclear
You can't use PHP to make GET requests like that (unless you use a hidden IFRAME, as far as I know). You need to use JavaScript for that, using any of those APIs (if you're using vanilla JavaScript):
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Example:
<script>
function test(url)
{
fetch(url);
}
</script>
<?php
function display_array_recursive($json_rec)
{
if (!$json_rec) {
return;
}
foreach($json_rec as $key=> $value){
if (is_array($value)) {
display_array_recursive($value);
continue;
}
echo '<a href="#" onClick="test(\''
. htmlspecialchars(
$value,
ENT_QUOTES|ENT_HTML5,
'UTF-8'
)
. '\')">Text</a>';
}
}
Notice the function display_array_recursive is escaping the HTML. It's also using ' (single quote) for the test arguments. It's already using " (double quote) for the element attribute values.
I suggest you to read:
How do I run PHP code when a user clicks on a link?
https://www.delftstack.com/howto/php/onclick-php/
https://johnmorrisonline.com/prevent-xss-attacks-escape-strings-in-php/
https://stackoverflow.com/a/3996696/4067232
https://betterprogramming.pub/refactoring-guard-clauses-2ceeaa1a9da

Data is UTF-8, Ajax is returning some characters incorrectly

I have spent a lot of time searching the web and seeing a lot of similar answers, but cannot find anything that works for my situation.
I spent some time converting my MySQL database to UTF-8 from latin1 (the default). I emptied the tables (truncate), and re-imported the data from a text file. I have set the headers for my pages to use the meta tag to UTF-8:
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
And that's being used everywhere. When I read data via PHP and output it into forms, and such, the data appears correctly, text like: Königstadt appear as one might hope. Saving them (update set ...) they seem to be okay, because when I re-read them from the data the display in the form is correct. (The display in PHP Admin shows "Königstadt", which is weird, but when I read the data it seems to be correct ... -- I am hoping this is some oddity of PHPAdmin)
Where everything seems to be falling down on me is my Ajax code, when I retrieve data via PHP using Ajax. The following is a relatively simple routine that calls a PHP program to generate the option tags for an SELECT:
function get_branches()
{
// numeric values that need to be passed to the
// routine (so we show the correct item selected)
var region = document.getElementById("search_region").value;
// the code in load_branches needs this, but ...
var branch = document.getElementById("search_branch").value;
$.ajax
({
type: "POST",
url: "<?php echo $Roster_html_RootPath; ?>lookups/load_branches.php",
data: {
'region' : region,
'local_branch' : branch
},
//cache: false,
success: function(data)
{
// load contents of DIV tag with id of branchoptions:
$("#branch_options").html(data);
} // end success
}); // end ajax call
}; // end function get_branches()
}); // end document.ready ...
Most of the records returned are fine. However the one shown above (Königstadt) looks like: Königstadt in the HTML Select that is returned.
I have been trying to find a solution, such as setting contentType for Ajax, here are things I have tried:
contentType: "application/x-www-form-urlencoded;charset=utf-8",
This one doesn't seem to make any difference at all. Nothing changes.
contentType: "application/text; charset=utf-8",
(or application/json)
This kills the values being passed to the PHP file -- the data array doesn't seem to get there, because I get errors from PHP:
Notice: Undefined index: region in C:\xampp\htdocs\Heralds\Roster\lookups\load_branches.php on line 32
Notice: Undefined index: local_branch in C:\xampp\htdocs\Heralds\Roster\lookups\load_branches.php on line 33
I am at a complete loss how to return the values correctly. I need versions for both text or html (where I return an html table or the option tags as here), but I also need to use the json array for some of my code to return the values correctly. None of them seem to work properly with UTF-8 encoded data. I have been working on this for some time now, and am very frustrated. The explanations I am seeing are not working or in some cases not making sense ...
PHP lookups/load_branches.php
<?php
// if session has not started:
session_start();
// load some basic configuration, including relative paths
// and variables needed ...
include_once( "../includes/configuration.php" );
// data connection
include_once( $Roster_RootPath . "includes/connect.php");
// values from Ajax code:
$region = $_POST["region"];
$local_branch = $_POST["local_branch"];
// open the roster_branches table and get list
if( $region > 0 ) // check only needed for find_by_branch.php
{
$branch_statement = "select * from roster_branches where region=" . $region . " order by local";
}
else
{
$branch_statement = "select * from roster_branches order by local";
}
// first, get the data from the table:
$branch_result = mysqli_query( $connect, $branch_statement );
if( !$branch_result )
{
$out = "";
$out .= "<div class='alert alert-danger'>";
$out .= "<p><b>Error in SQL statement ...</b><br />";
$errornum = mysqli_errno( $connect );
$out .= "MySQL Error Number: " . $errornum . "<br />";
$out .= "MySQL Error: " . mysqli_error( $connect ) . "<br />";
$out .= "SQL Statement: " . $branch_statement . "</p>";
$out .= "</div>";
echo $out;
die;
}
else
{
$out = "";
// create select:
$out = "<select class='form-control' id='local_branch' name='local_branch'>\n";
// need the blank option:
$out .= " <option value=0 selected></option>\n";
while( $branch_row = mysqli_fetch_array( $branch_result ) )
{
$id = $branch_row["rb_id"];
$local = $branch_row["local"];
$selected = "";
if( $local_branch == $id )
{
$selected = " selected";
}
$out .= "<option value=" . $id . $selected . ">" . $local . "</option> \n";
}
$out .= "</select>\n";
echo $out;
} // we have something
?>
my MySQL database to UTF-8 from latin1 (the default).
1) I used "utf8_unicode_ci". 2) I have no idea what "multibyte safe functions" you're talking about. I use mysqli_real_escape_string() when reading data from $_POST, and the usual mysqli_query() and so on functions
This is the cause of your issue.
There are 3 main places to work to correct this:
1)
You need to enable true UTF-8 (4-byte) in MySQL so that data stored in your SQL is stored as the correct UTF-8 characters. by universally using collations and character sets with the utf8mb4_ prefix.
2)
To ensure data from your application/PHP is saved correctly you then need to ensure that the data is passed to MySQL as UTF-8 4-byte characters by setting the connection character set to full (4-byte) UTF-8 in your PHP:
$mysqliObject->set_charset('utf8mb4'); // object oriented style
mysqli_set_charset($connect, 'utf8mb4'); // procedural code style
3)
Finally; you need to ensure that any processing PHP does with the resulting data is multi-byte aware; by using the mbstring set of functions.
Most notably:
mb_http_output() — Detect and convert HTTP output character encoding
mb_internal_encoding() — Set PHP's internal character encoding
So your top of each PHP page should look like this before any browser output)
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
Then if you do anything with str_<whatever> functions (and some others) you know it won't break you strings before they're output to the browser (ajx in this case).
If you can't use mbstring functions for any reason then check out here [how to install them](http://www.knowledgebase-script.com/kb/article/how-to-enable-mbstring-in-php-46.html
).
Please also review this excellent Q&A has helped you at all?
Further reading about solving the MySQL side of things can be found here.
ö is "Mojibake" for ö. See "Mojibake" in Trouble with UTF-8 characters; what I see is not what I stored .
But the real problem probably happen when you converted from latin1.
The tables needed to be converted via ALTER TABLE .. CONVERT TO CHARACTER SET utf8mb4. Any other technique is likely to make a mess.
Any connection to MySQL needs to be specify utf8mb4.

Un-escaping characters when using jQuery.post()

I'm making a site where users can submit some code which is then received by a php script and stored in a file on the server. I am using the jQuery $.post() method to send the code to the php script. The problem I have is that when I do this jQuery escapes any single quotes, double quotes or backslashes with a backslash. This means when the code is then retrieved from the file it contains unwanted backslashes and wont execute properly. How can I un-escape these characters whilst making sure i don't effect anything in case the users code contains a wanted escaped character. Example below:
Users code:
var someText = 'Don\'t';
jQuery that submits this:
$.post("/submit.php", {id: 123, code: {main: "var someText = 'Don\'t';", foo: "bar"}}).done(function(data) {
if (data === 'success') {
// Do something.
}
}
PHP script that saves it to file:
foreach($_POST['code'] as $file => $content) {
if (ctype_alnum($file)) {
file_put_contents("/code/" . $_POST['id'] . "/" . $file, $content);
}
}
Resultant file that gets stored on the server:
var someText = \'Don\\\'t\';
The solution to this turned out to be much simpler than I anticipated and I realized this as soon as I posted but I'll leave the question here for future reference.
All I needed to do was to modify the PHP script to use the stripcslashes method to remove the unwanted escape characters at the server's end. Modified PHP code below:
foreach($_POST['code'] as $file => $content) {
if (ctype_alnum($file)) {
file_put_contents("/code/" . $_POST['id'] . "/" . $file, stripcslashes($content));
}
}

how to load specific files/urls based on a database query

I am trying to alter a piece of code that will allow me to position an image left, right or centred.
I have been able to create radio buttons that populate a table on the database but now I want to pull that information out and create an IF statement that will then open a specified page depending on the result.
For example, If I choose the 'right' radio button, this will then populate the database with the id and the 'right' value. I then want to pull the value from the database so if the value is 'right' the newsitem2.php page will load.
This is the code I have in order to do this:
if ("" . $tnrow['newsimage'] . "" == "none") {
}else {
$radio="SELECT imageposition FROM newsimage";
if ("$radio" == Centre) {
<p class='newsmore'> <a href='newsitem3.php?i=" . $tnrow['niid'] . "'>Read More</a></p>
}
if ("$radio" == Right) {
<p class='newsmore'> <a href='newsitem2.php?i=" . $tnrow['niid'] . "'>Read More</a></p>
}
if ("$radio" == Left) {
<p class='newsmore'> <a href='newsitem.php?i=" . $tnrow['niid'] . "'>Read More</a></p>
}
However, it is not loading each page it just loads the 'newsitem' page with the image on the left. is there any reason for this?
You don't make any call to your database, so $radio is just a String when you use it for now (representing the query) ; you have to send this query to your database (using for example a wrapper like PDO), and then get the result back.
Another thing, are Right, Left, ... constants or enum values ? 'Cause if they're not, you also have to put them into quotes, in order to be interpreted as String
There are a lot of weird instructions in your code, you should probably get more informations on PHP, 'cause you doesn't really seem to understand the concepts for now. Get a good tutorial/book, and you'll see that what you want to do is pretty easy when you got the ideas behind. ;)
Your IF's are all wrong. I assume the value of $radio is a string?
if ("$radio" == Centre) {
Should be
if ($radio == 'Centre') {
And so on for all the others

how to change these lines of javascript from scriptaculous to jQuery syntax

I am rewriting a helper class which was originally built on top of Scriptaculous. I am moving to jQuery - however, I am stuck on a couple of lines, that I need help with (see below): Note: the javascript code is interpersed with php variables (the sigils being a dead give away)
Statement 1
'new Insertion.Before(\'' . $updateContainer . '\', new Element(\'div\', {\'id\': \'' . $updateContainer . '_loading\', \'class\': \'' . $spinnerClass .'\'})); $(\'' . $updateContainer . '_loading\').innerHTML="<h4>Loading ...</h4>";',
Statement 2
'$(\'' . $updateContainer . '_loading\').remove();'
I'll assume that the $updateContainer is ID of the HTML element that contains the loading message.
Then, I'd write the Statement 1 like this:
$statement1 = sprintf('$(\'#%1$s\').html(\'<div id="%1$s_loading" class="%2$s"><h4>Loading</h4></div>\');', $updateContainer, $spinnerClass);
And the second statement is:
$statement2 = sprintf('$(\'#%s_loading\').remove();', $updateContainer);
If you have a lot of AJAX communication and need the 'Loading' often, it might be better to hide() it so you can just show() it later instead of creating the HTML again.
Statement1 would be uset to create the loading element, Statement2 with hide() instead of remove() to hide it and Statement3 with show() instead of hide() to show it again.

Categories