Php inside a javascript function? - php

I have a feature on my users inbox that allows users to check/uncheck messages in their inbox that they want to make favourite.
I'm currently testing what happens when a user checks the box (clicks on the image and causes it to go from greyed out to colour meaning the box is checked).
Anyway as you can see from the code below when the box ischecked this url is suppose to be loaded: http://mysite.com/messages/favourite_checked
The message_id of the row the user has checked the box on is suppose to be added onto the end of the url this then loads my controller "messages" and method "favourite_checked" which then passes a variable that grabs the message_id from the url, stores it in a variable then sends it the my model and it is used in a mysql query.
Basically I update the favourites column of my messages table and set it to = 1 where the message_id from url matches the one in the messages table in my database. So yea, where the match is found the "favourite" column in that row is updated to 1. 1 = favourite 0 = not favourite.
Any I just thought I would make it clear what was happening..
My problem is nothing happens when I check the box, nothing is updated so I feel I must be doing something wrong where I try to add the id to the url in the javascript function.
I've tried $(post) also.. nothing happens then also.
Maybe someone can spot it because I really don't know what the problem is.
<script type="text/javascript">
// favourite check box
$('input.favourite:checkbox').simpleImageCheck({
image: '<?php echo base_url()?>images/messages/check.png',
imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
afterCheck: function(isChecked) {
if (isChecked) {
//query to db from php to update favourite number to 1
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
}
// else (!isChecked)
// {
// //query to db from php to update favourite number to 0
// $.get('http://mysite.com/messages/favourite_unchecked');
// }
}
});
</script>

I think your basic problem is some confusion about when the PHP is running vs the javascript.
The PHP you put on the page is server side, it will load first, then the javascript will run client-side.
This part here:
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
Seems like you are wanting this to be dynamic based on what you checked, but I don't see how that url is going to show specifically what you are looking for.

About the PHP:
I think you want to replace this:
<?php $row['id']; ?> // does nothing
with this:
<?php echo $row['id']; ?> // echo's the id
Although I´m not sure that that will work as the loop you have there will generate a strange url, just adding all id's...
About the javascript:
I´m not familiar with the simpleImageCheck() function you are calling, but does it have an onClick or onChange event handler? Otherwise I don´t see your code being run at all.

Related

PHP How to stay on same page after another form has been processed?

So on this application I'm working on, it searches for some code in my database, grabs it, opens a new page and places the code (where necessary) onto the new page by getting its id.
Now within that code (from the database) there is another form that is processed based on user's input. The problem that I am getting is that the new form is not processed on the same page. It redirects to a new url that doesn't specify the code from the database. For example...
When the new page is generated with the code from the database, the url looks like this...
localhost/newpage.php?id=1
Then when I submit the form within the code from the database it changes to this...
localhost/newpage.php?input1=blah&input2=blah
But I want something like this...
localhost/newpage.php?id=1&input1=blah&input2=blah
Just FYI this code needs to be dynamic. For example, let's say I don't know what id the user is looking for and within that id I don't know how many input fields there are.
If you guys need some explicit code (obviously I left out the unnecessary things)...
This is searchpage.php which searches db and displays all relevant items. Then the user selects an item which contains an id and generates newpage.php with that id...
//there is a search query then puts all elements in an associative array
$rows = items->fetch_all(MYSQL_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
echo "<a href='newpage.php?id=$id>User clicks to generate a newpage</a>";
}
This is the form retrieved from database and placed in newpage.php...
<form action="newpage.php" method="GET">
<input name="input1"></input>
//there can be an x amount of input tags here depending on what id is pulled
</form>
This is the php at the top of newpage.php when it is generated...
if (isset($_GET['id'])) {
//retrieves data from specified id from database
if(isset($_GET['inputs'])) {
//do something with user inputs
}
}
Is there any way to achieve this? All help is appreciated! Thanks :)
SOLUTION
For this to work, I had to create a session which stores the id. Consequently i had to change all my $_GET varaibles (that dealt with id info) to $_SESSION variables. But it works as long as you're not storing critical/sensitive info!
Here's the code changes...
Changes in search.php ...
//there is a search query then puts all elements in an associative array
$rows = items->fetch_all(MYSQL_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$_SESSION['current_id'] = $id;
echo "<a href='newpage.php?id=$id>User clicks to generate a newpage</a>";
}
Changes in newpage.php ...
<form action="newpage.php?id=" method="POST">
<input name="input1"></input>
//there can be an x amount of input tags here depending on what id is pulled
</form>
Changes in php of newpage.php ...
if (isset($_SESSION['current_id'])) {
//retrieves data from specified id from database
if(isset($_POST['inputs'])) {
//do something with user inputs
}
}
ALL THANKS TO...
Sathik Khan
You can get the query string "id" in referred header. Either you can attach that query string in client or in server.
Please use $_SERVER['HTTP_REFERER'] to get referer url and from there you can get the id. If it's id of logged in user, I would recommend store them in session for security reason.
Based on your comments,
You can take any one of these actions,
1. Keep the ID in your form as hidden variable
2. Update your url with id as one of the query string and send back to client for error correction.
3. Keep the ID in session, if applicable
4. Use post and perform form validation before redirecting
Thanks.

Pass dynamic data from to div to another div on same page

I am stuck in a problem and in need of support from you guys.
My problem is I want to pass a php variable(dynamically called through database in loop) to another div on the same page without page refresh
//This is a loop
<td><a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a></td>
//The div which should get the above php variable
<div class="tabright" id="existingcase">
<?php
$c_id = $_GET['case_id'];
echo $c_id;
?>
</div>
//the javascript code for calling divs on the same page
<script>
$(".linkright").click(function(){
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
});
</script>
It shows in the url like this index.php#existingcase?case_id=2012001 but never passes the case id to #existingcase. And also #existingcase div does not load either but without passing caseid value, #existingcase loads.
Any suggestions would be great.
I think you want to print clicked case_id in div without page load. To do this, you don't want to pass it using url. you can simply achieve it using javascript.
If your div id existingcase is just change your code like this below.
you are printing that same case_id as a text of anchor tag using $row_mycases['case_id'];. So, you can easily get that text using javascript and you can easily print it in your #existingcasediv.
<td><a class="linkright" href="#existingcase"><?php echo $row_mycases['case_id']; ?></a></td>
I don't know about your other scripts. in .linkright click function place this code like this
$(".linkright").click(function(){
$('#existingcase').text($(this).text()); //if your div id is existingcase it will print your case id.
});
try this code. And let me know the result.
SEE THIS FIDDLE DEMO
UPDATED:
To pass client side value to serverside without page reload, you can use jquery.post() method.
Place this PHP code at the top of your page.
<?php
if (isset($_POST['id'])) {
$caseid = $_POST['id'];
return print_r($caseid);
}
?>
$caseid will contain currently clicked case_id value. So, you can use this $caseid wherever you want in this page. If you click on the another case id, it will update with respect to currently clicked case_id
replace your js with below code,
$(".linkright").click(function () {
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
$.post("yourPHPFile.php", { //use your current php file name instead of "yourPHPFile.php"
id: $(this).text()
}, function (caseid) {
$('#existingcase').text(caseid);
});
});
id : $(this).text() means, get the current element .text() and assign it to $_POST variable name of id. It will post to yourPHPFile.php. And you can retrieve that value like $caseid = $_POST['id'];.
In function (caseid) {, caseid contains the value of $caseid. So, only in this code, I assigned $caseid = $_POST['id'];
By this you can directly print clicked case_id text to your #exixtingcase div.
Any values after # are not sent to the server. Since PHP is a server technology you php code will never see the values after #
<a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
try doing
<a class="linkright" href="existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
instead and your php code should fill the div.
In my understanding of your explanation I think you are making a mistake. You are trying to mix Javascript and PHP with out page refresh. This is not possible through your code as PHP is server side and only works on the server. You can't do href within the same page and expect PHP code inside this div to be executed. The PHP code will not be there. You can try "view source" in your browser and check it out.
I think the only way to solve your problem is to make AJAX call using Javascript, get the response and put wherever you want (without refreshing the page)
Hope this helps and excuse my English
EDIT : Here is a working example for making a simple AJAX call using Jquery.
Your table should be some thing like this:
<td>
<a class="linkright" href="#" data-id="<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a>
</td>
You will notice I added "data-id" attribute. We will use this id in our AJAX call. Put this in your JS :
// Create Jquery ajax request
$("a.linkright").click( function() {
$.get("example.php", // Put your php page here
{ case_id : $(this).attr("data-id") }, // Get data, taken from the a tag
function(data) { // Call back function displays the response
$(".tabright").html("<p>" + data + "</p>");
}); // Get
}); // click event
}); // Document Ready
I tested the code and it is working. You will need to customize it to work for you. If all of this AJAX is new to you I suggest these links for you :
http://www.w3schools.com/ajax/default.ASP
http://learn.jquery.com/ajax/

PHP: Confirm Box before deleting

I want to add a button on my website, where a User can delete his Account. Unfortunately I don't know how to realize it...
my Code so far:
Javascript:
<script language = "JavaScript" >
function delete(id) {
if (confirm("Do your really want to delete your account?"))
{
header("refresh:1;url=intern.php?act=account");
}
else
{
}
}
</script>
my .html file:(there are no tags like html title head... it begins with ?php..)
<td></form><input type='submit' name='deleteuser' value='Delete Account' onClick='return delete()'/></form></td>
Also i have an if clause in the .html file:
if(isset($_POST['deleteuser'])) {
if(delete() == true){
delete_user;
}
else{
header("refresh:1;url=intern.php?act=account");
}
}
The Button is there and when I click on it, it asks me if I'm sure to delete my account, but afterwards I got an error: "Fatal Error:Call to undefined function delete() "
I have a stored procedure named: sp_deleteAccount. In my config.php I declared it as:
$SQL_delete_user = "CALL sp_deleteAccount('";
Now I don't know how to bind that stored procedure in the code so that the Account will be deleted after pressing "Yes I want to delete my Account".
Hope I didn't miss anything and someone can help me
JOP
In this portion you're calling a php redirect(i think?) in javascript without php open tag so that's not going to work. Instead you can use a javascript reditrect if the 'if' statement returns true(yes) then redirect to a url with a get variable of delete or something, see below.
edit -- you'll probably want the id as well so i made adjustments. PLus in the onclick in the form you'll need to pass the id, unless it's stored in a session variable or something, in which case you don't need to pass it into the url. your sql should end with "WHERE id=" then just tack the id onto the query. This is just a simple example to get you started, always be cautious of sql injection, but i'll leave preventing it up to you.
<script language = "JavaScript" >
function deleteUser(id) {
if (confirm("Do your really want to delete your account?"))
{
window.location.href= 'intern.php?delete=true&id='+id;
}
else
{
window.location.href = 'intern.php?act=account';
}
}
</script>
next in intern.php check for the get variable
if(isset($_GET['delete'])) {
$mysqli = new mysqli(connection variables here);
$mysqli->query($SQL_delete_user.(int)$_GET['id']);
}
give that a try, rearrange the code as you like but that should get it done.
as for the error, you can't use the keyword delete for a function name. One last thing, for this to work make the input type "button"
I am not sure there might be a way to achieve it using the approach you are trying , but I am not aware of it. For this I would typically use an ajax call to an url, on the click event of the OK button in the jquery-ui Dialog. And then process the logic and on success create another dialog for confirmation.
I searched and struggled with this issue until I did a little lateral thinking.
I used JavaScript to show a hidden div containing the Yes/No options.
Then an onClick around the Yes option which loaded the php script into a hidden iFrame.
The onClick around the No option simply hid the div and did nothing else.
A bonus is being able to style the div any way I wanted, show and hide it with an effect and place it exactly where it looked best.

How to create a Facebook style "Like" system?

I've been trying to find an example online of a Facebook style "Like" button but have not been able to find anything like this. What I would like to do is, place a button below an image which the user can press. Once pressed it will increment a value in the database for the image's record, and then reflect the addition on the page by adding + 1 to the existing amount. I can guess this will need PHP, SQL and jQuery to pull off. Problem is I have no idea where to begin. I've created already a PHP script to add to my Like's for a particular image by giving the image ID. I created already a jQuery post button which posts to the PHP and likes the image. The thing I'm stuck on is updating the page to reflect the like.
For starters, I think the code I made to do this so far is completely disgusting lol.
Here is all my code so far.
PHP to output the Likes count and Like button, plus code for addition. $info is the array for the result of my whole image files table:
Echo "<b>Likes:</b> ".$info['likes'] . "</span>";
Echo '<script src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript">function test() {$.post("http://stormstorm.com/like.php? id='.$info['fileid'].'")</script>';
Echo '<br /><img onClick="test();" src="img/like.jpg"></p>';
The PHP for the like incremented in like.php:
$id = $_GET['id'];
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id) or die(mysql_error());
The PHP for the liking works fine, I'm happy with that. But the thing to show the liking just sucks badly I think. Thing is I have a list.php which will print the contents of the database one after the other to print all the image listed. So it will print the same replica of the script over and over, typically hard coding the current image ID into the posting. I'm pretty new to this but feel this code sucks, plus it doesn't update the images section.
I was thinking to use Javascript to simply get the Likes element and ++ it but, then it hit me. My list will have over 100+ of these same elements. You can probably tell I might be approaching this the wrong way, and I hope someone can help me out with this.
It looks like you have the general idea down, just a crude implementation of it.
You may want to designate the counter element for each image and update the inner content after the button is pressed...
<img src="xxx.jpg">
<p>
Like <span id="{image_id}_count">150</span>
</p>
where the {image_id} is obviously unique to each image. Pass that to test({image_id}) and then update the html of the count total on success...
function test(id)
{
$.ajax({
url: 'http://stormstorm.com/like.php',
method: 'get',
data: {id: id},
dataType: json,
success: function(data)
{
$('#' + id + '_count').html(data.total);
}
});
}
in your php you would do exactly what you did except return a json encoded array back to the js for update...
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id);
if(mysql_affected_rows() > 0)
{
$sql = mysql_fetch_assoc(mysql_query("SELECT `likes` FROM `files` WHERE `fileid` = ".$id));
echo json_encode(array('total' => $sql[0]['likes']));
}
Keep in mind this is a VERY POOR implementation of this. The real system should definitely be one that does not allow people to just repeatedly click the button over and over again to increment something for the hell of it. According to your needs, of course, you should limit it by login and even record user information relative to the file they're liking and not just increment a number in the database.
So you would have a relational table that stores information for each like. That way you can query the database to make sure a user has not already liked the file before incrementing the number.
Hope that makes sense.
I think you are headed the right direction. You can return the number of likes after the update call in php and let jquery update the like count. I added some code below as an example.
HTML:
<form name="like_form">
<input type="hidden" name="id" value="<?php echo $info['fileid']; ?>" />
Likes: <span class="like_count"><?php echo $info['likes']; ?></span>
<img src="img/like.jpg" class="like_click" />
</form>
Javascript:
$(document).ready(function() {
$('img.like_click').click(function() {
var form = $(this).closest('form[name=like_form]');
var id = $(form).find('input[name=id]').val();
$.post("http://stormstorm.com/like.php?id='" + id + "', function(data) {
$(form).find('span.like_count').html(data);
});
});
PHP: (*Note: I didn't check syntax but hopefully it will be enough code to understand the idea.)
$id = $_GET['id'];
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id) or die(mysql_error());
$result = mysql_query("SELECT likes from files where fileid=" . $id) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['likes'];

PHP variable as part of a jQuery function doesn't work, but plain text does

I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.

Categories