i am trying to pass 3 variables in javascript [codeigniter post method] - javascript

It's a like dislike button, connected with a database. But it only takes the first variable "storyid".
<script type="text/javascript">
function savelike(storyid, username, autid)
{
$.ajax({
type: "POST",
url: "<?php echo site_url('site/homecontroler/savelikes');?>",
Data: "Storyid="+storyid,
success: function (response) {
$("#like_"+storyid).html(response+" Likes");
}
});
}
</script>
<p style=" width: 10%;float: left;"><a onclick="javascript:savelike(<?php echo $Data['postid'];?>, <?php echo $Data['firstname'];?>, <?php echo $this->session->userdata('userproid'); ?>);">
<i class="fa fa-thumbs-up" style="font-size: 25px; color: cornflowerblue;"></i>
<span id="like_<?php echo $Data['postid'];?>">
<?php if($Data['likes']>0){echo $Data['likes'].' Likes';}else{echo 'Like';} ?>
</span></a>
</p>

You miss the username and autid in Data
<script type="text/javascript">
function savelike(storyid, username, autid)
{
$.ajax({
type: "POST",
url: "<?php echo site_url('site/homecontroler/savelikes');?>",
Data: "Storyid="+storyid+"&username="+username+"&autid="+autid,
success: function (response) {
$("#like_"+storyid).html(response+" Likes");
}
});
}
</script>
In Html pass the values as string missing '' in firstname and autid
<p style=" width: 10%;float: left;"><a onclick="javascript:savelike(<?php echo $Data['postid'];?>, '<?php echo $Data['firstname'];?>', '<?php echo $this->session->userdata('userproid'); ?>');">
<i class="fa fa-thumbs-up" style="font-size: 25px; color: cornflowerblue;"></i>
<span id="like_<?php echo $Data['postid'];?>">
<?php if($Data['likes']>0){echo $Data['likes'].' Likes';}else{echo 'Like';} ?>
</span></a>
</p>

Apologies for the formatting as I'm on mobile. Try defining the data to be sent like so:
data: {
storyid: storyid,
username: username,
...
}
If that doesn't work please do a console log to see if you are getting the variables. If you aren't, then the issue is obvious.
PS you also haven't properly quoted your first paramter (postid)!

Related

how to refresh the div content without the page reloads

I have the modal with form on click of save it saves in the temporary page and the modal has to close the values should get displayed in the div content.now it is working fine but when the page reloads the content is displaying.i don't want to reload the page
html code:
<div class="content">
<?php if($load_data): ?>
<?php foreach($load_data as $data): ?>
<div class="row modal_bg">
<div class="col-md-3">
<span class="jd_name"><?php echo $data->first_name; ?></span>
<span class="jd_name" ><?php echo $data->last_name; ?></span>
<p class="loc"><?php echo $data->location; ?></p>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
ajax code:
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "page/datapage/",
data: formData,
processData: false,
contentType: false,
success: function(res)
{
$('#myModal').modal('hide');
console.log(res);
if(res)
{
url:"<?php echo base_url(); ?>page/datapage/<?php echo $per->id; ?>";
}
},
error: function(errResponse)
{
console.log(errResponse);
}
});
how to solve this issue ,without page reload i want to display the content.can anyone suggest me how to do.
you need to use html();
success: function(res)
{
$('#yourTargetId').html(res);

How do I pass multiple PHP variables to ajax function onclick

I am trying to send data to one of my function within a controller using ajax but the error at the bottom (in the image) wont let the variables pass.
I'm using the codeigniter framework and this ajax function is in my view.
$(document).ready(function(){
function myButton(id1, id2, id3){
$.ajax({
method: "POST",
url: "<?php echo base_url() ?>controller/function/"+id1+"/"+di2+"/"+id3,
data: {
id1:id1,
id2:id2,
id3:id3
}
dataType : 'text',
success:function(data){
location.reload();
});
}
}
<div align="center">
<a>
<button onclick="myButton('<?php echo $id1; ?>', '<?php echo $id2; ?>', '<?php echo $id3; ?>')">
<img src="<?php echo base_url();?>images/button.png" >
</button>
</a>
</div>
Uncaught ReferenceError: myButton is not defined(…)
Define the function outside of $(document).ready()
Currently, the function isn't being defined until after the dom is loaded, meaning that there is no definition when the button is setup.
This should look like this:
<script>
var myButton = function(id1, id2, id3){
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>controller/function/"+id1+"/"+id2+"/"+id3,
data: {
id1:id1,
id2:id2,
id3:id3
},
dataType : 'text',
success:function(data){
location.reload();
}
});
};
$(document).ready(function(){
//This isn't really needed
});
</script>
<div align="center">
<a>
<button onclick="myButton('<?php echo $id1; ?>', '<?php echo $id2; ?>', '<?php echo $id3; ?>')">
<img src="<?php echo base_url();?>images/button.png" >
</button>
</a>
</div>
You're declaring myButton within the inner document.ready function. You need to declare it in the global scope.
<script>
// Define in global scope
function myButton(id1, id2, id3){
$.ajax({
method: "POST",
url: "<?php echo base_url() ?>controller/function/"+id1+"/"+di2+"/"+id3,
data: {
id1:id1,
id2:id2,
id3:id3
}
dataType : 'text',
success:function(data){
location.reload();
});
}
</script>
<div align="center">
<a>
<button onclick="myButton('<?php echo $id1; ?>', '<?php echo $id2; ?>', '<?php echo $id3; ?>')">
<img src="<?php echo base_url();?>images/button.png" >
</button>
</a>
</div>
The answer may be one charcter ; so use <?php echo base_url(); ?> this will print invalid Javascript and may be more !!!
$(document).ready(function(){
function myButton(id1, id2, id3){
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>controller/function/"+id1+"/"+di2+"/"+id3,
data: {
id1:id1,
id2:id2,
id3:id3
}
dataType : 'text',
success:function(data){
location.reload();
});
}
}
<div align="center">
<a>
<button onclick="myButton('<?php echo $id1; ?>', '<?php echo $id2; ?>', '<?php echo $id3; ?>')">
<img src="<?php echo base_url();?>images/button.png" >
</button>
</a>
</div>

Problen with my ajax code to display comment

The code below is a attempt to create a comment system using ajax and php here php part works well comment is inserted into table but seems I didn't get my hands on ajax yet. Ajax does not work comment is not shown unless I reload page. On reloading page comment appears perfectly where it should be so help me on fixing my ajax code.
<?php
if(isset($_POST['content'])) {
$comment=strip_tags($_POST['content']);
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));
}
?>
<div class='db'>
<table>
<tr>
<td>
<img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
</td>
<td>
<a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
<p><?php echo $tar['comment']; ?></p>
</td>
<td>
<a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
</td>
</tr>
</table>
</div>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content=' + test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "",
data: dataString,
cache: false,
success: function(html) {
$(".db").show(html);
}
});
}
return false;
});
});
</script>
<form method='post' name='form' action='' class='commentbox'>
<textarea cols='30' rows='2' name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit'class='comment_button'/>
</form>
You dont need to use the variable dataString and you need to change the $.ajax() function for this:
var test = $("#content").val();
$.ajax({
type: "POST",
url: "",
data: {
content: test;
},
success: function(response) {
$(".db").append(response);
}
});
change the following line to avoid page refreshes:
$(".comment_button").click(function(event) {
event.preventDefault();
or change the attrubute type="submit" of your button for type="button", like this:
<button type='button' name='submit' class='comment_button'>Comment</button>
I hope it helps you...
Try this.
And make sure jQuery library is also included in your page.
HTML PAGE
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var comment = test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "process.php",
data: {content : comment},
cache: false,
success: function(html) {
$("#db").append(html);
}
});
}
return false;
});
});
</script>
<div id="db">
<!--Returned comment will appear here -->
</div>
<form method='post' name='form' action='process.php' class='commentbox'>
<textarea cols='30' rows='2' name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit'class='comment_button'/>
</form>
PHP PAGE
process.php
<?php
if(isset($_POST['content'])) {
$comment=strip_tags($_POST['content']);
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));
}
?>
<table>
<tr>
<td>
<img src='<?php echo $tar['profile_pic']; ?>' style='width:40px;height:40px;'/>
</td>
<td>
<a href='<?php echo $tar['username']; ?>'><?php echo $tar['first_name'].' '.$tar['last_name']; ?></a>
<p><?php echo $tar['comment']; ?></p>
</td>
<td>
<a href='#' id='<?php echo $tar['id']; ?>' class='delcomment' style='color:#555555;text-decoration:none;' title='Delete'>X</a>
</td>
</tr>
</table>
Use
$(".db").append(html);
if you already have existing comments like:
<div class = "db">
Comment 1
Comment 2
...
</div>
.append will add more HTML to existing tag.

How to grab the required value input on click?

For example, there is such a JS-code:
function openAlbum() {
$("#tracks").html('Some text...');
var uid = $("#uid").val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
}); }
And this html/php-code that is displayed in a cycle:
for ($i = 0; $i < count($searchAlbum); $i++) {
echo '<div id="cover"><form action=""><input type="hidden" id="uid" value="'.str_replace('https://example.com/', '', $searchAlbum[$i]->href).'"/><img src="'.$searchAlbum[$i]->images[1]->url.'"/><br><br><span>'.$searchAlbum[$i]->name.'</span><input type="submit" style="position: absolute;;left: -99999px;" /></form></div>';
}
Problem: currently by clicking grabs only the first input value on the page with id="uid".
How do I put a JS var uid value from the div, which clicked a link?
P.S. Sorry for my bad english.
I'm going to change the way you kinda do this a bit...
<?php
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div class="cover">
<form action="">
<input type="hidden" class="uid" value="<?php echo str_replace('https://example.com/', '', $searchAlbum[$i]->href); ?>"/>
<img src="<?php echo $searchAlbum[$i]->images[1]->url; ?>"/>
<span><?php echo $searchAlbum[$i]->name; ?></span>
<input type="submit" style="position: absolute;left: -99999px;" />
</form>
</div>';
<?php
}
?>
Script:
$(document).on('click','.cover img',openAlbum);
function openAlbum() {
$("#tracks").html('Some text...'); var uid = $(this).parent().find('.uid').val();
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
//$("#results").empty();
//$("#results").append(html);
$("#results").html(html);
}
});
}
This should cover everything. I switched all ids to classes and changed how you execute your jQuery.
Thank you all for your help!
As a result, I will be able to solve the problem.
JS-code:
function openAlbum(uid)
{
$("#results").html('Some text...');
$.ajax({
type: "POST",
url: "s.php",
data: "uid="+uid,
success: function(html) {
$("#results").empty();
$("#results").append(html);
}
});
}
HTML-code:
for ($i = 0; $i < count($searchAlbum); $i++) {
?>
<div id="cover"><a href="#" onclick='openAlbum("<? echo $searchAlbum[$i]->id; ?>");'><img src="<? echo $searchAlbum[$i]->images[1]->url; ?>"/></a><br><br><span><? echo $searchAlbum[$i]->name; ?></span></div>
<?
}
Since id in HTML must be unique, it is taking only the first element's value. Make the ids unique or use class attribute as Cayce K has answered.

Ajax returns proper repsonse but not displaying html

I have a a page where I am getting data from a SQL database via a call through jQuery and Ajax. When the page loads, the script is getting the data from the PHP file. Ajax is getting the correct response (I can see that in Firebug), but is not displaying it in the div as HTML.
Frontpage:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<?php foreach($news as $item): ?>
<li style="border-top: 5px solid #a1cb2f;" class="block" id="post_<?php echo $item['date_added'] ?>">
<img class="post_user_img" src="<?php echo "/userdata/profile_pics/".$item['user_img'] ?>">
<span class="feedtext">
<div class="added_by"></div>
<script type="text/javascript">
function get_userdata() {
user_id = "<?php echo $item['added_by'] ?>";
var datastring = 'user_id='+ user_id;
$.ajax({
type: "POST",
url: "/get_userdata.php",
data: datastring,
dataType: "html",
success: function(data){
$('.added_by').html(data);
}
})
};
get_userdata();
</script>
</br>
</br>
<?php echo $item['body'] ?>
</span>
</br>
</li>
PHP:
<?php include("includes/session.php"); include("includes/connect_to_mysql.php");
if(isset($_POST['user_id'])){
$user_id = $_POST['user_id'];
$sql = mysql_query("SELECT * FROM members WHERE id='$user_id'");
$news = array();
$row = mysql_fetch_assoc($sql);
}
echo "".$row['firstname']."".$row['lastname']. "";
?>
Have tried searching a lot of places now and I have looked through a lot of questions here on Stackoverflow, but I was not able to find the answers. If there are any other questions that are exactly the same, please lead me in that direction. That would be very nice of you.
It looks like you are not returning valid HTML, try:
echo "<a href='user_profile.php?u=".$row['id']."'>" .$row['firstname']."".$row['lastname']. "</a>";
See the extra ' to close href attribute.

Categories