Javascript and PHP (window.open) - php

So, in my website, I have a news system which has an option to edit and delete the news the administrator desires.
Well, I got the edit part right by using:
href="noticiaEditarForm.php?id_noticia=<?php echo $id ?>">Editar</a>
And then a $_GET on the other page.
However, this is not how I desire my editing window.
Therefore, I have been exploring a way to send the PHP variable that contains the primary key for the news table (MySQL) to a popup window, using JavaScript. But that's just the thing, it will only return the 1st value it gets from the query... (i.e If I click to edit the 3rd article, it edits my 1st one. Always.)
Here is my current code:
<div class="noticias">
<?php
include('conn/conn.php');
mysql_select_db($bd, $conn);
$resultado = mysql_query("SELECT * FROM noticia INNER JOIN user ON noticia.id_user=user.id_user ORDER BY id_noticia DESC");
while ($linha = mysql_fetch_array($resultado)) {
echo "<h1>" . $linha['titulo'] . "</h1>";
echo "<i>Posted by " .$linha['username']. " on " . "<y>" . $linha['data'] . "</y>" . "</i>";
echo "<p>";
echo $linha['texto'];
$id = $linha['id_noticia'];
if (isset($_SESSION['admin'])) {
?>
<div class="noticiasOpcao">
Editar
<a onclick="return confirm('Are you sure?')" href="noticiaApagar.php?id_noticia=<?php echo $id ?>">Apagar</a>
</div>
<?php
}
}
?>
<script language="javascript">
function open_win_editar() {
window.open (
"noticiaEditarForm.php?id_noticia=<?php echo $id; ?>",
"Editar notícia",
"location=1, status=1, scrollbars=1, width=800, height=455"
);
}
</script>
<?php mysql_close($conn); ?>
</div>
My point is to then use another query to get the title and text of the article to display on an WYSIWYG editor.
Can anyone point out my flaw?

This code:
<script language="javascript">
function open_win_editar() {
window.open ("noticiaEditarForm.php?id_noticia=<?php echo $id; ?>", "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
Is happening outside of the PHP while loop, so the value of $id will be the last value that was set to $id in the loop. So the JavaScript code will always open the same link.
If you need the code within the PHP loop to specify the $id value for the JavaScript, then you can pass it as an argument to the JavaScript function. Something like this:
<script language="javascript">
function open_win_editar(targetID) {
window.open ("noticiaEditarForm.php?id_noticia=" + targetID, "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
So the code rendering the anchor tags in the loop would pass the argument like this:
Editar
The rendered output would then contain the record-specific $id value on each a tag to be used by the JavaScript code on the client.

<script language="javascript">
function open_win_editar() {
window.open ("noticiaEditarForm.php?id_noticia=<?php echo $id; ?>", "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
This is only rendered once, probably with the last ID. You need to figure out a structure so you can pass a different ID to it based on what article you clicked to edit.

The id of the piece to edit is only updated within the while loop and never outside of it.
To use it as you wish you should use a parameter for the open_with_editar function:
<script language="javascript">
function open_win_editar(id) {
window.open ("noticiaEditarForm.php?id_noticia="+id, "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
Now you only have to update the onclick event and hand over teh respective id:
<div class="noticiasOpcao">
Editar
That should work.
Regards
STEFAN

Related

$.ajax script not pulling php data into div

I've spent the last couple of days wrestling with a .hover script that posts data to a php script then retrieves related data from a database.
Posting id data to the details.inc.php page is working fine. An alert in the script retrieves and show's the data correctly.
The problem arises when i try to include the data in a div, nothing seems to happen. Firefox show's the script to be executing and retrieving the correct id info as it should.
I don't know where from here. I've tried all i can, but my understanding of java is limited
Thanks for any help in advance.
A mouse over function executes and retrieves the id from an image
<img src="#" class="latest" id="id_retrieved_from_DB">
id is then passed through jquery and ajax which retrieves data linked to id from details.inc.php, the data retrieved should then be included in the "details" div
<script type="text/javascript">
//Mouse over
$(function(){
$('.latest').hover(function() {
id = $(this).attr('id');
$.ajax({
cache: false,
url: "details.inc.php",
data: 'hovered_id='+id,
success:function(data){
alert(data);//showing data correctly
//not working here
$("#details").load('details.inc.php', data);
}
});
return false;
}
});
</script>
details.inc.php
<?php require_once('../../Connections/userauthentication_conn.php'); ?>
<?php
require_once('../../includes/session_remap.inc');
require_once('../../includes/tNG_functions.inc.php');
?>
<?php
$KTColParam1_rsDetails = "0";
if (isset($_GET["hovered_id"])) {
$KTColParam1_rsDetails = (get_magic_quotes_gpc()) ? $_GET["hovered_id"] : addslashes($_GET["hovered_id"]);
}
mysql_select_db($database_userauthentication_conn, $userauthentication_conn);
$query_rsDetails = sprintf("SELECT tbl_entries.id_ent, tbl_entries.country_ent, tbl_entries.date_ent, tbl_entries.title_ent, tbl_entries.subject_ent, tbl_entries.description_ent, tbl_entries.image_ent, tbl_entries.url_ent FROM tbl_entries WHERE (tbl_entries.id_ent=%s) ORDER BY tbl_entries.date_ent DESC ", $KTColParam1_rsDetails);
$rsDetails = mysql_query($query_rsDetails, $userauthentication_conn) or die(mysql_error());
$row_rsDetails = mysql_fetch_assoc($rsDetails);
$totalRows_rsDetails = mysql_num_rows($rsDetails);
?>
<!-- Details -->
<a href="<?php echo $row_rsDetails['url_ent']; ?>" title="Go to <?php echo $row_rsDetails['title_ent']; ?>">
<?php
//show if file exists
if (file_exists("../../images/entries/" . $row_rsDetails['id_ent'] . "__img.jpg")) {
?>
<img src="../../images/entries/<?php echo $row_rsDetails['id_ent']; ?>__img.jpg" width="70" height="70">
<?php
}
//end show if file exists
?>
<p class="seriesName"><?php echo $row_rsDetails['subject_ent']; ?></p>
<h4 class="programTitle"><?php echo $row_rsDetails['title_ent']; ?></h4>
</a>
<!-- End -->
<?php
mysql_free_result($rsDetails);
?>
Why are you doing a second ajax call?
If you already have the data available in javascript, you can replace:
$("#details").load('details.inc.php', data);
with:
$("#details").html(data);
if $("#details") is in the script page and that's the div you wish to display the result, you could use only load:
//Mouse over
var id = $(this).attr('id');
$("#details").load('details.inc.php', 'hovered_id='+id, function(data){alert(data);});
Or you could use $.get()
Jquery manual
The POST method is used if data is provided as an object; otherwise, GET is assumed.
And your PHP script uses get.

Calling a javascript function by using onClick in a hyperlink

I have been looking online, but I have failed to find a direct answer to my question:
Can you use onClick for a tags?
In other words can you do this (note echoed through php)?
echo "\n";
I tried to run this, but when I click on the link, my counter function is not being called.
The rest of my code snippet:
echo "<script type=\"text/javascript\" src=\"src\jquery\jquery.js\">\n";
echo "function counter(){\n";
echo "alert(\"HELLO WORLD!\");\n";
echo "}\n";
echo "</script>\n";
echo "\n";
Although that should work, it's better practice not to bind events inline. I would suggest looking into addEventListener and for older versions of IE, attachEvent. More information on these can be found in a topic here: Correct usage of addEventListener() / attachEvent()?
If you wait for the window to be ready, you ensure that the element is on the page and defined for you to access it.
window.onload = function(){
//add any event listeners using the above methods in here
}
Example:
<script>
window.onload = function(){
var t = document.getElementById("test");
t.addEventListener("click", sayHi, false);
function sayHi(){
alert("Hi");
}
}
</script>
<div id="test">test</div>​
According to your above echo statements, if you are determined to make it work that way then you can try this:
echo "<script type='text/javascript' src='src/jquery/jquery.js'></script>\n";
echo "<script>\n"
echo "function counter(){\n";
echo "alert('HELLO WORLD!');\n";
echo "}\n";
echo "</script>\n";
echo "<a href='#' id ='loginbutton' onClick='counter()'></a>\n";
notice that I closed the script tag including jQuery and added a new opening tag right below it.
EDIT:
Script tags that reference external resources (via the src attribute)
are no longer able to execute script embedded within the tag itself.
Read more here
Made a little Demo code, Note that the function fires and then the href is followed. You can turn this off with JS by returning false.
<script type="text/javascript">
function counter() {
alert("do something here")
var FollowHref_Or_Not = false;
// true would simply follow the href after the function is activated
return FollowHref_Or_Not;
}
</script>
Test Link
To add more context to the comments above, here's a working example. Where I put the HTML comment about simulating an echo, just put your PHP echo line. Also note that I added a return false; This prevents the default link click behavior from executing. Since your href is "#" it would modify your URL to put "#" in the URL so if you used your browser back button you'd still be "stuck" on the same page.
http://jsfiddle.net/6pEbJ/
<html>
<head>
<script type="text/javascript">
function connect()
{
alert('connected!');
}
</script>
</head>
<body>
<!-- simulated echo result here -->
Testing
</body>
</html>

Printing a javascript variable in php echo

To clarify:
I have an echo statement as follows:
$striptitle .= ' - <a onclick="getnewurl();" href="'.SGLink::album($aid). '">'. $namek .'</a></h1>
<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-via="jb_thehot" data-text="Pictures of '. $hashfinal .'" teens>Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';
echo $striptitle ;
The onclick does this:
<script type="text/javascript">
function getnewurl()
{
var url = document.URL;
alert( url );
}
</script>
What I need is essentially to add the my anchor tag a data-url="INSERT_VAR_URL_HERE"
Is that possible?
Let me know if this isn't clear enough
Thanks!
Edit: to clarify, the alert in the function is only for testing. What I need is to be able to use the variable obtained in the function, in the same $striptitle variable.
My problem is that the url changes with AJAX, and the twitter button's data-url does not get updated. I was hoping to be able to get the new url by getting it everytime it is clicked. If there are other ways to do that, I'm open to suggestions!
Why not pass it as an argument?
$striptitle .= " - <a onclick=\"getnewurl('URL-HERE');\"...>";
Then in your script:
<script>
function getnewurl(url) {
alert(url);
}
</script>
Building on #Kolink's answer one way to not repeat the url in two places you could generate the link as:
<a onclick="getnewurl(this);" href="...">
then your JS could look like:
function getnewurl(link) {
link.setAttribute('data-url', location.href);
}
EDIT apparently jQuery.data doesn't update the dom properly, but setAttribute does

Javascript: dynamic var names with php?

Probably a dead simple and idiotic question (I'm totally new to javascript):
I have this code that loads a new post by clicking on a "next" or "back"-link. The clicks variable is used to scroll up and down in the sql-limit-statement (using the swapContent function), means you move backward or forward in the database by clicking the links. It works easy and perfectly:
<script type="text/javascript">
var clicks = -1;
function increase()
{
clicks++;
return false;
}
function decrease()
{
clicks--;
return false;
}
</script>
<div id="<?php echo $post['id'].'-multipost'; ?>">
<?php include('views/posts/_postmultipost.php'); ?>
</div>
<div id="<?php echo $post['id']; ?>-next" class="rightbutton" style="display:block;">
next
</div>
<div id="<?php echo $post['id']; ?>-back" class="leftbutton" style="display:none;">
back
</div>
The only problem: As you see I have several posts (post-IDs). But the javascript var "clicks" is always the same. How can I add the post-id into the javascript variable name "clicks", well, something like this :
var <?php echo $post['id']; ?>-clicks = -1;
Of course it doesn't work this way, but I have no clue how to manage it. Any advice? Sorry for this stupid question...
Thanks for your help!
UPDATE
Ok, got the solution: Bryan was right!!!
Changed the code to:
<script type="text/javascript">
var clicks = {};
clicks['<?php echo $post['id']; ?>'] = -1;
function increase()
{
clicks['<?php echo $post['id']; ?>']++;
return false;
}
</script>
The javascript in html stays as it is:
>
Clicks is now an object and will output the following in the swapContent-Function:
count: Array
(
[80] => 0
)
In php you would access the value like this:
foreach($count as $key=>$value) { $count = $value }
In javascript it seems to work a bit different like this:
for(x in clicks)
{
var clicks = clicks[x];
}
Seems to work perfectly now, thanks for your help!!
I'm not incredibly familiar with PHP, so I don't know about php echo. However, would using an object work?
var postClicks = {};
postClicks['<?php echo $post['id']; ?>'] = -1;
As far as I understand you are trying to get this:
var something-clicks = -1;
But in JS something-clicks is an expression - substraction of two variables.
Name tokens in JS cannot contain '-' in contrary with CSS.
You have a syntax error:
onmousedown="increase(); javascript:swapContent('next', clicks, '<?php echo $post['id']; ?>', '<?php echo $post['title']; ?>', '<?php echo $_SESSION['user']['id']; ?>');"
that javascript: is the problem. That property is expected to contain raw JS, and that token is invalid. the javascript used as a protocol is for use on the href property of an a tag.
Other than that, it looks alright. Just type clicks in the JS console of your browser to get the current value returned. Or add console.log('clicks:', clicks); to your function so that the result is logged out on each click.

i need help to pass mysql/php variable to javascript?

im trying to get the id of the picture the user selected to rate with the onclick,however it will only alert "null". when the user selected the div tag, it will alert the id. i want to display the id. i can build off of this and then implement ajax to rate the picture. But, i need help on getting the id of the picture the user selected.
<?php
mysql_connect('localhost','root','');
mysql_select_db("ajax");
$query="SELECT * FROM xxxx";
$result= mysql_query($query);
while($row= mysql_fetch_array($result)){
$rating=$row['ID'];
echo "<img src='".$row['filepath']."'>";
echo "<br>";
echo "<div id='".$row['ID']."' value='".$row['ID']."' onclick='getrating();'>Likes: ".$row['Likes']."</div>";
echo "<br>";
}
im trying to get what picture the user selected to rate.
?>
<script type="text/javascript" >
function getrating(){
var x= document.getElementById("<?php echo $row['ID']; ?>");
alert(x)
}
</script>
A few things that you should do:
Try giving an id which starts with a letter for example, when writing the HTML code use:
echo "<div id='img" . $row[ 'ID' ] . "'></div>"
Note that i've added a prefix 'img' to the div's ID.
You have to pass the correct index to the javascript function because you are drawing the divs in a list but not the javascript function:
onclick='getrating( " . $row[ 'ID' ] . " );'
Now the javascript function will get the correct image ID when called upon clicking the respective DIV element.
Change the javascript function to:
<script type="text/javascript" >
function getrating( id )
{
var x = document.getElementById( "img" + id );
alert( x );
}
</script>
onclick="getrating(this.value);"
That code will pass the current value attribute of the div to the function you made in JavaScript. Be sure to add a parameter to your function to receive the data.
Easy.
Change this:
echo "<div id='".$row['ID']."' value='".$row['ID']."' onclick='getrating();'>Likes: ".$row['Likes']."</div>";
to this:
echo "<div id='".$row['ID']."' value='".$row['ID']."' onclick='getrating(this.value);'>Likes: ".$row['Likes']."</div>";
And this:
function getrating(){
var x= document.getElementById("<?php echo $row['ID']; ?>");
to this:
function getrating(row_id){
var x= document.getElementById(row_id);
You should put your event handler inside image like this:
<img src="" onclick="getrating(this.value)">
And you function should be like this:
function getrating(row_id){
x = document.getElementById(row_id);
alert(x);
}

Categories