javascript adding to string not wokring - javascript

Im trying to get a link where I have to add a countrycode to a link.
Im trying this:
var link = "http://restcountries.eu/rest/v1/alpha?codes=" + myData;
Where myData is defined by:
var div = document.getElementById("dom-target");
var myData = div.textContent;
dom-target:
<div id="dom-target" style="display: none;">
<?php
$output = $_GET['id'];
echo htmlspecialchars($output);
?>
</div>
Where the $_GET['id'] is a code like FR or NL.
but for some reason when I console.log() it, it comes out with the link and underneath that I see the countrycode, indicating that it hasnt added the countrycode to the link.
Am I doing something wrong here?

var link = "http://restcountries.eu/rest/v1/alpha?codes=" + myData.trim();
the .trim() will remove and spaces
if that doesn't work you can try myData.replace(/(\r\n|\n|\r)/gm,""); this will remove line breaks.
good luck

Related

Formatting PHP text for use in Javascript variable

I am having a tough time covering all areas with special chars that could possibly break the variable in JavaScript. So for context I am pulling information from a database and then echoing it to JavaScript variable that will display the data which is text that has been entered by a user and stored to the table.
The php variable is $letter see the code below that I used to try to keep it from breaking
$letter = $order["letter"];
$letter = str_replace("'", "\'", $letter);
$letter = str_replace("\"", "\"", $letter);
$letter = str_replace("\r\n", "\\n",$letter);
Below is the line of code where I attempt to decode it so that it will display in an html format
$(".fa-eye").click(function () {
//clear pager html
$(".pager").html('');
$("#text-pager").html('<p class="text-left prevdescription"></p>');
//clear pager html
var parentTd = $(this).parent().parent('td');
var letterContent = parentTd.find('#letterTxt').val();
var pagerHtml = '<p class="controls"><a class="tp-control-arrow-left unactive"><span><</span></a><a class="tp-control-arrow-right"><span>></span></a><ul class="pager"></ul></p>';
$(".prevdescription").html(letterContent.replace(/\r?\n/g, '<br/>'));
It produces the output in the image below...what am I missing?
You may write me down in history\nWith your bitter, twisted lies,\nYou may tread me in the very dirt\nBut still, like dust, I\ ............. This is what it outputs. not showing all of the content.
Use json_encode(), it converts a PHP value to the equivalent JavaScript literal.
<script>
var letter = <?php echo json_encode($order['letter']); ?>;
</script>

AJAX data returned is not correct

I have this posts.php where it uses a unique id to view different contents. For example: posts.php?id=1 will display all data on my table which has an id of 1, id = 2 for 2 and so on...
This id is held on a php var $post_id on each page and in order to send this php variable on my jquery/javascript, I used:
<div id = "dummy_disp" style = "display: none;">
<?php echo htmlspecialchars($post_id); ?>
</div>
<div id = "real_commentsno"></div>
( I know, not the best way to do it but it works)
It connects to my js:
var commentid = document.getElementById("dummy_disp");
var commentidreal = commentid.textContent;
$.ajax ({
type:"GET",
url:"php/post_comments.php",
data:'comid='+commentidreal,
success: function(data){
$("#real_commentsno").html(data);
}
});
I have this post_comments.php where it has:
$cc_g_postid = htmlentities($_GET['comid']);
$cc_postid = mysqli_real_escape_string($con,$cc_g_postid);
$cc_sql = "SELECT * FROM comments WHERE postuniqueid = '$cc_postid' ";
$cc_result = mysqli_query($con,$cc_sql);
$cc_count = mysqli_num_rows($cc_result);
echo $cc_count;
When I try to view the post_comments.php alongside with the attached url var: ?comid=1 the page displays 2 which is correct since post id=1 on my table has only 2 comments. But when I go to my posts.php the ajax displays 0, not 2. I tried looking at the console, there were no errors.
Is there anything I missed or misdo? Also, post_comments.php is on located on mypage/php/post_comments.php whereas posts.php is located on mypage/posts.php ( i dunno if this is necessary info but maybe the url is jamming it or something? )
The problem is that the DIV has newlines and spaces around the ID number. You need to remove all this whitespace.
var commentidreal = commentid.textContent.trim();

Strings with double quotes in html input field displaying as &quot

Im getting data from sql and using php to generate javascript for an edit button for each entry. The edit interface uses a text input in a form. When the generated edit button is clicked, the text within this field is set to equal the name of the entry from sql.
This works fine in all cases expect when the name contains double quotes ("), in which case the quotes are replaced with &quot in the text field.
The php genertaed javascript is below:
function editButton($suffix,$name)
{
echo "<button class=\"edit\" onclick=\"editMode$suffix()\">Edit</button>";
echo "<script>
<!--
function editMode$suffix(){
document.getElementById(\"title\").innerHTML = \"Edit Artist\"
var main = document.getElementById(\"main\");
main.style.display = 'none';
var edit = document.getElementById(\"edit\");
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById(\"editInput\").value = \"$name\";
document.getElementById(\"artEdit\").value = \"$name\";
}
-->
</script>";
}
The $name variable is sanitized via htmlentities() before being passed to the function. Without doing so, the edit interface for entries with quotes will not even display.
I found this which sounds like the same issue but no solutions (https://code.google.com/archive/p/embeddedjavascript/issues/19) :/
IF anyone has a solution or can point out some stupid thing im doing thats causing this it would be very appreciated. At this point im going to have to just disable database entry for double quotes and limit to singles.
Just change all the double-quotes in the JavaScript portion to single-quotes, then use addslashes() on the $name variable:
function editButton($suffix, $name)
{
$name = addslashes( html_entity_decode($name) );
echo "<button class='edit' onclick='editMode$suffix()'>Edit</button>";
echo "<script>
<!--
function editMode$suffix() {
document.getElementById('title').innerHTML = 'Edit Artist'
var main = document.getElementById('main');
main.style.display = 'none';
var edit = document.getElementById('edit');
edit.style.display = 'block';
//Set the input of the edit interface to be equal to the current name
document.getElementById('editInput').value = '$name';
document.getElementById('artEdit').value = '$name';
}
-->
</script>";
}
*Also added html_entity_decode() to converts the entities back to their initial state. Consider removing the htmlentities() altogether, in which case, you can remove the html_entity_decode() from the above script.

javascript function with 2 arguments is not working

DEscription :
I have a php script that displays the div on an html page
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id)"></div>';
Now when I click on this div the star_it function gets called and it works perfect...
The problem
I want to pass another argument in the star it function .. like this
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,'.$each_status['regno'].')"></div>';
or a simple alphabet if any like star_it(this.id,s)
but when I do so the function stops working as when I click the div the function does not gets called ....
I dont know why I am stuck and now my star rating system does not work... I have absolutely no idea what is wrong
Anyone ??
You should modify your string quote's like this :
<?php
$status = "second test";
echo '<div class="star_box" id="'.$id.'" onmousedown="star_it(this.id,'."'".$status."'".');" >Hello</div>';
?>
<script>
function star_it(foo1,foo2){
console.log(foo1);
console.log(foo2);
}
</script>
This example works for me.
So with your code :
<?php
echo '<div class="star_box" id="'.$id.'" onmousedown="star_it(this.id,'."'".$each_status['regno']."'".');" >Hello</div>';
?>
Here you go
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,\''.$each_status['regno'].'\')"></div>';
you forget to add \' before and after your string , the JS engine on the browser will treat your string as an undefined variable and the function will not work because of that .
//my English is not so good.
Try
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,\"'.$each_status['regno'].'\")"></div>';

how can I add a copy of a div with jquery?

I have a div containg a few dynamically generated dropdowns.
I want to clone this and add it underneath the original. The code for the original is:
<div id="subjectselectiondiv" style="width:inherit;">
<h4>Select the subjects that you are able to tutor</h4>
<div id='choices'>
<script type="text/javascript">
var doc = document.getElementById("choices");
var subj_div = document.createElement('div');
subj_div.setAttribute('class', 'selectSearchBar');
subj_div.innerHTML = '<select id="level'+counter+'" name="level'+counter+'" class="selectSearchBar"><?php echo "<option>Level</option>"; while($row = mysqli_fetch_array($result_level, MYSQLI_ASSOC)){echo "<option value=".$row['id'].">".$row['level']."</option>";}?></select><div id="subject'+counter+'" style="display:inline;">sBar2</div><div id="topic'+counter+'" style="display:inline;">sbar3</div>';
doc.appendChild(subj_div);
</script>
Add another subject
</div>
I thought that the function Repeat() would work with:
function Repeat(){
counter++;
$('#choices').clone().appendTo('#subjectselectdiv');
event.preventDefault();
}
but this isnt working - am I missing something?
Thanks
Name mismatches:
<div id="subjectselectiondiv" style="width:inherit;">
^^^^^^
$('#choices').clone().appendTo('#subjectselectdiv');
^^^
What you're attempting to append to doesn't exist. Most likely if you'd bothered checking your javascript console, you'd have seen the warnings/errors about the non-existing element.

Categories

Resources