I want to get all posts id from current page after 15 second interval to make server side php query. Php query will find match in Sql with id and if any data find for a particular id's, it will be .append it.
So in my current page have many div with their own dynamic post id like:
<div class="case" data-post-id="111"></div>
<div class="case" data-post-id="222"></div>
<div class="case" data-post-id="333"></div>
<div class="case" data-post-id="anything else dynamic no"></div>
And I want, my javascript will get and sent this ids to a php query for find any match in Sql.
Here my array only got 1st post id. Problem is either my javascript array or php array
My update script: (here var CID cannot get ids, only get first id)
//make array to get id
var CID = []; //get dynamic id
$('div[data-post-id]').each(function (i) {
CID[i] = $(this).data('post-id');
});
function addrep(type, msg) {
CID.forEach(function (id) {
$("#newreply" + id).append("");
});
}
var tutid = '<?php echo $tutid; ?>';
function waitForRep() {
$.ajax({
type: "GET",
url: "/server.php",
cache: false,
data: {
tutid: tutid,
// this way array containing all ID's can be sent:
cid: CID
},
timeout: 15000,
success: function (data) {
addrep("postreply", data);
setTimeout(
waitForRep,
15000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
setTimeout(
waitForRep,
15000);
}
});
}
server.php
if($_REQUEST['tutid'] && $_REQUEST['cid']){
//make array to cid to get id
foreach($_REQUEST['cid'] as $key => $value){
$res = mysqli_query($dbh,"SELECT * FROM test WHERE id =".$value." AND page_id=".$_REQUEST['tutid']." ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$rows = mysqli_fetch_assoc($res);
$row[] = array_map('utf8_encode', $rows); //line 80
$data = array();
$data['id'] = $rows['id'];
//etc all
//do something
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} }
Change small code and check it
//make array to get id
var CID = []; //get dynamic id
$('div[data-post-id]').each(function (i) {
CID[CID.length] = $(this).data('post-id');
});
Related
I want to display my JSON array which i got from the PHP server as list in HTML. The code I used loops through the array, but when i replace the array with the variable it does not work.
$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});
var ownproducts = $('#ownproducts');
$.ajax({
url: 'MYURL',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var products = '<br>'+item.item;
var ul = $('<ul>').appendTo('body');
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
$(json.items).each(function(index, item) {
ul.append($(document.createElement('li')).text(item));
});
ownproducts.append(products);
});
},
error: function(){
ownproducts.text('Error Message');
}
});
});
So i get a JSON file containing data from my database, item.item contains an array but when i replace this:
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
for:
var json = { items: item.item };
or:
var json = { items: products };
it does not work (not displaying anything javascript related).
EDIT:
I try to get some items from my database through PHP
<?php
header('Content-type: application/json');
require 'config.php';
$con = mysqli_connect($url,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$userid = $_GET['userID'];
mysqli_select_db($con, $database);
$sql = "SELECT shoppingListID AS id, shoppingListUserID AS userid, shoppingCheckBox AS checkbox, shoppingItem AS item, shoppingDate AS date
FROM shoppinglist
WHERE shoppingListUserID='$userid'
ORDER BY shoppingDate DESC";
$result = mysqli_query($con,$sql) or die ("Query error: " . mysqli_error());
$records = array();
while($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
the ShoppingItem field contains an array like ["Tomatos","Apples","Mangos","Bananas"] the SQL returns multiple shoppinglists from a single user, I want to display the shoppinglists on cards with the items of each list in an html list.
Anyone any suggestions? I appreciate the help.
Let me suppose that your JSON endpoint does in fact return the right data -- in this case visiting what you"ve labeled MYURL generates (I believe!) the text:
jsoncallback({"items":["Banana","Cherry","Apple","Strawberry","Pear","Pineapple"]})
Then we can move on to your logic, which consists in this callback function:
function (data, status) {
$.each(data, function (i, item) {
var products = "<br>" + item.item;
var ul = $("<ul>").appendTo("body");
var json = {
items: ["Banana", "Cherry", "Apple", "Strawberry", "Pear", "Pineapple"]
};
$(json.items).each(function (index, item) {
ul.append($(document.createElement("li")).text(item));
});
ownproducts.append(products);
});
}
What is the problem here? There are a lot. The first is that you should probably not be iterating over data, since that is not your array. Instead you should be iterating over data.items.
The second is that you should probably just be creating the HTML rather than creating a ton of DOM stuff. You can use vanilla JS's Array.prototype.map or Array.prototype.join functions rather than delegating this to JQuery: it is a part of the JS spec that this is sufficient:
function (data, status) {
var html = '<ul><li>' + data.items.join('</li><li>') + '</li></ul>';
$(html).appendTo('body');
}
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
My Ajax code:
$("a#edit").click(function(){
var id = $(this).closest('tr').attr('id');
//alert(id);
$.ajax({
url: 'getdata.php',
type: "POST",
dataType:'JSON',
data: {
id: id,
},
success:function(result){
alert(result);
}
});
});
My php code:
if ($_REQUEST['id'] != "")
{
$id=$_REQUEST['id'];
$sql = "select * from visit_reports WHERE visit_planner_id='$id'";
$query = sqlsrv_query( $link, $sql);
while($data = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC))
{
print_r($data);
}
}
In Firebug, the array I get:
Array
(
[id] => 1.0000
[visit_planner_id] => 230338
[bi_staff_present_name] => BI staff present name
[bi_staff_trial_function] => BI staff trial function
)
How can I use this array value into my specific input field of modal form?
In your PHP code, Why not print JSON instead of array?
echo json_encode($data);
Now, you can parse it easily from your ajax code.
success:function(result){
var json = $.parseJSON(result);
var id = json.id; // 1.0000
var visit_planner_id= json.visit_planner_id; // 230338
// so on..
}
I'm developing a simple guestbook and I want to update the table with all messages without refreshing the page because if someone it's writing a comment and the page refreshes the comment will be lost.
So I began writing some code with ajax to update the table but I don't know how to send an array (with comment, username, date ecc) from php to ajax.
In the database I have a column named "wrote" and it can be 0 (unread) or 1 (read). 1 it's when the messages it's already on the table.
This is what I've done since now, maybe it's wrong
getGuest.php
<?php
include("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$result = $Database->unreadMessages();
$rows=mysql_fetch_array($result);
echo json_encode($rows);
?>
Script.js
window.onload = function(){
interval = window.setInterval('updateGuest()',5000);
}
function updateGuest() {
$.ajax({
url: 'getGuest.php',
method: 'get',
success: on_getGuest_success,
error: on_error
});
}
function on_getGuest_success(data) {
for(var i=0; i<data.length;i++) {
// HERE I WANT TO ADD A ROW WITH ALL MESSAGE UNREAD BUT I DONT KNOW WHAT I HAVE TO DO
}
}
function on_error() {
//do something
}
Make sure the JSON contains an array
Add headers
use getJSON
Like this:
PHP
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
header("content-type: application/json");
echo json_encode($data);
JS:
$(function() { // when page has loaded
var tId = setInterval(function() { // save the tId to allow to clearTimeout if needed
$.getJSON("getGuest.php",function(data) { // call the server using jQuery's JSON access
$('.guestbook').empty(); // empty the container
var rows = []; // create an array to hold the rows
$.each(data,function(_,item) { // loop over the returned data adding rows to array
rows.push('<tr><td class="name" width="10%">' + item.name + '</td></tr>');
});
$('.guestbook').html(rows.join()); // insert the array as a string
});
},5000); // every 5 secs
});
I would personally only return what was new since last time
I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});