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"]
Related
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.
I have seen solutions close to my problem but none of them solves it.
Here is my html for the anchor tag:
<div class="rating rating2" align="center">
<a onclick="myAjax(5)" value="5">★</a>
<a onclick="myAjax(4)" value="4">★</a>
<a onclick="myAjax(3)" value="3">★</a>
<a onclick="myAjax(2)" value="2">★</a>
<a onclick="myAjax(1)" value="1">★</a>
</div>
Here is my JS code:
function myAjax(star) {
$.ajax({
url:"find.php",
method:"POST",
data:{ star : star },
success: function( data ) {
console.log( data );
}
});
}
And my corresponding PHP code in find.php:
<?php
if(isset($_POST['star']))
{
$s=$_POST['star'];
echo $s;
}
?>
And of course I have stored the files in the same directory.I am not getting any output.Any help will be much appreciated.
I'm assuming your target is the value attribute of each link.Hence try something like this.
<script>
function myAjax(star) {
$.ajax({
url:"find.php",
method:"POST",
data:{ star : star },
success: function( data ) {
console.log( data );
}
});
}
$("a").click(function () {
var result = $(this).attr('value');
myAjax(result)
})
</script>
I use if (isset($_POST['category_drop'])) {...} to check for the post condition in PHP.
Kindly provide me a solution.
$('.category_filter .dropdown-menu li a ').on('click', function(e) {
e.preventDefault();
var category = $(this).text();
$.ajax({
type: "POST",
url: 'page_author.php',
data: {
category_drop: category
},
success: function(data) {
// do something;
alert(category);
}
});
});
Try this:
var params = {'category_drop':category};
$.post('page_author.php', params, function(data) {
//do stuff
}, 'json');
OK, main problem was in your event setting. Check these codes:
page_author.php (v1.0)
<?php
if (isset($_POST['category_drop'])) echo $_POST['category_drop'];
else echo 'Nothing!';
?>
index.html (v1.0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$(function(){// <---------------- document.ready event
$('.category_filter .dropdown-menu li a').on('click', function(e){
e.preventDefault();
var category = $(this).text();
$.ajax({
type: "POST",
url: 'page_author.php',
data: {
category_drop: category
},
success: function(data) {
console.log(category); // <----- using `data` is correct but using category has no problem, *I changed alert() to console.log()*
}
});
});
});
</script>
<div class="category_filter">
<div class="dropdown-menu">
<ul>
<li>
<a href="javascript:void(0);">
Click Me :)
</a>
</li>
</ul>
</div>
</div>
I created the click event inside document.ready and everything works now.
Just another thing, that you have to send enough code that people can help you. I added some html and other codes to test the code.
and I used console.log() instead of alert(), alert() is good, but console.log() is more pro. and you can see result in console's log, for example in Console of Firebug or something else.
UPDATE - 21/SEP/2016
[cause: questioner needs to change html face after success ajax]
You want to show the result in your page, just do this:
page_author.php (v1.1)
<?php
if (isset($_POST['category_drop'])) echo $_POST['category_drop'];
// else echo 'Nothing!'; // <-------- REMOVE THIS
?>
index.html (v1.1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$(function(){// <---------------- document.ready event
$('.category_filter .dropdown-menu li a').on('click', function(e){
e.preventDefault();
var category = $(this).text();
$.ajax({
type: "POST",
url: 'page_author.php',
data: {
category_drop: category
},
success: function(data) {
$("#outdiv").html($("#outdiv").html()+"<b>This is the result from AJAX: </b> "+data+"<br/>"); // <------ This will change output div inner html after success ajax
}
});
});
});
</script>
<div class="category_filter">
<div class="dropdown-menu">
<ul>
<li>
<a href="javascript:void(0);">
Click Me :)
</a>
</li>
</ul>
</div>
</div>
<div id="outdiv"></div><!------------ Result will show here -->
Just copy above code.
Thanks for all your supportive answers, Finally I got the output by the below method
$('.category_filter .dropdown-menu li a').on('click',function(e) {
e.preventDefault();
var category = $(this).text();
console.log(category);
$.ajax(
{
type: "post",
url: 'category_drop.php',
data: {
category_drop: category
},
cache: false,
success: function(response) {
$('#ajax_section').html(response);
}
});
});
I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue
I am getting undefined function error. I have defined this function on onmouseover but it is not working.
My code is
HTML
<div class="col2" onmouseover="show_info('<?php echo $sub_menu['page_id']; ?>');" onmouseout="hide_info();">
<a href="#">
<img src="css/images/img1.png" />
<h3><?php echo $sub_menu['page_title']; ?></h3>
</a>
</div>
Script
<script>
function show_info(id)
{
alert('hiiii');
var data = "page_id ="+id;
$.ajax({
url:"get_page_info.php", type:"post",data=data,cache:false,
success: function(html)
{
document.getElementById('hide').style.display='none';
document.getElementById('show').innerHTML=html;
}
});
}
function hide_info()
{
document.getElementById('hide').style.display='block';
document.getElementById('show').style.display='none';
}
</script>
Please suggest
You have a syntax error here
url:"get_page_info.php", type:"post",data=data,cache:false,
Change it to
url:"get_page_info.php", type:"post",data:data,cache:false,
Working demo
You also have a problem with your data declaration "page_id ="+id;. You mean "page_id="+id;, or indeed var data = {page_id: id};
Here is how you would handle this using jQuery to avoid the problem completely.
Working demo
HTML - use a class and store the info in data.
<div class="col2 showinfo" data-showinfo="123"><h3>456</h3></div>
<div id="show" style="display:none">show</div>
<div id="hide">hide</div>
So in your PHP this would read
<div class="col2 showinfo" data-showinfo="<?php echo $sub_menu['page_id']; ?>">
jQuery
<script>
$(function(){
$('.showinfo').hover(
function(){ // first one is mouseover
var data = {page_id: $(this).data('showinfo')};
data.html="this is page " + data.page_id; // jsfiddle test
console.log(data);
$.ajax({
url:"/echo/html/", // jsfiddle test
type:"post",
data:data,
cache:false,
success: function(html){
console.log(html);
$('#hide').toggle();
$('#show').toggle().html(html);
}
});
},
function(){ // second one is mouseout
$('#hide, #show').toggle();
}
);
});
</script>
in the script in line 7 there is a syntax error data=data must be data:data