I am currently trying to make a system of "favorites". It works correctly but in the console of my browser gives an error (image below) and I do not understand why it happens.
I tried to find solutions but I can not understand them at all. Can anyone help me?
index.php:
<div class="blog-fav">
<i <?php if (userLiked($post['id'])): ?>
class="fas fa-heart favorite like-btn"
<?php else: ?>
class="fas fa-heart single like-btn"
<?php endif ?>
data-id="<?php echo $post['id'] ?>"></i>
</div>
scripts.js:
$(document).ready(function(){
$('.like-btn').on('click', function(){
var post_id = $(this).data('id');
$clicked_btn = $(this);
if ($clicked_btn.hasClass('single')) {
action = 'like';
} else if($clicked_btn.hasClass('favorite')){
action = 'unlike';
}
$.ajax({
url: 'index.php',
type: 'post',
data: {
'action': action,
'post_id': post_id
},
success: function(data){
res = JSON.parse(data);
if (action == "like") {
$clicked_btn.removeClass('favorite');
$clicked_btn.addClass('single');
} else if(action == "unlike") {
$clicked_btn.removeClass('single');
$clicked_btn.addClass('favorite');
}
}
});
});
});
The error I get:
ERROR MESSAGE - IMG
The problem is in the excerpt res = JSON.parse (data);, the return from AJAX is HTML, but you are treating it as JSON.
Related
I have an ajax code as shown below in which I want to logout the page after particular timeperiod of inactivity. The code below is inside the file mno.php (both javascript and php). My login/logout code is inside the file mno.php.
I believe I need to make changes at Line A. Instead of {action:'logout'}, I tried with {'logout'} but it's still not working. My login and logout code is inside mno.php.
<?php
if(isset($_GET['action']) && $_GET['action'] == "logout") {
unset($_SESSION['admin']);
header('location: /abc/mno.php.php');
exit();
}
?>
<script>
jQuery(document).ready(function ($) {
let lastActivity = <?php echo time(); ?>;
let now = <?php echo time(); ?>;
let logoutAfter = 10;
let timer = setInterval(function () {
now++;
let delta = now - lastActivity;
console.log(delta);
if (delta > logoutAfter) {
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/abc/mno.php",
type: 'GET',
data: {action:'logout'}, // Line A
success: function(data){
console.log(data); // Line B
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
}, 1000);
});
</script>
Problem Statement:
I am wondering what changes I need to make at Line A or in php so that page logout after 10 seconds of inactivity or whatever time we set.
Edit 1: I placed console.log(data) at Line B. On console, I am getting the HTML of my login page but the page is still not logging out. My login page code is inside mno.php. On doing console.log(data), I am getting the following on my console:
<form action="/abc/mno.php" method="post">
<div style='width:400px;'>
<input type="hidden" id="user_login" name="user_login" value="1">
<fieldset>
<legend>Login</legend>
<div>
<label for="user_name">User Name</label>
<input type="text" name="user_name">
</div>
<div>
<label for="user_pass">Password</label>
<input type="password" name="user_pass">
</div>
<div>
<button type="submit">Login</button>
</div>
</fieldset>
</div>
</form>
Edit 2: I have replaced /mno.php with /abc/mno.php
As you have used ajax after processing the response has to be return back to ajax and now your code is sending back the html data which is mno.php because you cannot redirect from your php code .Instead do like below :
Your ajax code :
$.ajax({
url: "test.php",
type: 'GET',
data: {
action: 'logout'
}, // Line A
success: function(data) {
//checking if data coming from php is "success"
if (data === "success") {
//to redirect
window.location.href = "login_page_to_redirect";
}else{
alert("error");
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
console.log(error);
console.log(status);
console.log(xhr);
}
});
Your php code:
if(isset($_GET['action']) && $_GET['action'] == "logout") {
unset($_SESSION['pageadmin']);
//this will send back to ajax
echo "success";
}else{
echo "error";
}
I tried the exact code and after the given time it worked. the ajax url is the file url itself (including php and ajax call).
test.php :
<?php
if(isset($_GET['action']) && $_GET['action'] == "logout") {
echo 'logged out';
}
?>
<script src="js/jquery-min.js"></script>
<script>
jQuery(document).ready(function ($) {
let lastActivity = <?php echo time(); ?>;
let now = <?php echo time(); ?>;
let logoutAfter = 10;
let timer = setInterval(function () {
now++;
let delta = now - lastActivity;
console.log(delta);
if (delta > logoutAfter) {
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "test.php",
type: 'GET',
data: {action:'logout'}, // Line A
success: function(data){
console.log(data); // Line B
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
console.log(error);
console.log(status);
console.log(xhr);
}
});
}
}, 1000);
});
</script>
I get the 'logged out' from php along with the rest of content on the file.
so you should be able to execute your log out function.
Maybe check if your url is correct.
I need a ajax call to post data to the database and fetch the data from database and update in live. I have the following codes
HTML Form
<div class="hover_bkgr_fricc">
<span class="helper"></span>
<div>
<div class="popupCloseButton">×</div>
<p>
<form>
<input type="hidden" name="check_num" value="123" />
<p>Please provide more details</p>
<input type="text" name="reason" />
<a id="submit">Mark Reviewed</a>
</form>
</p>
</div>
</div>
<b id="review_result"></b>
<a class="trigger_popup_fricc">
<button> Mark Reviewed</button>
</a>
Javascript Block
$(document).ready(function() {
$(".trigger_popup_fricc").click(function() {
$('.hover_bkgr_fricc').show();
});
$('.popupCloseButton').click(function() {
$('.hover_bkgr_fricc').hide();
});
$('#submit').click(function() {
var check_num = $('input[name=check_num]').val();
var reason = $('input[name=reason]').val();
var form_data =
'check_num=' + check_num +
'&reason=' + reason;
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(html) {
//if process.php returned 1/true (send mail success)
if (html == 1) {
//hide the form
$('.hover_bkgr_fricc').fadeOut('slow');
$('#review_result').html(data);
} else alert('Sorry, unexpected error. Please try again later.');
}
});
});
And the php block
$link = mysqli_connect($HOST, $USER, $PWD, $DB_NAME);
$check_num = $_POST['check_num'];
$reason = mysqli_real_escape_string($link, $_POST['reason']);
$insert = mysqli_query($link, "INSERT INTO `vloer_paylink_reason` (`id`, `check_number`, `reason`) VALUES (DEFAULT, '$check_num', '$reason')");
$update = mysqli_query($link, "UPDATE vloer_paylink SET reviewed = 1 WHERE check_number ='$check_num'");
$get_check_data = mysqli_query($link, "SELECT reviewed FROM vloer_paylink WHERE check_number = '$check_num'");
$check_data = mysqli_fetch_array($get_check_data);
if($check_data['reviewed']==1){
echo "Reviewed done";
}
else {
echo "Not Reviewed done";
}
Data is inserting and updating to the database but after that not returning to html update. Its returning false (Sorry, unexpected error. Please try again later.)
Add .error : function(e){ console.log(e)} to your ajax call, to return the error.
The function will be:
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(data) {
if(data == "Reviewed done"){
// code goes here
}
},
error : function(e) { console.log(e)} // this will print error
});
You are sending Reviewed done or Not Reviewed done in the php code as a response. Change the javascript code like below.
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(response) {
//if process.php returned 1/true (send mail success)
if (response === "Reviewed done") {
//hide the form
$(".hover_bkgr_fricc").fadeOut("slow");
$("#review_result").html(response);
} else alert("Sorry, unexpected error. Please try again later.");
},
error: function(error) {
console.log(e);
} // To catch any network errors
});
In view_candidates form in my application, I have a button with text REQUEST CONTACT INFO. When I click on the button, the text will be changed automatically to FINISH.
Now what happens: When I refresh the page the button text automatically changes to REQUEST CONTACT INFO.
To overcome this, I gave a status column in my database.
What I want:
Once user click on the button, the status should change from 0 to 1.
With status, I want to display my button text like: if status=0 button should be REQUEST CONTACT INFO, else it should be FINISH.
Button code:
<td>
<button type="button" id="button" class="btn btn-info" onclick="getConfirmation(id);">
<b>REQUEST CONTACT INFO</b>
</button>
</td>
SCRIPT:
<script>
function getConfirmation(id)
{
var retVal = confirm("your request is confiremed ?");
if(retVal)
{
$('#button').text('Finish');
$.ajax({
url: "Candidate/user_view_candidates/change_status",
type: "post",
data: id,
success: function (response)
{
//location.reload();
alert('success');
}
});
}
}
</script>
Controller code:
public function change_status()
{
$id = $this->input->post('candidate_id');
$status = $this->db->query("select status from candidates_details where id = candidate_id")->row()->status;
if($status==0)
{
$status = 1;
}
else
{
$status = 0;
}
$data=array('status'=>$status);
$this->db->where('candidate_id',$id);
$this->db->update('candidates_details',$data);
}
Can someone help me? Thanks in advance.
Check this:
View
<input type="hidden" name="candidate_id" value="<?php echo $candidate_id; ?>"/>//your candidate_id
<button type="button" id="button" class="btn btn-info" >
<b><?php $status == 0? 'REQUEST CONTACT INFO':'FINISHED';?></b>//your status value
</button>
<script src="<?php echo base_url(); ?>assets/plugins/jquery.min.js"></script>
js
$('#button').click(function() {
var candidate_id = $('input[name="candidate_id"]').val();
var url = 'your_cntroller_name/change_status/';
$.ajax({
url: your_base_url + url,
type: 'POST',
data: {'$candidate_id': $candidate_id},
dataType: 'JSON',
success: function(data) {
$('#button').text('FINISHED');
}
});
});
Controller
public function change_status() {
$candidate_id = $this->input->post('candidate_id');
$this->your_model->update_status($candidate_id);
echo true;
exit;
}
Model
public function update_status($candidate_id) {
//your query toupdate status
}
complete step by step solution is
step -1
in your view
<td><button type="button" id="button" class="btn btn-info" onclick="getConfirmation(row id);"><b>REQUEST CONTACT INFO</b></button></td>
getConfirmation(id){
$.ajax({
url: "url_to_your_controller/change_status",
type: "post",
data: id,
success: function (response) {
location.reload();
}
});
}
step -2
in your controller
change_status(){
$id = $this->input->post('id');
$status = $this->db->query("Your query")->row()->status;
if($status==1){
$status = 0;
} else {
$status = 1;
}
$data=array('status'=>$status);
$this->db->where('id','id');
$this->db->update('table_name',$data);
}
from your question I understand that you are displaying your record in a grid/ table and for each record in a row you have a button when you click on button it change the status of the record.
so the solution is simple onclick change the status using ajax call and in DB add a field status against each record which will be 0 by default and after onclick it'll be updated to 1
on page load you've to implement in your view a check
e.g
<?if(status==0){?>
<td><button type="button"><b>Working</b></button></td>
<? } else { ?>
<td><button type="button"><b>Finished</b></button></td>
<? } ?>
I am having a Bootstrap dropdown in my HTML which when clicked should list values from postgres database through AJAX request
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Region/Country
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>
</li>
</ul>
</div>
This is my PHP service code which gets called by AJAX when the dropdown is clicked:
$result = pg_query($dbh, "SELECT country from countries");
if (!$result) {
echo "An error occurred.\n";
exit;
}
$features = array();
while ($row = pg_fetch_array($result)) {
$features[] = array("country" => array($row[0]));
}
$result_feature = $features;
echo json_encode($result_feature);
I had tried something like below
$(".dropdown-toggle").dropdown({
source: function (request, response) {
$.ajax({
url: 'KFRI_Service.php',
dataType: 'json',//since you wait for json
data: {
'service': 'dropdown'
},
success: function(json){
//now when you received json, render options
$.each(json, function(i, option){
var rendered_option = '<li>'+ option.country +'</li>';
$(rendered_option).appendTo('.dropdown-menu');
})
}
})
}
})
current dropdown
Something like this:
$.ajax({
url: 'url',
dataType: 'json', //since you wait for json
success: function(json) {
//now when you received json, render options
$.each(json, function(i, option) {
var rendered_option = '<li>' + option.country + '</li>';
$(rendered_option).appendTo('.dropdown-menu');
})
}
})
And by the way - since frontend is waiting for JSON, you don't always echo your text, for example you need to write an error message:
if (!$result) {
echo "An error occurred.\n";
exit;
}
That's bad - because on client side JQuery will try to parse JSON response and will silently fail in case of error.
Should be done like this:
if (!$result) {
echo json_encode(['error' => 'An error occurred.']);
exit;
}
Now it can easily be checked on client side:
success: function(json){
if (json.error) {
alert(json.error);
} else {
// do your stuff
}
}
You can make a function to get the PHP data as JSON using AJAX like this:
function getJSON(callback){
return $.ajax({
url: your_php_script_url, //the url of the PHP script where your echo your JSON
dataType:'json',
type: 'POST',
success: callback
});
}
And then call your getJSON function like this:
getJSON(function(data){
// where data is your data from PHP
});
And from here on you just simply need to create a dropdown and list the items in it using a for in loop for example.
I'm trying to post a piece of Json data to AJAX and get a "upvote_message" in return. However, the "upvote_message" is returned as undefined.
Code:
<div class="media">
<div class="media-body">
<p align="right">
<span href="javascript:;" rel="1" class="upvote">Text to be replaced</span>
</p>
</div>
</div>
JS:
<script type="text/javascript">
$(function(){
$('.media .media-body .upvote').click(function(){
var this_a = $(this);
var comment_id = $(this).closest('span').attr('rel');
$.ajax({
type:"POST",
url: base_url + "/upvote",
data:{comment_id : comment_id},
dataType: "json",
success: function(data,status){
if(data.state == 'succ')
{
this_a.html(upvote_msg);
}
else
{
this_a.html(upvote_msg);
}
}
});
});
});
</script>
PHP
public function upvote (){
$comment_id = $this->input->post('comment_id');
if($comment_id==5){
echo json_encode(array('state' => 'succ','upvote_msg'=>'haha'));
}
else{
echo json_encode(array('state' => 'fail','upvote_msg'=>'bam'));
}
exit();
}
}
The PHP and AJAX's write-into part works fine. Data is also registered in database.
The issue is that the 'upvote_msg' is shown as "undefined" when being returned to the Javascript.
How to fix this? Many thanks,
upvote_msg is a property of the data object so it should be data.upvote_msg
To get upvote_msg value you have to use
data.upvote_msg or data["upvote_msg"]