Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.
Related
I was working on project in which I have to get some text from the database and display it in the text area. Working fine with no line breaks and tabs. but when a line breaks occurs it gives the error
Uncaught SyntaxError: Invalid or unexpected token
My java script code is as :
<script type="application/javascript">
$(document).ready(function () {
document.getElementById('job_type').value = "<?php echo set_value('job_type') ?>";
document.getElementById('job_cat').value = "<?php echo set_value('job_cat') ?>";
if("<?php if(validation_errors() == false) echo "false"; else echo "true"; ?>"=="false")
{
$('#job_title').val("<?php echo $job[0]->job_title ?>");
$('#job_type').val("<?php echo $job[0]->job_type ?>");
$('#job_cat').val("<?php echo $job[0]->job_cat ?>");
$('#salary').val("<?php echo $job[0]->salery ?>");
$('#job_descp').text("<?php echo $job[0]->job_desc ?>");//error here
}
});
});
</script>
The text it was trying to set was
Error details are shown in images
Debug info
I have tried using .html() and .val() too but nothing worked. How can I handle it.
This has already been answered here https://stackoverflow.com/a/4270709/3004335
However, you can use json_encode
<script type="application/javascript">
$(document).ready(function () {
document.getElementById('job_type').value = "<?php echo set_value('job_type') ?>";
document.getElementById('job_cat').value = "<?php echo set_value('job_cat') ?>";
if("<?php if(validation_errors() == false) echo "false"; else echo "true"; ?>"=="false")
{
$('#job_title').val(<?php echo json_encode($job[0]->job_title); ?>);
$('#job_type').val(<?php echo json_encode($job[0]->job_type); ?>);
$('#job_cat').val(<?php echo json_encode($job[0]->job_cat); ?>);
$('#salary').val(<?php echo json_encode($job[0]->salery); ?>);
$('#job_descp').text(<?php echo json_encode($job[0]->job_desc); ?>);//error here
}
});
});
</script>
You do however need to be careful about cross site scripting
See here https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet in particular rule #0
Remove line break(CR LF) in job[0]->job_desc
like this:
$('#job_descp').text("<?php echo str_replace (array("\r\n", "\n", "\r"), '<br>', $job[0]->job_desc);?>");
So I am currently working on a forum, and I want to be able to have users edit their own questions and replies. Currently I am able to edit questions (sort of *other error is below) just fine. But replies are my biggest problem right now. Currently it shows an edit button under a reply but then it will allow me to edit ALL the other replies on the page and then when I save it, it saves the very last row.
<h3>Replies:</h3>
<div id="replies">
<?php
while($rows = mysqli_fetch_array($result2)) {
?>
<p id="dates"><?php echo $rows['a_datetime']; ?></p>
<div id="reply">
<b><p><?php echo $rows['a_username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['a_answer']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', '<p id="reply'.$rows['a_id'].'">'.$text.'</p>');
} else {
?>
<p id="reply<?php echo $rows['a_id']; ?>"><?php echo htmlspecialchars($rows['a_answer']); ?></p>
<?php
}
if($_SESSION['username'] == $rows['a_username']) {
$editReply = true;
?>
<div id="questionId"><?php echo $rows['question_id'];?></div>
<div id="replyId"><?php echo $rows['a_id'];?></div>
<button id="editReply">Edit</button>
<button id="saveReply">Save</button>
<button id="cancelReply">Cancel</button>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#saveReply').hide();
$('#cancelReply').hide();
});
</script>
<?php
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#editReply').click(function() {
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','true');
$('#reply<?php echo $rows['a_id']; ?>').css('background','white');
$('#reply<?php echo $rows['a_id']; ?>').css('border','solid 1px');
$('#saveReply').show();
$('#cancelReply').show();
$('#editReply').hide();
});
$('#saveReply').click(function() {
// Get edit field value
$detail = $('#reply<?php echo $rows['a_id']; ?>').html();
$q_id = $('#questionId').html();
$a_id = $('#replyId').html();
$.ajax({
url: 'editReply.php',
type: 'post',
data: {detail: $detail, q_id: $q_id, a_id: $a_id},
datatype: 'html',
});
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
$('#cancelReply').click(function() {
$('#editReply').show();
$('#saveReply').hide();
$('#cancelReply').hide();
$('#reply<?php echo $rows['a_id']; ?>').attr('contenteditable','false');
$('#reply<?php echo $rows['a_id']; ?>').css('background','#D8D8D8');
$('#reply<?php echo $rows['a_id']; ?>').css('border','none');
});
});
</script>
<?php
}
?>
editreply.php:
<?php
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = ""; // Mysql password
$db_name = "db"; // Database name
$tbl_name = "fanswer"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$detail = htmlspecialchars($_POST['detail']);
$q_id = $_POST['q_id'];
$a_id = $_POST['a_id'];
// Add your validation and save data to database
echo $detail;
echo $q_id;
echo $a_id;
$sql = "UPDATE $tbl_name SET a_answer = '$detail' WHERE question_id='$q_id' AND a_id= '$a_id'";
$result = mysqli_query($conn, $sql);
?>
Originally I had all the editable content in divs but for some reason it made some pages load funny so for now I was hoping to use the p tag.
How can I make it so only one of the replies are editable and so it only sends that information to the editreply.php script?
*My other problem which is sort of a side problem, when I go to edit something that has a link in it I get a load of gibberish posted into my database. E.g. a user post LMAO: https://afunnypic.com, the information in my database says:
LMAO: <a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="https://afunnypic.com" rel="nofollow">https://afunnypic.com</a><br>
Which I don't understand.
Just found my answer to the first problem, all I did was move the script inside the if ($editReply = true) statement and it worked!
If anyone can help with the second bit on editing the links bit that would be great!
This is my example code
<script>
var item = "yooow";
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
echo $str_html; //it will output "yooow"
?>
but...
when i'm trying to compare this into another php variable
<?php $str_php ="yooow";
if($str_html == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>
but it returns to false
how can they be an equal?
PHP is run serverside which means it's not aware of any changes you make in the DOM using Javascript.
<script>
var item = "yooow";
Value set only in clinet side, PHP don't know about changes here
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
WRONG, it will output "<p id="view"></p>"
echo $str_html; //it will output "yooow" ?>
<?php $str_php ="yooow";
Comparing "<p id="view"></p>" and "yoow" and that is not equal!
if($str_html == $str_php)
Better, you give the item value in cookie/session. And, compare the cookie value with $str_php.
<?php session_start(); ?>
<script>
$(document).ready(function(){
var item = "<?php echo $_SESSION['html']="yooow"; ?>";
$("#view").html(item);
});
</script>
<?php
$str_html = '<p id="view"></p>';
$strHtml=$_SESSION['html'];
$str_php ="yooow";
if($strHtml == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>
I am trying to call a PHP function using AJAX to check if the pressed button is the right button.
But I can't seem to figure it out.
I am using this as <input> code :
<?php
$i=0;
while ($i<4){
?>
<input style="background-color: <?php echo $buttonColors[$i]; ?>" onclick="echoHello(<?php echo $i?>)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php $i=$i+1; } ?>
and I'm trying to call a PHP function when the button is clicked. I tried this :
<script>
function echoHello()
{
alert("<?php hello(); ?>");
}
</script>
<?php
function hello() {
echo "Hello World";
}
?>
This worked so I tried to change this to :
<script>
function echoHello(num)
{
alert("<?php hello(num); ?>");
}
</script>
<?php
function hello($num) {
if($num == 1) {
echo "Correct button!!!";
} else {
echo "WRONG BUTTON";
}
?>
But this didn't seem to work. What am I doing wrong?
I think you have quite some thing mixed up here.
I would suggest just writing out the buttons, and pass the buttons value to the javascript:
<?php
$i=0;
while ($i<4){
?>
<input onclick="echoHello(this.value)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php
$i=$i+1;
} ?>
and then in your javascript (after adding all the jQuery goodness):
function echoHello(btnValue) {
$.ajax({
type: "POST",
url: "formhandler.php",
data: { buttonValue: btnValue }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
The javascript above will send the button value to your 'formhandler.php' page, using AJAX.
In the 'formhandler.php', you could then check what the value of $_POST["buttonValue"] is.
Using your setup, together with jQuery, PHP and JSON, it could be something like this:
function echoHello(btnValue) {
$.getJSON('page.php', {
choice: btnValue
})
.done(function(data) {
// based on $_GET["choice"], your PHP could render some JSON like:
// {"background":"image.jpg","fields":["newValue1", "newValue2", "newValue3"]}
// clear the current html
$("#form").html('');
// load a new background
$('body').css({'background-image':data.background})
// set up the new fields:
$.each(data.fields, function( i, item ) {
$("#form").append('<input type="text" value="' + item + '"/>');
});
});
}
This is just a sample, to give you an idea! It's untested also ;)
I am just getting into the world of PHP, Javascript and HTML and would like some help from the community regarding the following code. Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes. Lines 1-3 were for me to test to get the box to update which it does but anything echoed by PHP does not run. I am completely new to this so I realize I must be missing something trivial.
I welcome any suggestions or comments about what I can do to fix this or what I can do better in general.
Thank you.
<script type='text/javascript'>
document.getElementById('modeltxt').value = "test2";
</script>
<?php
echo "<script type='text/javascript'>";
echo "document.getElementById('modeltxt').value =\"TEST3\";";
echo "document.getElementById('customertxt').value = $customer;";
echo "document.getElementById('endusertxt').value = $enduser;";
echo "document.getElementById(dongletxt').value = $dongle;";
echo "document.getElementById('shipdatetxt').value = $shipdate;";
echo "document.getElementById('chasistypetxt').value = $chasistype;";
echo "document.getElementById('chasisnumbertxt').value = $chasisnumber;";
echo "document.getElementById('opsystxt').value = $opsys;";
echo "document.getElementById('dvd1txt').value = $dvd1;";
echo "document.getElementById('dvd2txt').value = $dvd2;";
echo "document.getElementById('storagetxt').value = $storage;";
echo "document.getElementById('nodrivetxt').value = $nodrive;";
echo "document.getElementById('drivesizetxt').value = $drivesize;";
echo "document.getElementById('interface1txt').value = $interface1;";
echo "document.getElementById('interface2txt').value = $interface2;";
echo "document.getElementById('interface3txt').value = $interface3;";
echo "document.getElementById('interface4txt').value = $interface4;";
echo "document.getElementById('interface5txt').value = $interface5;";
echo "document.getElementById('interface6txt').value = $interface6;";
echo "document.getElementById('commentstxt').value = $comments;";
echo "document.getElementById('warrantyexptxt').value = $warrantyexp;";
echo "document.getElementById('extendedwarrantytxt').value = $extwarexp;";
echo "document.getElementById('onsitetxt').value = $onsite;";
echo "document.getElementById('sqlversiontxt').value = $sqlversion;";
echo "<\script>";
You can create dynamics JS using the below
Define Content-Type on the top of your .js.php file:
<?
header('Content-Type: application/javascript');
// Write your php code
?>
and call the js file like this ..
<script type="application/javascript" src="JS_PATH/name-of-file.js.php"></script>
and if you want to use inline php values, you can write like this
<script type="application/javascript">
document.getElementById('modeltxt').value = "<?php echo $dummy_value ?>";
</script>
No need to do this. You can simply use javascript inside php as below :-
As you mention in your question
Basically I want to pass variables plucked from a ODBC_connection by PHP into textboxes.
<?php
// Php block of code
?>
<script type="text/javscript">
document.getElementById('modeltxt').value = "TEST3";
document.getElementById('customertxt').value = "<?php echo $customer;?>";
......
....
...
</script>
<?php
// Another block of code
?>