How do I insert variable inside an echo string and function call? - javascript

I checked out this post but no luck :
PHP - concatenate or directly insert variables in string
The suspect in question: showUser(3, change, " . $name . ");'> $name breaks the code; the second $name does work. The variable does not get passed to the function.
I have been testing for hours to get this to work! It seems like it should work.
I tried checking other places in the application to see what the problem could be and this seems to be the culprit.
<?php
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = "<p onClick='DoIt(); showUser(3, change, " . $name . ");'>" . $name . "</p>";
} else {
$hint .= "\n" . "$name";
}
}
}
?>

JavaScript probably is requiring $name to be quoted.
$hint = "<p onClick='DoIt(); showUser(3, change, \"" . $name . "\");'>" . $name . "</p>";
Escaping the quotes like this will cause them to appear in the JS function call.
Quotes are often a thorny problem when mixing PHP, JavaScript and HTML on one line.

You can quote your variable like this
if ($q !== "") {
$q = strtolower($q);
$len = strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$name = "'" . $name . "'";
$hint = '<p onClick="DoIt(); showUser(3, change, ' . $name . ');">' . $name . '</p>';
} else {
$hint .= "\n" . "$name";
}
}
}
}

Related

Argument #5 ($port) must be of type ?int, string given - error when setting up a form on laravel 9

I am relatively new to backend, so I've encountered an error and I have no idea where to even start.
Everything works totally fine locally, I receive the response email from the SMTP server, no problem. As soon as it goes live, when I click submit on my form, I get this error:
XHRreload?k=6LffRmckAAAAAA8fhqt3YfyTgWOpGuYRrlxTdSKy XHRform
2 requests
36.9 kB transferred
{,…}
exception: "TypeError"
file:
"/var/www/sites/fantasy-road/docs/releases/2023-02-09-23.37/vendor/symfony/mailer/Transport/Dsn.php"
line: 28
message:
"Symfony\Component\Mailer\Transport\Dsn::__construct(): Argument #5 ($port) must be of type ?int, string given, called in /var/www/sites/fantasy-road/docs/releases/2023-02-09-23.37/vendor/laravel/framework/src/Illuminate/Mail/MailManager.php on line 174"
trace:
[{,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…}, {,…},…]
I'm at a loss as how to even begin debugging this, and I have no idea what files to provide to give further insight as to what is causing the issue.
The last file I edited was my FormController:
namespace App\Http\Controllers;
use App\Enquiry;
use Request;
use Redirect;
use Validator;
use App\Form;
use Mail;
use Illuminate\Support\Str;
class FormController extends Controller {
const contact_gallery_form_id = 7;
public function submit() {
$input = Request::all();
$form_id = $input['_form_id'];
$form = Form::where('id', $form_id)->first();
if($form === null){
\Log::error('Form doesn\'t exist');
die("Form doesn't exist");
}
$return_url = config('forms.' . $form_id . '.return_url');
$form_url = config('forms.' . $form_id . '.form_url');
//my_time and my_name are honeypot fields
unset($input['_token'], $input['_form_id']);
$validator = Validator::make($input, config('forms.' . $form_id . '.validation'));
unset($input['my_name'], $input['my_time'], $input['recaptcha_validation']);
if ($validator->fails()) {
\Log::channel('warnings')->info('Invalid inputs for Form ID: ' . $form_id . '. Errors are : ' . $validator->errors());
return abort(500, 'Invalid inputs: ' . $validator->errors());
} else {
if (\Request::has('file')) {
$name = date("Ymd_His") . '_' . Str::slug(pathinfo(\Request::file('file')->getClientOriginalName(), PATHINFO_FILENAME), '-') . '.' . \Request::file('file')->getClientOriginalExtension();
\Request::file('file')->move(public_path() . '/assets/files/uploads/user', $name);
$input['file'] = url('/assets/files/uploads/user/' . $name);
}
$email_content = '';
$fields = ['publication-date_1', 'title_1', 'issue-number_1', 'value_1', 'publication-date_2', 'title_2', 'issue-number_2', 'value_2', 'publication-date_3', 'title_3', 'issue-number_3', 'value_3', 'publication-date_4', 'title_4', 'issue-number_4', 'value_4', 'publication-date_5', 'title_5', 'issue-number_5', 'value_5', 'publication-date_6', 'title_6', 'issue-number_6', 'value_6', 'publication-date_7', 'title_7', 'issue-number_7', 'value_7', 'publication-date_8', 'title_8', 'issue-number_8', 'value_8', 'publication-date_9', 'title_9', 'issue-number_9', 'value_9', 'publication-date_10', 'title_10', 'issue-number_10', 'value_10'];
foreach ($input as $field_key => $field_val) {
if (!in_array($field_key, $fields)) {
if($field_key == 'file'){
$email_content .= '
<br /><b>' . str_replace('_', ' ', ucfirst($field_key)) . ' :</b><br />' . $field_val . '<br />';
} else {
$email_content .= '
<br /><b>' . str_replace('_', ' ', ucfirst($field_key)) . ' :</b><br />' . $field_val . '<br />';
}
}
}
$email_content .= '
<br /><b>Date :</b><br />' . date('l jS \of F Y h:i:s A') . '<br />';
$email_content .= '<table>
<thead>
<tr>
<th>Publication Date</th>
<th>Title</th>
<th>Issue Number</th>
<th>Value</th>
</tr>
</thead>
<tbody>';
for ($i = 1; $i <= 10; $i++) {
$publication_date = $input['publication-date_' . $i] ?? '';
$title = $input['title_' . $i] ?? '';
$issue_number = $input['issue-number_' . $i] ?? '';
$value = $input['value_' . $i] ?? '';
if (!empty($publication_date) || !empty($title) || !empty($issue_number) || !empty($value)) {
$email_content .= '<tr>
<td>' . $publication_date . '</td>
<td>' . $title . '</td>
<td>' . $issue_number . '</td>
<td>' . $value . '</td>
</tr>';
}
}
$email_content .= '</tbody></table>';
$enquiry = new Enquiry();
$encoded_post = json_encode($input);
$enquiry->ip = $_SERVER['REMOTE_ADDR'];
$enquiry->post = $encoded_post;
$enquiry->form_id = $form_id;
$enquiry->save();
if($form->id == static::contact_gallery_form_id){
$gallery = \App\Gallery::findOrfail(\Request::get('contact_gallery'));
$notification_emails = $gallery->email;
} else {
$notification_emails = $form->notification_emails;
}
$emails = explode(';', str_replace(' ' , '', $notification_emails));
try {
$data = array();
$data['subject'] = 'Website form submission : ' . $form->name;
$data['content'] = $email_content;
$data['title'] = $form->name . ' Form Submission';
if (isset($input['name']) && isset($input['email'])) {
$data['name'] = $input['name'];
$data['replyto'] = $input['email'];
}
foreach ($emails as $email) {
$data['notify'] = $email;
Mail::send('emails.form-notification', $data, function($message) use ($data) {
if(isset($data['replyto']) && isset($data['name'])){
$message->to($data['notify'])->replyTo($data['replyto'], $data['name'])->subject($data['subject']);
} else {
$message->to($data['notify'])->subject($data['subject']);
}
});
}
} catch(Exception $e) {
\Log::error('Error sending start email | ' . $e . '');
}
return 'ok';
}
}
}
Are there any issues here that could cause this?
I have tried debugging the issue, but unable to locate the source.
My own stupidity was the cause of this issue.
As this was my first large scale project that I have worked on, on my own, doing both the rear and front end, I did not realise that the sensitive data was not pushed in the form of the .env
The cause of the issue was simple. The live .env file was empty, so to fix this I used SSH to get into the live files, and manually updated the .env (which you're supposed to do.) This fixed it.

Get day names in Russian

The day names on my site are in English.
How can I get the day names in Russian?
In JavaScript I tried to replace Tuesday->Вторник in code but it is not working.
Code:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$url = 'http://api.sypexgeo.net/xml/'. $ip .'';
$xml = simplexml_load_string(file_get_contents($url));
$loc_array = array($xml->ip->city->lat,$xml->ip->city->lon);
$loc_safe = array();
foreach($loc_array as $loc){
$loc_safe[] = urlencode($loc);
}
$loc_string=implode(',', $loc_safe);
$json = file_get_contents('http://api.wunderground.com/api/232323***/satellite/webcams/forecast/q/' . $loc_string . '.json');
$obj = json_decode($json, true);
?>
<?
$html .= "</h2><table cellpadding=4 cellspacing=3><tr>";
foreach ($obj['forecast']['simpleforecast']['forecastday'] as $arr) {
$html .= "<td align='center'>" . $arr['date']['weekday'] . "<br />";
$html .= "<img src='http://icons-pe.wxug.com/i/c/k/" . $arr['icon'] . ".gif' border=0 /><br />";
$html .= "<font color='red'>" . $arr['high']['celsius'] . '°C' . " </font>";
$html .= "<font color='blue'>" . $arr['low']['celsius'] . '°C' . "</font>";
$html .= "</td>";
}
$html .= "</tr></table>";
echo $html;
?>
<script type="text/javascript">
window.onload=function(){
//I try, but not replace
$("td:contains('Tuesday')").html("Вторник");
};
</script>
As an option, you can change the call to wunderground API. Include language settings /lang:xy. Something like this:
https://api-ak-aws.wunderground.com/api/8dee7a0******/satellite/webcams/forecast/lang:RU/units:metric/v:2.0/q/CWEW.json
You can try defining a JSON object like:
days = { "name of the day": "name of the day in Russian" }
Then instead of using $arr['date']['weekday'] use days[$arr['date']['weekday']].
Note: I don't know the php syntax actually, but something like that should work.

How to dynamically poputate title and meta tags with php and/or javascript

I'm trying to replace my title tag and meta description dynamically using parameters from a search query in PHP. They keep showing up blank, but if I echo the $title or $desc inside the original PHP (first set) of tags, it appears fine. There is no header.php file for reference.
<?php
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
list($chuck, $keep) = explode('?', $url);
$patterns = array();
$patterns[0] = 'foo';
$patterns[1] = 'bar';
$patterns[2] = '123';
$replacements = array();
$replacements[0] = 'good ';
$replacements[1] = 'bad ';
$replacements[2] = 'ugly ';
$mytitle = "my cool " . $keep . " title tag";
$mydesc = "my cool " . $keep . " meta " . $keep . " description";
$title = str_replace($patterns, $replacements, $mytitle);
$desc = str_replace($patterns, $replacements, $mydesc);
//echo $title . "</br>";
//echo $desc . "</br>";
?>
<title><?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { some other title"; }?></title>
<meta name="description" content="<?php echo $desc; ?>">
Alternatively, would a javascript/php mashup like this work?
<script>
document.title = <?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { some other title"; }?>;
</script>
You need to amend your title alteration code's else slightly to include echo "
<title><?if (strpos($url, 'foo=') !== false) { echo $title . "</br>"; } else { echo "some other title"; }?></title>
Other than throwing a parse error as is this seems to work fine for me.

PHP Database Query: How to return the results from a while loop to a Javascript Variable?

I have a php query like so:
<?php
$query = "SELECT * FROM " . $usertable . " ORDER BY fname;";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo '<option value="' . $row['pkid'] . '">' . $row['fname'] . ' ' . $row['lname'] . '</option>';
}
?>
Within this same .php file I have some javascript. All I would like to do is return $row['fname'] as a a javascript variable.
Is this possible?
If you want to output the PHP variable in a JavaScript variable you could do something like this -
echo '<script>var name+' . $row['pkid'] . ' = ' .$row['fname'] . ';</script>';
This would give you a uniquely named variable for each row.

unable to retrieve selected array values [php]

To generate the stockroom drop down list
function einv_generateStockrmSelectDropdown($Stockrm,$field,$dropdown) {
//connect to database
base_connectDatabase();
echo "<select id=\"stockrm\" name=\"".$field."[]\" multiple=\"multiple\" style=\"align:left\" class=\"form-control\">";
if (isset($Stockrm) && ($Stockrm != "")) {
$stockrmname = einv_getStockrmDetail($Stockrm);
echo "<option value=\"". $Stockrm ."\">". $stockrmname['einv_stockrm_name'] ."</option>";
} else {
$Stockrm = 0;
}
$getStockrmSQL = base_executeSQL("SELECT * FROM einv_stockroom WHERE einv_stockrm_id<>" . $Stockrm . " ORDER BY einv_stockrm_name");
while ($Stockrmdata_row = base_fetch_array($getStockrmSQL)) {
if (base_num_rows($getStockrmSQL)!= 0) {
echo "<option value=\"".$Stockrmdata_row['einv_stockrm_id']."\">".$Stockrmdata_row['einv_stockrm_name']."</option>";
}
}
echo "</select>";
echo "<script src=\"../terms_base/js/jquery.multiple.select.js\"> </script>";
//Input some codes to split the dropdown and make it into the setSelects. By default, the first time = AutoSelectAll
if(isset($dropdown) && ($dropdown != "")) { //dropdown = 1;2;3
$SDDArrays = explode(";", $dropdown);
$countTrap0 = count($SDDArrays);
$drop = "$('#stockrm').multipleSelect(\"setSelects\", [";
$counting = 1;
foreach ($SDDArrays as &$value) {
if ($countTrap0 != $counting) {
$drop .= "'". $value . "',";
} else {
$drop .= "'". $value . "'";
}
$counting++;
}
$drop .= "]);\n";
} elseif (isset($dropdown)) { //dropdown=
$drop = "$('#stockrm').multipleSelect(\"uncheckAll\")";
} else { //
$drop = "$('#stockrm').multipleSelect(\"checkAll\")";
}
echo "<script>\n";
echo "$(function() {\n";
echo "".$drop."";
echo "});\n";
echo "$(\"#stockrm\").multipleSelect({ onClose: function() {
document.getElementById('search').click();
}});\n";
echo "$(\"#stockrm\").multipleSelect();\n";
echo "</script>";
//close the database
base_closeDatabase();
}
//This function is use to add new stock room
//code = stock room code
//name = stock room name
//desc = stock room description
//remark = stock room remark
//cat = stock room category
add stockroom function
function einv_addStockrm($code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
base_executeSQL("INSERT INTO einv_stockroom (einv_stockrm_code, einv_stockrm_name, einv_stockrm_desc, einv_stockrm_remark, einv_stockrm_cat)
VALUES ('" . $code . "', '" . $name . "', '" . $desc . "', '" . $remark . "', '" . $cat . "')");
base_addTransactionLog('Manage Stock Room', 'Add',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/stockrm_list.php";';
echo '</script>';
//close the database
base_closeDatabase();
}
Edit stockroom
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
File name: add_Stockroom.php and edit_stockroom.php
I have a dropdown list named Stockroom where it displays an array of values.
Example:
Stockroom
[A]
[B]
[C]
When user clicks on [A], it will display relevant data fields that [A] possess (appears below stockroom ddl).
And as user clicks on [B], there is an onchange function that will then show [B] data fields (fields in A is deleted and replaced with B).
I am able to add the initial values however, as i want to edit and change the stockroom from [A] to [B] which will result in a whole new data to be stored, i am unable to do so.
Any ideas?
I believe i have to amend my edit stockroom function where i require a set of coding such as
If the array is selected, i have to delete existing data and add new data in accordance to the selected ID.

Categories

Resources