I have a problem when sending data using Ajax
t_id This is the variable I am trying to send to the chat.php using ajax.
function tid() {
var t_id = "<?php echo $AC["id"]; ?>";
$.ajax({
type: 'POST',
url: 'ajax/chat.php',
data: 't_id=' + t_id
});
}
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
document.getElementById('chat').innerHTML = req.responseText;
}
}
req.open('GET', 'ajax/chat.php', true);
req.send();
}
setInterval(function() {
ajax()
}, 1000);
setInterval(function() {
tid()
}, 1000);
chat.php page code
<?php
include("../INC/header.php");
function formatDate($date){
return date('g:i a', strtotime($date));
}
$path = ""; include("../INC/emo.php");
$t_id = $_POST["t_id"];
$query = "SELECT * FROM chat WHERE f_id='$UID' AND t_id='$t_id' OR f_id='$t_id' AND t_id='$UID' ORDER BY msg_data DESC"; $run = $CONFIG->query($query);
while($row = $run->fetch_array()) :
$r_id = $row["f_id"];
$t_id = $row["t_id"];
$r_s = "SELECT * FROM accounts WHERE id='$r_id' "; $r_q = mysqli_query($CONFIG, $r_s); $r_i = mysqli_fetch_assoc($r_q); ?>
<div id="chat_data" class="text-right">
<span class="btn <? if($r_id == $UID){echo"btn-info";}else{echo"btn-secondary";} ?>"><img width="45" style="border-radius:100%;" src="IMG/<?php echo $r_i['img_i']; ?>"></span> :
<span style="<? if($r_id == $UID){echo"color:green;";} ?>text-align:right;"><?php echo $msg = str_replace($EMO_1,$EMO_2,$row["msg"]); ?></span>
<span style="float:left;"><?php echo formatDate($row['msg_data']); ?></span>
</div><hr>
<? endwhile; ?>
The problem now is that the function ajax() is sent and then the function tid() is sent. I want to send all at the same time instead of sending one by one
Related
I have auto load more on page scroll down.
My jQuery/ajax is working but it is auto loading only first 2 pages on scroll down. There are more pages/records but it stuck after 2nd page loads.
I cannot understand the issue.
Somebody please help me out. My php and java code is given below
just played around with the same moving lines up and down but no use.
<?php
$pxe = $_GET['pname'];
$sxe = $_GET['sname'];
?>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
getresult.php
<?php
include('inc/db.php');
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($sql);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql." limit ".$start.",".$perPage;
$faq = $dba3->query($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = mysqli_num_rows($faq);
}
$output = '';
if(!empty($faq)) {
$output .= '<input hidden class="pagenum" value="'.$page.'" />';
$output .= '<input hidden class="total-page" value="'.$pages.'" />';
while ($row = $faq->fetch_assoc()) {
$output .= $row["ename"];
} }
print $output;
?>
no errors just loader image keeps moving
The key is to get the row count from the initial sql, before applying the limit, something like:
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($query);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql . " limit " . $start . "," . $perPage;
$faq = $dba3->query($query);
You should add async : false, in your ajax request.
url: url,
async : false,
type: "GET",
data: {rowcount:$("#rowcount").val()},
Your browser needs to wait for the response before the next request is sent.
I am sending some information to a php file that runs a query but I want to also retrieve some information from that php file at the same time. The php file executes fine but I can't get the json_encoded object.
Javascript function that sends a string and a number to a php file:
function open_close(){
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status="+status+"&TicketNum="+ticketNum;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
alert("Ticket Updated!"); //This never gets hit
getUpdatedTicket(JSON.parse(http3.responseText));
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
PHP File that takes the string and number and updates a table
<?php
include("config.php");
session_start();
$status = $_POST["Status"];
$num = $_POST["TicketNum"];
$newStatus = " ";
if(strcmp($status, "Open") == 0){
$newStatus = "Closed";
}
elseif(strcmp($status, "Closed") == 0){
$newStatus = "Open";
}
$sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
$r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");
$sql = "SELECT * FROM tickets where TicketNum = $num";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
?>
How can I retrieve the json_encoded object in the same javascript function?
You'd need a readyState listener to know when the request is done, and then get the data from the responseText
function open_close() {
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status=" + status + "&TicketNum=" + ticketNum;
var http3 = createAjaxRequestObject();
http3.onreadystatechange = function () {
if (http3.readyState == 4) {
if (http3.status == 200) {
console.log(http3.responseText); // <- it's there
}
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
I have an html select on my page
<pre>
$query = mysql_query("select * from results");
echo "<select id='date' onchange='showdata()' class='form-control'>";
while ($arr = mysql_fetch_array($query)) {
echo "<option value=".$arr['month'].">".$arr['month']." / ".$arr['year']. "</option>" ;
}
echo "</select>";
</pre>
the options are coming from database. After this I have ajax script
<script>
function showdata() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "result.php", true);
xhttp.send();
}
</script>
I want it to send the selected value in the html select to the page result.php
another way of doing the same thing using jquery ajax ...
<select id="item" onchange="send_item(this.value)">
<?php $someVariable = $_GET["someVariable"];
$query = mysql_query("select * from results");
echo "";
while ($arr = mysql_fetch_array($query)) {?>
<option value="<?php echo your value?>"><?php echo your value?></option>
<?php }?>
</select>
<script>
function send_item(str){
$.ajax({
url: '',
type: "post",
data: {
'str':str,
},
success: function(data) {
},
});
}
</script>
Try with this:
$someVariable = $_GET["someVariable"];
$query = mysql_query("select * from results");
echo "";
while ($arr = mysql_fetch_array($query)) {
echo "".$arr['month']." / ".$arr['year']. "" ;
}
echo "";
And JS:
<script>
function showdata() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "result.php?someVariable=test", true);
xhttp.send();
}
</script>
If you need example for POST, visit Send POST data using XMLHttpRequest
For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.
I'm trying to populate a drop-down menu from a MySql.
My problem is that the data from JASON are not showing in my HTML page.
This is what I want to achieve.
ID: Select ID
JASON //This works and the output: {"article1":{ "title":"acGH2867" },"article2":{ "title":"apGS0158" }}
$jsonData = '{';
foreach ($conn_db->query("SELECT customerID FROM customers WHERE furniture='33' ") as $result){
$i++;
$jsonData .= '"article'.$i.'":{ "title":"'.$result['customerID'].'" },';
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
HTML
<script type="text/javascript">
$(document).ready(function(){
var ddlist = document.getElementById("ddlist");
var hr = new XMLHttpRequest();
hr.open("cData.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
for(var o in d){
if(d[o].title){
ddlist.innerHTML += '</option><option value='+d[o].title+'</option>';
}
}
}
}
ddlist.innerHTML = "Loading....";
$('#dlist').on('change', function(){
$('#val1').value() = $(this).val();
});
});
</script>
</head>
<div class="dlist" id="ddlist">
</div>
try this
$jsonData = array();
foreach ($conn_db->query("SELECT customerID as title FROM customers WHERE furniture='33' ") as $result)
{
$i++;
$jsonData["article'.$i]=$result;
}
echo json_encode($jsonData);