Ajax function not working in CodeIgniter - javascript

I have a button in my page, when I click on this button it redirect me to this link readMessage/id.
I want when I click on it to stay in the same page, I don't want my page to be reloaded or something else.
The link readMessage/id will update the database, which is a function in a controller :
function readMessage($id) {
$this->message_module->readMessage($id);
$this->index();
}
This function will call the readMessage function in the message module :
function readMessage($id) {
$data = array('is_read' => 1);
$this->db->where('id',(int)$id)
->update($_tbl_msg, $data);
}
This is my button :
<button class="testButton" data-id="<?php echo $message->id; ?>">Test</button>
And this is the code I tried :
$('.testButton').click(function(){
// get jquery object access to the button
var $thisButton = $(this);
var form_data = {
id : $thisButton.data('id')
}
$.ajax({
url:'<?php echo base_url;?>messages/readMessage',
type:'GET',
data: form_data,
success:function(d){
alert(d);
}
});
});
But it's not working.
If someone could show me how to do that I'll be thankful.
Edit 1:
I changed the ajax code, and it worked I can see now the alert box which is in the success attribut :
$('.testButton').click(function(){
$.ajax({
url:"<?php echo site_url('messages/readMessage'); ?>",
type:'GET',
data: {id : $(this).data('id')},
success:function(d){
alert(d);
}
});
});
I think the URL after that will be : messages/readMessage?id=myId , but in CodeIgniter it should be : messages/readMessage/myId, that's why it doesn't work.
I did a test by giving the id manually :
url:"<?php echo site_url('messages/readMessage/5'); ?>"
And it worked.
Now I need to know how to concat that value $(this).data('id') with the url, because when I tried this : url:"<?php echo site_url('messages/readMessage/" + $(this).data('id') + "'); ?>", it didn't worked.

As per your recent edit, try below code in url section
url:"<?php echo site_url('messages/readMessage'); ?>/"+$(this).data('id'),
Then your readMessage should accept a parameter as below
function readMessage($data ="") {

In you controller
try by echoing
function readMessage() {
$id=$this->input->get('id');
$this->message_module->readMessage($id);
$this->index();
echo "something";
}

Related

How refresh particular div without reload whole page?

<div id="success_hold">
<?php
if($row['mandate_end']!=date('Y-m-d') && $row['job_position']=='unhold')
{
echo '<span class="badge badge-success">Open</span>';
}
else
{
echo '<span class="badge badge-warning">Hold</span>';
}
?>
</div>
<script>
$(document).ready(function(){
var flag = 1;
$(".hold").click(function(){
job_id = this.id;
if(flag == 1)
{
$.ajax({
type:"POST",
data:{"job_id":job_id},
url:"<?php echo base_url(); ?>pausehold",
success:function(data){
$("#success_hold").load("#success_hold");
}
});
flag = 0;
}
else
{
$.ajax({
type:"POST",
data:{"job_id":job_id},
url:"<?php echo base_url(); ?>resumehold",
success:function(data){
$("#success_hold").load("#success_hold");
}
});
flag = 1;
}
});
});
</script>
I have div where id="success_hold". Now, what happens when I click on class="hold" I am updating my data. Now, I want to refresh my <div id="success_hold"> without reload whole page where I am using .load() function But the problem is that when I use .load() the function shows the whole page in success_hold. So, How can I fix this issue? I want to refresh only success_hold.
Thank You
The problem is because load() is used to make another AJAX request and place the a portion of the HTML retrieved from that request in the target element.
As you're already making an AJAX request to get the data, which is presumably HTML, you simply need to append() data to the container.
Also note that the only difference between the two sides of your condition is the URL the request is sent to, so you can easily DRY this code up:
$(document).ready(function() {
var flag = true;
$(".hold").click(function() {
var url = '<?php echo base_url(); ?>' + (flag ? 'pausehold' : 'resumehold');
flag = !flag;
$.ajax({
type: "POST",
data: { job_id: this.id },
url: url,
success: function(data) {
$("#success_hold").append(data);
}
});
});
});
If data contains the entire page, then you should change that PHP file to return only the relevant HTML as it will help to speed up the request. If, for whatever reason, you can't do that then you can extract the required element from the response like this:
$("#success_hold").append($(data).find('#success_hold'));
success:function(data){
$("#success_hold").load("#success_hold");
}
This is your success method in ajax. You want to pur the content of data into your div #success_hold ?
If you want that, just do this :
success:function(data){
$("#success_hold").html(data);
}

AJAX redirect to another php file and pass javascript variable to that same php file

I am new to Ajax. I have here a function that when a button is clicked, you should be redirected to id.php and at the same time pass the value of clicked_id.
Javascript code:
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
$.post('id.php',{ID:clicked_id},
function(data){
window.alert("here");
window.location='id.php';
});
}
Inside my id.php,
<?php
$clickedID = $_GET['ID'];
echo 'here at id.php';
echo $clickedID;
?>
Now the problem is that ID in id.php cannot be identified.
Please help me. I already tried both $_POST and $_GET.
I believe that the problem here is in the passing of the variable.
there is no need for ajax if you wanna pass the id to the id.php after redirection
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
window.location='id.php?id=' + clicked_id;
}
in id.php you can get the id like this:
<?php $id = $_GET['id'];
function buttonClicked() {
$.ajax({
url: "id.php", //url for php function
type: "POST",
data: {'clicked_id':clicked_id}, // data to sent
dataType: 'json',
success: function (data)
{
}
});
}
And in your id.php file:
$_REQUEST['clicked_id']

How to get another page on ajax?

I've a problem with my page, first code (let said is hompe.php)
<html>
<div id="trackingkp"></div>
</html>
then on my ajax I've code like these
$( document ).ready(function() {
var dataString = '';
$.ajax
({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'html',
success: function(html)
{
$('#trackingkp').html($(html).find('#trackingkp').html());
//$("#trackingkp").html($(data).find('#trackingkp').html());
}
});
});
and on my ajax controller, I do like these (I'm using framework laravel)
public function tracking($url)
{
//var_dump("AAA");
$this->view('ajax/tracking/'.$url,[]);
}
on my ajax/tracking view like this
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
When I try that is showing
Syntax error, unrecognized expression: "<input type='text'>
I have solved the problem, I'm using another option without using jQuery, so on same time, on controller when load view home.php, I try put load view too like these
public function index(){
is_header();
$this->view('home',[]);
$this->view('ajax/tracking/kp',[]); ---> I add these
is_footer();
}
and on ajax/tracking/kp (view) I put these code
<input type='text'></input>
and is working.
The problem would be in this one:
success: function(html) {
// Problem : $(html).find('#trackingkp').html();
$('#trackingkp').html($(html).find('#trackingkp').html());
}
From which this html response is expected to return a json value
in your given [controller]
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
Thus this is equivalent to:
$("<input type='text'></input>").find('#trackingkp').html();
In this case, I don't think you might need to call another *.html(). You can simplify / solve this by calling it once:
$.ajax({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'json', // Kindly replace [html] to [json] since you are returning a [json] value
success: function(html) {
$('#trackingkp').html(html);
}
});
Hope this helps for your case

Send js value to php controller by ajax

I have this button
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
And this button related to this
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
I'm using this script to send value of button to my php controller
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable,
success: function (data){
}
});
}
When I use alert, the result of javascriptVariable is correct and I want it in my controller so I'm trying in my controller to do this:
if(isset($_POST['activation']))
{
$name = $this->input->post('myname');
var_dump($name);
}
But I get null value, what is the wrong?
When you pass data from the browser via AJAX only the data you pass in the data: parameter is sent to the PHP script.
So if you want to test for activation in the PHP script you must actually send that parameter
Also see the amendment to the data: parameter creation below. Its easier to read and a lot easier to code correctly when passing more than one parameter as you dont have to remember &'s and + concatenation.
function handleButton(obj) {
obj.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {activation: 1, myname: obj.id}, // add parameter
success: function (data){
alert(data);
}
});
}
Now the PHP will see 2 parameters in the $_POST array activation and myname
if(isset($_POST['activation']))
{
$name = $_POST['myname'];
var_dumb($name);
}
Or if you are using a framework which I assume you are
if(isset($this->input->post('activation')) {
$name = $this->input->post('myname');
var_dumb($name);
}
EDIT:
Spotted another issue your button has an attribute type="submit" this will cause the javascript to run AS WELL AS the form being submitted in the normal way.
Remove the type="submit" attribute and to be doubly sure that the form will not be submitted as well as the AJAX add a call to preventDefault(); as well before the AJAX call
Since the php script is conditioned by a second POST variable [if(isset($_POST['activation']))], you should post that as well.
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable+'&activation=1',// <-- RIGHT HERE
success: function (data){
alert(data);
}
});
}
SIDE NOTE: you could also echo instead of dump the variable:
if(isset($_POST['activation']))
{
echo $this->input->post('myname');
}
Try this in your ajax function :
function handleButton(obj) {
var javascriptVariable = obj.id;
//alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {myname: javascriptVariable},
success: function (data) {}
});
}
And in your PHP script, you can do $_POST['myname'] to get it (maybe $this->input->post('myname') can work, you can test it)
Look two id
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
AND
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
For both html elements id is same.It can not be used with in the same page.This may cause a problem for you...

Ajax request to php only works once per pageload

I have seen a few of these questions post on here but none of them are working for me. I have a favourite button that i would like my users to press to favourite things. The ajax request is working just fine and the favourite gets stored in the database but i can only use it once then i have to refresh the page to fav/unfav the item. The code for the button is:
<div id="fav-icon">
<?php
// Function checks if user has fav'd the item.
$isFav = favourite($user->id) ? 'un-fav' : 'fav';
?>
<i id="<?php echo $item->id; ?>" class="<?php echo $isFav; ?>"><span class="font-12 fa fa-heart"></span></i>
</div>
Jquery/Ajax
$('.fav').click(function(e){
var con = $(this).attr('id');
$.ajax({
url: 'fav.php',
type: 'POST',
async: true,
data:{
'fav' : con
},
success:function(){
$('#fav-icon').load(document.URL + ' #fav-icon');
}
});
});
$('.un-fav').click(function(e){
var con = $(this).attr('id');
$.ajax({
url: 'fav.php',
type: 'POST',
async: true,
data:{
'fav' : con
},
success:function(){
$('#fav-icon').load(document.URL + ' #fav-icon');
}
});
});
So this works but only once! I have tried a couple of different functions to try make this work including:
$('.fav').live('click', function(e) {
Can anyone tell me where i am going wrong and the correct method to get my button to work multiple times?
Use $(document).on() click event
$(document).on('click','.fav', function(e) {
...
});

Categories