Why is ajax only displaying last data - javascript

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

Related

Why isn't my comment getting posted?

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.

How do I see what data AJAX is passing

I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!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>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.

AJAX is not passing data via POST to its intended URL

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

Javascript get value from multi dimensional array

I experience an issue with getting values from an array. For some reason I can't get it to work (just getting [object]) and appreciate any help here:
Here I'm creating the response
foreach ($locations as $location) {
if($location->getStreet1() != ''){
$result .= $location->getStreet1() .', ';
}
if($location->getCity() != ''){
$result .= $location->getCity() .', ';
}
$locationList[$i]['location'] = addslashes(htmlspecialchars($location->getName()));
$locationList[$i]['address'] = addslashes(htmlspecialchars($result));
$i++;
$result = '';
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode(array('locations' => $locationList)));
And here I'm handling the response:
request.done(function(data) {
var container = jQuery('#hotel-list-container');
var locations = jQuery.parseJSON(data).locations;
container.html('');
var firstSymbols = [];
locations.forEach(function(location) {
var firstSymbol = location.location;
if (jQuery.inArray(firstSymbol, firstSymbols) === -1) {
firstSymbols.push(firstSymbol);
}
});
firstSymbols.forEach(function(firstSymbol) {
if (jQuery.isNumeric(firstSymbol)) {
if (container.find('.numeric').size() === 0) {
container.append('<div class="numeric">0–9</div>');
}
} else {
container.append('<div class="letter">' + firstSymbol + '</div>');
}
locations.forEach(function(data) {
if (firstSymbol == data.location) {
container.append('<div class="hotel-item"><a class="hotel" data-id="' + data.location + '"><div class="hotel_addr_div"><span>' + data.location +'</span>'+data.address+'</div></a></div>');
console.log(data.location);
}
});
});
container.slideDown(null, function() {
jQuery('#hotel-list-container').mCustomScrollbar({ scrollInertia: 0 });
});
});
locations.forEach(function(data) {
if (firstSymbol == data.location) {
container.append('<div class="hotel-item">
<a class="hotel" data-id="' + data.location + '">
<div class="hotel_div"><span>' + data.location +'</span>'+data.address+'</div>
</a>
</div>');
}
And that is what I'm seeing in frontend
<div class="hotel-lists" id="hotel-list-container-mobile" style="max-height: 497px;">
<div class="letter">undefined</div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
<div class="hotel-item"><a class="hotel" data-id="[object Object]">[object Object]</a></div>
</div>
Thanks for all answers. Like requested I added the full code in here

How can I add php variables to this Javascript?

I'm trying to build a simple news page with ajax filters depending on what category the user wants to see. The javascript below connects to a php file and outputs HTML with data from the mysql database. I need to know how to tell the JS to put the data from the "heading" column into a php variable so that it wraps it in the correct href link.
This is the php that creates the heading and the link
$data_fields = '`id`, `heading`, `date`, `copy`, `summary`, `article`, `press_release`, `video`';
$from = '`media`';
$news_result = $db->selectByStrings($data_fields, $from, $where_conditions, $order_by);
$news = $db->getAllRows($news_result);
foreach ($news as $new) {
echo '<h2 class="news"><a class="news" href="'.$base_href.$new['id'].'">'.$new['heading'].'</a></h2>';
}
I somehow need to include this is the separate JS file, making sure it is only applied to data from the heading column.
Javascript
function makeTable(data) {
var tbl_body = "";
$.each(data, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>" + v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
function getEmployeeFilterOptions() {
var opts = [];
$checkboxes.each(function () {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts) {
$.ajax({
type: "POST",
url: "filter3.php",
dataType: 'json',
cache: false,
data: {filterOpts: opts},
success: function (records) {
$('#employees div').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function () {
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
The php file the above connects to:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
$where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
$where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
$where .= " AND video = 1";
}
$sql = $select.$from.$where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I think you are looking for something like this :
var base_href = 'http://www.stackoverflow.com/';
function makeTable(data) {
var tbl_body = "";
$.each(data, function (index, row) {
var tbl_row = "";
$.each(row, function (k, v) {
if(k == 'heading' && 'id' in row) {
v = '<a class="news" href="' + base_href + row.id +'">' + v + '</a>';
}
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
+ v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}

Categories