JAVASCRIPT : Parameter Passed Is "Not Defined" - javascript

I'm creating a page that should read data from the database, display it as a table, and allow row-wise editing of the entries (using AJAX calls). Here are brief code snippets where the problem comes -
Javascript:
function editParam(bname, button) {
alert(bname); //this part doesn't happen, the error on console comes up before it
tr = button.parentNode;
while (tr && tr.nodeName.toUpperCase() !== "TR" && tr.nodeName.toUpperCase() !== "BODY") {
tr = tr.parentNode;
}
if (!tr || tr.nodeName.toUpperCase() !== "TR") {
return;
}
//some more code
}
PHP:
//get $row_users['Name']
while ($row_users = mysqli_fetch_array($results)) {
echo "<form method='POST'> //some <tr><td></td></tr>
<button onclick='editParam(".$row_users['Name'].", this)'>Edit</button>
</form>";
}
My data in the column Name is like "B1", "C2", etc.
Error onclick of button : B1 is not defined.
While running the code for other text or numbers, it worked fine. So I understand that my problem has to do with the datatype. However, I do not know how resolve the same.
Any suggestions would be much appreciated, thanks!

You need to add quotes around $row_users['Name'] since otherwise it is interpreted as a JS variable.
"<button onclick='editParam(\"" . $row_users['Name'] . "\", this)'>Edit</button>";

Related

How to use explode function to delimit and display different values

I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.
I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:
The book, El libro
The man, El hombre
The woman, La mujer
etc.
I would like to break these two values into an array and display them in separate places on my web page.
I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
The script that displays the result:
<script type="text/javascript" src="rantex.php?type=1"></script>
Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?
Thank you, and please excuse my noobness.
The following seems unnecessary, since file() will have already removed new line characters:
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
To break your line, you may instead use:
list($english, $spanish) = explode(', ', trim($txt));
It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?
Heres a quick implementation.
// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)
$sentences = explode("\n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) {
return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) {
return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
Now you can let the client handle the rest, with some basic JavaScript.
// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence
[edit]
You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.
// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
var sentences = <?= json_encode($pairs); ?>;
var random = sentences[Math.floor(Math.random() * sentences.length)];
var elspa = document.getElementById('spanish');
var eleng = document.getElementById('english');
elspa.innerText = random.sentence.split(',')[1];
eleng.innerText = random.sentence.split(',')[0];
</script>
Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to #stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.
The .PHP file is like so:
<?php
$f_contents = file('quotes.txt');
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>
On the .HTML page in the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
(function ($) {
$(function()
{
function load_random_data() {
$.get('random_line.php', function(data) {
var data = $.parseJSON(data);
$('#random_english').text(data.eng);
$('#random_spanish').text(data.esp);
});
}
load_random_data();
$('#get_random').click(function(e){
e.preventDefault();
load_random_data();
});
});
})(jQuery);
</script>
This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:
<td id="random_spanish"></td>
<td id="random_english"></td>
Plus as a bonus the coder threw in a nifty button to refresh the json classes:
<input type="button" value="Get random" id="get_random" />
So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.
Thanks again everyone!

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

Read a hard coded csv file and iterate through each entry to detect empty values

I have written a script for iMacro that reads a CSV file to extract numerous login details in order for passwords to be updated. The majority of these login details then also need to be updated on a second website, but in order to do so I need to be able to determine which sites have login details for the second site, and if they do, then run the second part of the iMacro script.
The CSV file I am using is laid out like so;
USERNAME 1 HEADER, PASSWORD 1 HEADER, USERNAME 2 HEADER, PASSWORD 2 HEADER
username1.1, password1.1, username1.2, password1.2
username2.1, password2.1, username2.2, password2.2
username3.1, password3.1, , ,
username4.1, password4.1, username4.2, password4.2
A loop would be used to process one row at a time, with a if statement inside to determine whether or not a empty/null value is present. If the second username or password are empty/null then the second part of the iMacro script would be skipped and the loop incremented.
I've never really used Javascript before, but I've have a bit of a look around and found jQuery-CSV, which looks like it's what I need but I cannot for the life of me get it to work. I also found this, which goes into detail about how to input a file, but it doesn't say how to hardcode it to a local file.
Any help on this would be greatly appreciated.
Thanks!
Here you go
HTML
<textarea id="csv"></textarea>
<button id="run">Run</button>
<div id="result"></div>
JS
$("#run").click(function(){
var result = $.csv.toArrays($("#csv").val());
empty = "";
html = "<table>";
for(i = 0; i < result.length; i++){
html += "<tr>";
for(j = 0; j < result[i].length; j++){
html +="<td>"+result[i][j]+"</td>";
if(result[i][j].trim() == ""){
empty += "cell "+i+" "+j+" is empty";
empty += "<br />";
}
}
html += "</tr>";
}
$("#result").html(html);
$("#result").append(empty);
});
http://jsfiddle.net/4J8Jb/
EDIT:
and to read the csv from a file you can use $.get like so
$.get('/path/to/file.txt',function(data) {
if (data == "ON") {
var result = $.csv.toArrays(data);
....
....
....
} else {
//there is an error reading the file
}
});

How to display delete message in correct table row?

Below is a function where it controls whatever happens after a file has finished uploading in its own table row. Each table row consists of a file input where the user can upload a file and then the name of the file is appended within it's own table row.
If the upload was successful then it displays a successful message, if upload was not successful then it displays a message stating there is an error. But I also have another function within the function where the user can delete a file by clicking on the "Delete" button. The only problem I have is with this line of code:
$(".imagemsg" + counter).html(data);
Let's say that I have 2 table rows, and I delete a file in the first row, the message within .imagemsg should only be displayed in the first row as that was the row the deletion occured, it shouldn't display the message in the first and second row.
Another example is that if I have 4 table rows and I delete the file in the third row, then the message should be displayed in the 3rd row as that is where the deletion has occured.
So my question is what do I need to add to $(".imagemsg" + counter).html(data); so that the message is only displayed within the row the deletion of the file occured and not in all .imagemsg which is in every row?
Below is full code:
function stopImageUpload(success, imagefilename){
var result = '';
var counter = 0;
counter++;
if (success == 1){
result = '<span class="imagemsg'+counter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
var image_file_name = $(this).attr('image_file_name');
jQuery.ajax("deleteimage.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".imagemsg" + counter).html(data);
});
$(this).parent().remove();
});
return true;
}
BELOW IS HTML CODE:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='listImage' align='left'></p>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
I believe that your counter variable will always be 1. So, all your span.imagemsg1 are the same. This is why you get the message in every row. Set the counter outside the function to increment the counter.
I believe that will stop the behavior that you are seeing, but I would like to give a shout out to the other answers as they are giving good advice to cleaning this code up.
Frankly, you should never use unique identifier in the class. Why not use an id or a data-image-count attribute?
In your html code you'll need to add a unique identifier, I would suggest using id. This way when you try to reference the element to add the error message in, it will only find one element. Currently it's looking for the first occurrence of the element with class = "imagemsg". You'll need a way to loop through each "row" and make the id's "imagemgs1", "imagemsg2", etc...Hope it helps.
It would be helpful to be able to see the HTML. Also, I cannot see in your script what you do with the "result" value. At this stage, I personally don't think there is enough info to help satisfactorily you yet.
However, an issue you will undoubtedly see is with your "counter" variable. Maybe that is your problem - hard to tell without the detail I asked for above. Your jQuery.ajax call will complete at some point but the value of "counter" may not be the same as when you called the jQuery.ajax() method. This is because the "counter" variable is being declared in a different scope.
E.g. Look at the code below. It sort of demonstrates your problem with the counter variable. It may look like at the end of 5 seconds it will spit out the numbers from 1 to 10 but it won't. It will spit out the value "10" ten times.
var x = 0;
for (var i = 0; i < 10; i++)
{
x++;
setTimeout(function() { console.log(x); }, 5000);
}
This problem applies to your code as well. You can fix the above by copying the variable value in to a variable of your local scope. E.g.:
var x = 0;
for (var i = 0; i < 10; i++)
{
var newScope = function() {
x++;
var y = x;
setTimeout(function() { console.log(y); }, 5000);
}();
}

JavaScript href onclick not working with Perl

The below is my code. All my button functions are working perfectly, but if I click the link click the value of server should be remembered and the page should be reloaded again with the parameters view and subsys.
But the value for the server is empty when I getting reloaded.
my $server = $q->param('server') ;
my $unit = $q->param('unit') ;
my $bfile = __FILE__ ;
$bfile = `basename $bfile` ;
chomp $bfile ;
print "<form name=\"form1\" action =\"/cgi-bin/$bfile\" onsubmit=\"javascript:onsubmitform(doc_press)\">";
print "<input type=\"hidden\" name=\"server\" id=\"server\">";
print "<input type=\"hidden\" name=\"unit\" id=\"unit\">";
print "\n\n<input type=submit name=view value=\"View\" onClick=\"doc_press=this.value\">";
print "<input type=submit name=save value=\"Save\" onClick=\"doc_press=this.value\">";
print $var{$a}."<a href=\"/cgi-bin/$bfile?view=5&SUBSYS=$subsys\" onClick=javascript:click_page(\"$_\")>CLICK</a>\n" ;
print <<"END_OF_SCRIPT";
<script type="text/javascript">
function onsubmitform(doc_press) {
if (doc_press == "View"){
document.getElementById('unit').value="$unit";
}
else if (doc_press == "Save") {
END_OF_SCRIPT
var x = "$user=$val";
document.cookie=x;
document.getElementById('unit').value="$unit";
}
if (document.getElementById('HTTP_TYPE').value == "post") {
document.form1.method='post';
}
else if(document.getElementById('HTTP_TYPE').value == "get") {
document.form1.method='get';
}
}
function click_page(server){
document.getElementById('server').value=server;
}
</script>
END
When you click on a link (<a href="..."/>), the browser will make a new GET request for the given link, regardless of any forms you might have. This means that your form is NOT submitted; so any value in the form will be lost. For this reason, your onclick handler as posted here is useless.
Sometimes, if you’re really linking to the same page, modern browsers are smart enough to recognize that, and fill in the values you already had. This is only a commodity to users who get frustrated if their values are not kept, and so this doesn't work for hidden fields.
If you want clicking on the link to submit the form, you should either a) use a button, or b) change your onclick handler to submit the form and return false (so that the link isn’t followed):
function click_page(server){
document.getElementById('server').value=server;
document.forms[0].submit();
return false;
}
To make this work correctly, also change the onclick declaration:
CLICK

Categories