How do I pass multiple PHP variables to ajax function onclick - javascript

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>

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);

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

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)!

JQuery on click event not always firing?

I have the following ajax call that fires on a click but it seems to be intermittently working and I can't seem to pinpoint the issue...
It seems to be working perfectly one minute and the next not even registering a click?
<input class="btn btn-success" type="button" value="Assign" id="assignJounrey<?php echo $callID; ?>" name="assignJounrey<?php echo $callID; ?>">
<input class="btn btn-danger" type="button" value="Unassign" id="unassignJounrey<?php echo $callID; ?>" name="unassignJounrey<?php echo $callID; ?>" style="display: none;">
<script>
$(document).ready(function(){
$('#assignJounrey<?php echo $callID; ?>').unbind().click(function(){
$.ajax({
type: 'POST',
url: 'assign-journey-calls.php?JourneyID=<?php echo $journeyID; ?>&Call=<?php echo $callID; ?>',
success: function(){
$("#assignJounrey<?php echo $callID; ?>").fadeOut();
$("#unassignJounrey<?php echo $callID; ?>").show();
}
});
});
$('#unassignJounrey<?php echo $callID; ?>').unbind().click(function(){
$.ajax({
type: 'POST',
url: 'unassign-journey-calls.php?JourneyID=<?php echo $journeyID; ?>&Call=<?php echo $callID; ?>',
success: function(){
$("#unassignJounrey<?php echo $callID; ?>").fadeOut();
$("#assignJounrey<?php echo $callID; ?>").show();
}
});
});
});
</script>
Is there anything that i am doing wrong here?

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.

Categories