I want to create comments with AJAX, I do not know if this is the right way its my first time doing it. I have been searching google for hours and im really stuck.
What I want to achieve is to add a comment right after I click 'comment' button wihtout reloading the page.
I do not know how to create JSON array that will suit my needs.
This is my javascript:
$(function(){
var userComments = $('.userComments');
var commentsUrl="commentsLoad.php";
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
success: function(komentarji){
//$.each ...
userComments.append("output...");
},
error: function(e){
console.log(e);
}
});
});
This is my PHP:
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments=array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
header('Content-type: application/json');
echo json_encode($comments);
}
}
The path that you're on is almost perfectly paved. Except the following you need to take note of:
You should echo the result array in the JSON format outside the while loop.
Since you have specified the dataType as json in your ajax call (and telling jQuery that you are expecting json back from the server), $.ajax will handle the headers itself and therefore header('Content-type: application/json'); is not needed.
A little tweak on the assignment that you're doing on $comments array:
$comments[] = array( // without [] you'll always end up with ONE comment
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date']
);
Just as you have hinted subtly, you need to iterate the returned array and append each comment one-by-one:
success: function(komentarji){
var parsedComments = JSON.parse(komentarji); //parse the result to Javascript readable objects
$.each(parsedComments, function(){
userComments.append("id =>" + this.id + " name => " + this.name + " text =>" + this.text /* etc. */); //you can access each column key as javascript object key here
});
}, //...
Note: There is a typo in the array assignment that you're doing, just remove the ) on the line 'date' => $row['date']) and you'll be fine.
First of all, move the returning of data back to the javascript code out of the while loop so you only do it once. Then change the script a little so that each comment is added to a new occurrence in the $comments array.
include('config.php');
$comments=array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[] = array(
'id' => $row['id'],
'name' => $row['name'],
'text' => $row['text'],
'date' => $row['date'])
);
}
}
echo json_encode($comments);
exit;
You can't send more than one json output but you are sending one in each iteration of while loop
Also can't keep adding header
what you will be sending will look like
{"id": 3 , "name": "foo"}
{"id": 4 , "name": "bar"}
Note that there is no outer array wrapping these or comma separating them.
Thus they are invalid json when sent together.
Put all the comments into one array and send that instead
Try this:
include('config.php');
$comments = array();
$commentsQuery = "SELECT * FROM komentarji";
$result = $conn->query($commentsQuery);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($comments, array('id' => $row['id'], 'name' => $row['name'], 'text' => $row['text'], 'date' => $row['date']));
}
return json_encode(array('status' => true, 'data' => $comments));
} else {
return json_encode(array('status' => false));
}
Also return status with response so that it will be easier to manipulate response
Related
im trying to do an ajax call to a php file which will then make an array, encode it to json and then console.log the first item in the array. At the moment i have this on my homepage :
<script>
window.setInterval(function ajaxcall(){
$.ajax({url: "functions/displayPostsDynamic.php",
success: function(data)
{
console.log(data[0]);
}
});
}, 1000);
</script>
So every second it will call functions/displayPostsDynamic.php and then output the first item when it receives the data.
This is the php page that its calling:
$result = $stmt->get_result();
$count = mysqli_num_rows($result);
$responseArray = [];
if ($count > 0) //If there is more than one post
{
while($row = $result->fetch_assoc()) //For every post, display each one
{
$currentPost[] = ['post_id' => $row["post_id"],'user_id' => $row["user_id"], 'post' => $row["post"], 'date' => $row["date"],'votes_down' => $row["votes_down"],
'votes_up' => $row["votes_up"]];
}
array_push($responseArray, $currentPost);
}
$stmt->close(); //Close the statment and connection
$conn->close();
echo json_encode(array($responseArray));
?>
So above all this it makes a connection to a sql database and $count is how many entrys in a table. So for each entry i want to add all the details to an array and at the end, push every entry to 1 big array so it can be transfered back to the homepage. So if i print out the responseArray just before it gets sent, it will print out this:
Array (
[0] => Array (
[0] => Array (
[post_id] => 117
[user_id] => 59
[post] => lol
[date] => 2017-03-26 18:36:21
[votes_down] => 2
[votes_up] => 1
)
[1] => Array (
[post_id] => 104
[user_id] => 46
[post] => hi from player8
[date] => 2017-03-23 22:19:10
[votes_down] => 19
[votes_up] => 17
)
)
)
There is only 2 entries in the table so that works just fine. Back to the homepage when it runs the console prints out [ as its the first character of the string thats being received instead of the first item of the array. Would anybody know how to transfer an array or even convert the string to an array when it gets back to the homepage? thanks for any help
Add this right before echoing:
header('Content-Type: application/json');
echo json_encode($responseArray);
What i notice in your code in case your wondering that your data is strangely filled with deep arrays.
$responseArray = []; // initialize array
if ($count > 0) //If there is more than one post
{
while($row = $result->fetch_assoc()) //For every post, display each one
{
$currentPost = ['post_id' => $row["post_id"],'user_id' => $row["user_id"], 'post' => $row["post"], 'date' => $row["date"],'votes_down' => $row["votes_down"],
'votes_up' => $row["votes_up"]];
array_push($responseArray, $currentPost); // probably just want to add the post not initialize an array and put the post into that
}
}
$conn->close();
header('Content-Type: application/json');
echo json_encode($responseArray); // probably dont need that array init here either
Your data are processed like string, you just need to set data type in your jquery ajax call:
$.ajax({
url: "functions/displayPostsDynamic.php",
dataType: "json",
or you can use JSON.parse:
success: function(data)
{
data = JSON.parse(data);
console.log(data[0]);
}
Paste the following code into PHP.
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 9;
}
foreach($json2 as $item){
print_r($item);
echo "<br>";
}
echo json_encode($json2);
The above code will display the following result. I will call this the "expected result"
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
stdClass Object ( [id] => 1 [quantity] => 2 [total] => 9 )
[{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9},{"id":1,"quantity":2,"total":9}]
Now, Following the same logic. Paste java script below
function test(){
var json = [{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}];
$.ajax({
url: base_url+"Product/ajax_test",
type: "POST",
dataType: "JSON",
data: {
'json':json,
},
success:function(data){
console.log(data);
}//end success function
});//end of ajax
}
And paste the php below, I am using codeigniter frame work if this helps
public function ajax_test(){
$json = $this->input->post('json');
$json2 = json_decode($json);
foreach($json2 as $item){
$item->total = 2;
}
echo json_encode($json2);
}
I expect the above 2 piece of code to show something similar in the console as my "expected result", but nothing shows in the console. And if I change the above code to the following
public function ajax_test(){
$json = $this->input->post('json');
foreach($json as $item){
$item["total"] = 2;
}
echo json_encode($json);
}
The above code will show result in console. the "total" property is not in the final result as if it simply gave back the original $json variable. And it is also weird I need to use $item["total"] instead of $item->total.
Question 1, What did I do wrong on the above?
Question 2, Since PHP is stateless, is there a way for me to trouble shoot ajax, by echoing out the php page in the console without json encoding it?, if this make sense.
json_decode() can decode a JSON object as either an object or an array.
$json = '[{"id":1,"quantity":1},{"id":2,"quantity":2},{"id":3,"quantity":3}]';
$json_with_objects = json_decode($json);
$json_with_arrays = json_decode($json, true);
echo $json_with_objects[0]->quantity;
echo $json_with_arrays[0]["quantity"];
var_dump($json_with_objects);
var_dump($json_with_arrays);
Presumably, though we can't know since you don't provide it, your code $this->input->post() is decoding with associative arrays instead of objects.
What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span> <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button> '+v.price+' '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);
i have the problem to add elements to an json array.
The structure i want is that:
[{"method":"edit","type":"1", "template":"3", "meta":{"title":"Tools", "descirption":"Tools"}}]
The problem is that i add all these parameters dynamically.
So lets say i have for the start:
[{"method":"edit","type":"1", "template":"3"}]
How can i add the whole "meta" array and please do not be with push(), because than i will have another structure when i print it.
When i use
$json = json_decode($json, true);
I want to have:
array(
method' => edit,
'type' => 1,
'template' => 3,
'meta' => array('title' => '')
);
Thanks in advice !
So I'm going to assume you have the JSON to start with. So let's decode to PHP (as you noted correctly)
$json = json_decode($json, true);
So now we should have $json['method'], etc. Now let's define $meta
$meta = array('title' => '');
And add this to $json
$json['meta'] = $meta;
echo json_encode($json);
When your current JSON decodes in PHP using json_decode, it will decode into an array with one element, or array[0]. Therefore in order to access or any object you need to first point to that 0 index. Do it this way:
$json = '[{"method":"edit","type":"1", "template":"3"}]';
$arr = json_decode($json);
$arr[0]->meta = array('title' => '');
$json = json_encode($arr);
var_dump($json);
//Result:
// string '[{"method":"edit","type":"1","template":"3","meta":{"title":""}}]' (length=65)
I want to select some content from the database and return it to the javascript. There are several rows returned by the database. I tried this with JSON and also get a result, if I print it out. But if I want to convert the JSON string, there is always the error message below. (at the JSON.parse) So, I assume maybe an mistake while filling the array? Thanks in advance guys!
Javascript:
$.ajax({
url: "./select_firsttracks.php",
type: "post",
success: function(resultset) {
$("#erroroutput").html(resultset);
var arr = JSON.parse("{" + resultset + "}"); // --> "Uncaught SyntaxError: Unexpected token {"
},
error: function(output) {
$("#erroroutput").html("fatal error while fetching tracks from db: " + output);
}
});
PHP:
$storage = array();
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
echo json_encode($storage);
}
Output on the console:
[{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"}][{"id":"1","trackname":"yes","artist":"Lady Gaga","genre":"Pop","url":"ftp:\/development","musicovideo":"1"},{"id":"2","trackname":"no","artist":"Prinz Pi","genre":"Rap","url":"ftp:\/development","musicovideo":"1"}]
echo the json after the while
$storage = array();
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
}
echo json_encode($storage);
and change:
var arr = JSON.parse(resultset);
You're adding curly braces in front and behind your received JSON, here:
var arr = JSON.parse("{" + resultset + "}");
Phps json_encode returns perfectly valid JSON by itself. Try it without adding the braces:
var arr = JSON.parse(resultset);
The resulting json string is not valid, you can check it with jsonlint
Modify your php code to echo outside the loop:
while($row = $result->fetch_array())
{
$storage[] =
array
(
"id" => $row["id"],
"trackname" => $row["trackname"],
"artist" => $row["artist"],
"genre" => $row["genre"],
"url" => $row["url"],
"musicovideo" => $row["musicovideo"]
);
}
echo json_encode($storage);
And in javascript just use the output as a javascript object
success: function(resultset) {
console.log(resultset)
resultset.each(function(index,element){ console.log(index,element )})
},