Html part:
<div class="page-data">
Page data is in here.
</div>
<div class="comment-wrapper">
<h3 class="comment-title">Feedback:</h3>
<div class="comment-insert">
<h3 class="who-says">Says: Leon Burning</h3>
<div class="comment-insert-container">
<textarea id="comment-post-text" class="comment-insert-text"></textarea>
</div>
<div class="comment-post-btn-wrapper" id="comment-post-btn">
Post
</div>
</div>
<div class="comments-list">
<ul class="comments-holder-ul">
<?php $comments = array( "a", "b", "c" , "d"); ?>
<?php require_once INCLUDES . 'comment_box.php';?>
</ul>
</div>
</div>
</div>
<input type="hidden" id="userId" value="1" />
<input type="hidden" id="userName" value="Leon Burning" />
</body>
<---JavaScript (comment_insert.js)---->
$(document).ready( function(){
$('#comment-post-btn').click(function() {
comments_post_btn_click();
});
});
function comments_post_btn_click() {
var _comment = $('#comment-post-text').val();
var _userId = $( '#userId' ).val();
var _userName = $( '#userName' ).val();
if( _comment.length > 0 && _userId !=null ) {
$('#comment-post-text').css('border','0px solid red');
$.ajax({
type: "POST",
url: "ajax/comments_insert.php",
data: {
task : "comment_insert",
userId : "userid",
comment : _comment
},
success : function(data)
{
comment_insert( jQuery.parseJSON(data));
console.log("ResponseText " + data); },
});
console.log(_comment + " / Username: " + _userName + " / User-ID " + _userId );
}
else {
$('#comment-post-text').css('border','1px solid red');
console.log("Area was empty.");
}
$('#comment-post-text').val("");
}
function comment_insert() {
var t = "";
t += '<li class="comments-holder" id"_1">';
t += '<div class="user-img">';
t += '<img src="user_img.png" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">Insert User</h3>';
t += '<div class="comment-text">New Comment</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">X</li>';
t += ' </ul>';
t += '</div>';
t += '</div>';
t += '</li>';
$( '.comments-holder-ul' ).prepend( t );
}
<---comments_insert.php--->
<?php
print_r( $_REQUEST );
?>
Firefox Error Message:
"SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
I would be very grateful if anyone could fix this for me! :)
You are trying to parse the response from your ajax call as JSON:
success : function(data)
{
comment_insert( jQuery.parseJSON(data));
console.log("ResponseText " + data); },
});
This will not work since you are just printing out the $_REQUEST array:
print_r( $_REQUEST );
You will need to convert the array to JSON first:
echo json_encode( $_REQUEST );
You are trying to parse the output of print_r as JSON (which it is not). Use the php function json_encode instead.
Related
Hello there am trying to get the data from database using ajax posts but i didn't get any data properly. first column data is splinting in another columns(Member names are coming in image field and info field). Image also shared please check that. And also datatables are not working while fetching the data using Ajax. Help me out from this problem...
Thanks & Regards
<body>
<label>Party</label>
<select id='partydropdown' name='partydropdown' onchange="partyFunction();">
<option>--select a party--</option>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row["Id"];?>">
<?php echo $row["PartyName"];?>
</option>
<?php }}?>
</select>
<div id="showhide"></div>
</body>
<script type="text/javascript">
function partyFunction(){
debugger;
$("#showhide").empty();
$("#showhide").html('');
$("#showhide").append("<table class='table table-bordered text-center table-responsive' border='1px' id='example'>"+
"<tr>"+
"<th>PartyMemberName</th>"+
"<th>Image</th>"+
"<th>Info</th>"+
"</tr>"+
"<tbody id='partyBody'>"+
"</tbody>"+
"</table>"
);
$postdata = {};
$postdata["Id"]=$("#partydropdown").val();
console.log($("#partydropdown").val());
$.post('test_data.php',$postdata,function (data) {
debugger;
console.log(data);
console.log(data["data"][0].candiateName);
$("#partyBody").empty();
$("#partyBody").html('');
console.log(data["data"]);
console.log(data["data"].length);
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
$("#partyBody").append("<tr>"+
"<td id='resdata"+i+"'></td>"+
"<td id='resdata1"+i+"' ></td>"+
"<td id='resdata2"+i+"'></td>"+
"</tr>");
$("#resdata"+i).text(data["data"][i].candiateName);
$("#resdata1"+i).append("<img id='photo"+i+"'>");
$("#resdata2"+i).text(data["data"][i].Background);
$("#photo"+i).attr('src', 'http://aptsvotes.com/wp-content/themes/apts2019/img'+data["data"][i].Photo );
}
}
});
};
</script>
here is the test_data.php code
<?php
include_once "conn.php";
include_once "voterdbclass.php";
session_start();
$tbl_name2="Parties";
$dbObj = new Database1();
$values1 = array("all");
$querys = "SELECT c1.CandidateName,c1.Photo,c1.Background ,c1.Type FROM aptsv1_votes.Parties p1 LEFT JOIN aptsv1_votes.Candidates c1 ON c1.CurrentPartyId = p1.Id where p1.Id ='" . $_POST['Id'] . "' limit 21";
$res = $dbObj->SelectRecord($tbl_name2,$values1,"","$querys");
$data=array();
$i=0;
while ($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data[$i]['candiateName']=$rs['CandidateName'];
$data[$i]['Photo']=$rs['Photo'];
$data[$i]['Background']=$rs['Background'];
$i++;
}
$json_array= array(
"data" =>$data
);
echo json_encode($json_array);
?>
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
var imge = data["data"][i].Photo;
var name = data["data"][i].candiateName;
var bg = data["data"][i].Background;
$("#partyBody").append("<tr>"+
"<td id='resdata" + i + "'>" + name+"</td>"+
"<td id='resdata1" + i + "' ><img id= 'photo" + i + "' src='http://aptsvotes.com/wp-content/themes/apts2019/img'" + imge+"></td>"+
"<td id='resdata2" + i + "'>" + bg+"</td>"+
"</tr>");
}
}
You have to parse JSON data into the first script. While ajax result you posting with json_encode, I found missing
var data = $.parseJSON(data);
console.log(data["data"].length);
into code
$.post('test_data.php',$postdata,function (data) {
// debugger;
console.log(data);
var data = $.parseJSON(data); // Add this line in your code and verify
console.log(data["data"].length);
Thank you!
I am trying to retrieve data from my db via ajax, console.log show the all results as I would like, however in my html it displays only one result which is the last data. Why is this? Can someone please help me?
Easy on answer as i'm a newbie :)
My code below;
HTML
<div class="mI">
<section>
<div class="pM" id="m1"></div>
</form>
</section>
<aside class="mBI">
<div class="mT">
<p id="m2"></p>
</div>
<p id="mG"></p>
<p style="margin-top:-8px" id="m3"></p>
</aside>
</div>
JAVASCRIPT
$(document).ready(function() {
"use strict";
function connect2mO() {
$.ajax({
url: "tes.php",
type: "GET",
//data:"",
dataType: "json",
//async:false,
success: function(data) {
$.each(data, function() {
var mP = this.p;
var mT = this.t;
var mG = this.g;
console.log(mP);
console.log(mT);
console.log(mG);
$('#m1').html('<img src="p/' + mP + '"/>');
$('#m2').html(mT);
$('#m3').html(mG);
});
},
error: function connect2mO() {
alert('error loading mO');
}
});
}
if (window.attachEvent) {
window.attachEvent('onload', connect2mO);
} else if (window.addEventListener) {
window.addEventListener('load', connect2mO, false);
} else {
document.addEventListener('load', connect2mO, false);
}
});
PHP
<?php
include ('session_start.php');
include ('db_connect_mO.php');
$sql = mysqli_query($con, "SELECT * FROM mo ORDER BY mRD");
$row = mysqli_fetch_array($sql);
while ($row = mysqli_fetch_assoc($sql))
{
$test[]= array(
'p'=> $row['mP'],
't'=> $row['mT'],
'g'=> $row['mG'],
);
}
header('Content-Type: application/json');
echo json_encode ($test);
//detailed error reporting
if (!$sql)
{
echo 'MySQL Error: ' . mysqli_error($db);
exit;
}
?>
What the code below will output in php its what I am trying to achieve using ajax.
<?php while ($row = mysqli_fetch_assoc($sql)) { ?>
<div class="mI">
<section>
<div class="pM"><img src="p/<?php echo $row["mP"];?>" alt=""/></div>
</section>
<aside class="mBI">
<div class="mT">
<p><?php echo $row["mT"];?></p>
</div>
<p id="mG"></p>
<p style="margin-top:-8px"><?php echo $row["mG"];?></p>
</aside>
</div>
<?php } ?>
var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];
$.each(data, function() {
$.each(this, function(key,value) {
var display = '<div>'+ key +' = ' +value+ ' </div>';
$('body').append(display);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For your code you can do it like this
var data = [{'p': 'p1', 't':'t1', 'g': 'g1'},{'p': 'p2', 't':'t2', 'g': 'g2'},{'p': 'p3', 't':'t3', 'g': 'g3'}];
$.each(data, function() {
var html = '<hr>'+
'<div class="mI">'+
'<section>'+
'<div class="pM" >' + this.p + '</div>'+
'</form>'+
'</section>'+
'<aside class="mBI">'+
'<div class="mT">'+
'<p>' + this.t + '</p>'+
'</div>'+
'<p></p>'+
'<p style="margin-top:-8px" id="m3">' + this.g + '</p>'+
'</aside>'+
'</div>';
$('body').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Replace this:
$('#m1').html('<img src="p/' + mP + '"/>');
$('#m2').html(mT);
$('#m3').html(mG);
which just overwrites the values with this which appends:
$('#m1').html($('#m1').html() + '<img src="p/' + mP + '"/>');
$('#m2').html($('#m2').html() + mT);
$('#m3').html($('#m3').html() + mG);
I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);
guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}
Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);
change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In open cart I have a custom module - with ajax filter - when trying to use the filter i'm getting following errors.
<script type="text/javascript">
$("#btnForm").fancybox({
width: 1000,
height: 1050,
autoSize : false,
fitToView : false,
closeBtn : false,
maxWidth : '100%'
});
$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: <?php echo $max_price ?>,
values: [ <?php echo $start_price ?>, <?php echo $end_price ?> ],
slide: function( event, ui ) {
$( "#amount" ).val( "<?php echo $curr ?>" + ui.values[ 0 ] + " - <?php echo $curr ? >" + ui.values[ 1 ] );
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
clearTimeout(wto);
wto = setTimeout(function() {
filter();
}, 100);
}
});
$( "#amount" ).val( "<?php echo $curr ?>" + $( "#slider-range" ).slider( "values", 0 ) + " - <?php echo $curr ?>" + $( "#slider-range" ).slider( "values", 1 ) );
});
var wto;
$(".checkish").change(function() {
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
clearTimeout(wto);
wto = setTimeout(function() {
filter();
}, 100);
});
$("input[type='text']").change(function() {
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
filter();
});
function mrvidaloca(filter, page) {
$.ajax({
url: 'index.php?route=information/jewels/xml' + filter,
dataType: 'json',
success: function(json) {
all_jewels = json.all_jewels;
pagination = json.pagination;
doolittle = '';
$.each( all_jewels, function( key, value ) {
doolittle += '<div style="text-align:left;padding-bottom:10px;margin- right:1px;">';
doolittle += '<div class="image"><img src="' + value.image + '" /></div>';
doolittle += '<div class="name"><a style="font-size:16px;" href="' + value.view + '">' + value.title + '</a></div>';
doolittle += '<div class="description" style="display:block;">' + value.description + '</div>';
doolittle += '<div class="rating" style="right:10px;position:absolute;z-index:3;top:0;"><img src="catalog/view/theme/pollishop2/image/stars-' + value.rating + '.png" /></div>';
doolittle += '</div>';
});
if(doolittle){
$("#results").html(doolittle);
$("#pagination").html(pagination);
} else {
$("#results").html('<?php echo $no_results ?>');
$("#pagination").html('');
}
}
});
}
function filter(page) {
url = '';
var filter_named = $('#mans').find('input[name="searchjewellery"]').val();
if (filter_named) {
url += '&term=' + filter_named;
}
var filter_name = $('input[name=\'price\']').attr('value');
if (filter_name) {
filter_name = filter_name.replace(/<?php echo $curr ?>/g, '');
filter_name = filter_name.split(' ').join('');
filter_name = filter_name.split('-');
url += '&start_price=' + filter_name[0] + '&end_price=' + filter_name[1];
}
var filter_cat = $('input[name=\'cat\']').attr('value');
if (filter_cat) {
url += '&jewels_category_id=' + filter_cat;
}
var vali = [];
$('#god :checkbox:checked').each(function(i){
vali[i] = $(this).val();
});
lashes = vali.join(',');
if(lashes) {
url += '&difficulty=' + lashes;
}
var valio = [];
$('#bios :checkbox:checked').each(function(i){
valio[i] = $(this).val();
});
helium = valio.join(',');
if(helium) {
url += '&designer_id=' + helium;
}
if(page){
url += '&page=' + page;
} else {
url += '&page=1';
}
mrvidaloca(url,page);
}
</script>
Console shows:
GET http://test.risetea.co.uk/index.php?route=information/jewels/xml&start_price=$0&end_price=$500&jewels_category_id=5&difficulty=1&pa ge=1 500 (Internal Server Error)
jquery-1.8.3.min.js?j2v=2.3.3:2 v.support.ajax.v.ajaxTransport.send
jquery-1.8.3.min.js?j2v=2.3.3:2 v.extend.ajax
index.php?route=information/jewels&jewels_category_id=5:989 mrvidaloca
index.php?route=information/jewels&jewels_category_id=5:1054 filter
index.php?route=information/jewels&jewels_category_id=5:980 (anonymous function)`
It is not Javascript error. It is 500 (Internal Server Error) which means that you have problems on your server side.