i use the following script to start a long poll with the php file.. it checks if any results are updated and sends a response ..
For some reason when this javascript is inserted all other scripts hangs on a long poll on fire bug
function waitForMsg(){
$.ajax({
type: "GET",
url: "auth/classes/getdata.php",
async: true,
cache: false,
success: function(data){
console.log(data)
setTimeout("waitForMsg()",1000);
},
error: function(XMLHttpRequest,textStatus,errorThrown) {
// alert("error: "+textStatus + " "+ errorThrown );
setTimeout("waitForMsg()",15000);
}
});
}
$(document).ready(
function()
{
waitForMsg();
});
This is the php file getdata.php
require_once($_SERVER['DOCUMENT_ROOT'].'/auth/config/db.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$user_id = $_SESSION['user_id'];
$lastmodif = time();
$update = 1;
while ($update <= $lastmodif) {
usleep(10000);
clearstatcache();
$sql = "select ua.user_id as member,ua.post_id,pa.user_id,pa.type,pa.time,CONCAT(u.first_name,' ',u.last_name) as
name,u.thumbnail from user_activity ua right join post_activity pa on
ua.post_id=pa.post_id right join users u on pa.user_id=u.user_id where
ua.user_id=".$user_id." and pa.time > FROM_UNIXTIME('".$lastmodif."')";
$result = $conn->query($sql) or die(mysqli_error());
if ($conn->affected_rows > 0) {
$update=$lastmodif;
$response = array();
$response['msg'] ='update';
echo json_encode($response);
}
}
Pretty sure your problem is
usleep(10000);
this will effectively stop execution and the ajax-cycle you try to initiate with setTimeout("waitForMsg()",1000); - usleep blocks for the execution logic.
<?
if(!define("_IS_GET"))
exit("Use another form to get get awww");
else
{
ignore_user_abort(TRUE);
set_time_limit(0); // adjust this to trap long time load
//...your lame process here
//sample you wanna dogetdata.php
$prId = shell_exec("nohup -f php '/path/to/your/getdata.php' /dev/null 2&<1 & $!",$display);
while(exec("$prId -s"))
echo $display."\n<BR>";
// note killing your jobs can be done using prId so its your initiative to store it and keep it ?
}
?>
Related
I have written a script i JQuery and PHP,
After the success return from PHP, AJAX function should catch a success response but I am not getting that.
Below is the code:
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
//if(data=="ok"){
if(data=="YES"){
alert("EMAIL");
}else{
alert(data);
}
//}
//if(data=="ok"){
//alert("Expenses Id already exists!");
//}else{
//alert(data);
//}
}
});
and here is the php code
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
//echo "helloooo";
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
//echo "Proceed";
}
}else{
echo "Not Okay";
}
}else{
}
}
I can see the echo value on browser and alert value also. But if condition is not working for success function???
Try set correct data type for returned data.
$.ajax({
url: 'script_admin-add-category.php',
method: 'POST',
data: {lExpensesId: lcl_ExpensesId},
dataType: 'text',
success: function (data) {
if (data === 'YES') {
alert('EMAIL')
} else {
alert(data)
}
}
})
#J Salaria as i understood your question you are having problem with jquery AJAX and PHP code as you are not getting you desired result. There are different ways to send the data through jquery ajax which i will be explain in detail.
$_POST["lExpensesId"] are you getting this ID from a HTML <form> ?.Because here i'll be showing you 3 different practiced ways to send data through ajax..
NOTE: YOUR CODE IS VULNERABLE TO SQL INJECION. I'LL BE ALSO SHOWING YOU THE METHODS TO OVERCOME.IF YOU WANT TO LEARN MORE ABOUT SQL INJECTION CLICK ON THIS LINK SQL INJECTION LINK
HTML FORM CODE :
<form action="" id="send_lExpensesId_form" method="post">
<input type="text" name="lExpensesId" id="lExpensesId" >
<input type="submit" name="submit" >
</form>
FIRST WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = $(this).serialize();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
SECOND WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = new FormData($(this)[0]);
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
contentType: false,
processData: false,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
THIRD WAY FOR SENDING DATA THIS IS USED WHEN A LINK CLICKED OR TO DELETED THROUGH ID OR CLASS
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var lcl_ExpensesId = $("#lExpensesId").val();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
HERE IT THE PHP CODE WITH mysqli_real_escape_string(); AGAINST SQL INJECTION
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "demo";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST["lExpensesId"])){
$lExpensesId = mysqli_real_escape_string($conn, $_POST["lExpensesId"]);
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
echo "Proceed";
}
}else{
echo "Error".mysqli_connect_error();
}
}
?>
HERE IT THE OTHER PHP CODE WITH MYSQLI->PREPARED WHICH IS BETTER AGAINST SQL INJECTION
<?php
// WITH MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION
$sql = $conn->stmt_init();
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId =?";
if($sql->prepare($Lquery)){
$sql->bind_param('i',$lExpensesId);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo 'YES';
}else{
echo "Proceed";
}
}
else
{
echo "Error".mysqli_connect_error();
}
?>
I HOPE YOU GOT ANSWERE FOR YOU QUESTION IF YOU HAVE OTHER DOUBTS FEEL FREE AND COMMENT BELOW
All methods are known and many thanks for assistance. My question is that Why I am not able to get proper return from PHP. Below is my code:
var lcl_ExpensesId = $("#IExpensesId").val();
//alert(lcl_ExpensesId);
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data=="ok"){
alert("Inserted");
}else{
alert(data);
}
}
});
ob_start();
/------------------FUNCTION TO READ ACCOUNTS DROPDOWN EXPENSES LIST -----------------------/
require_once 'db_config.php';
$newlist = fxn_CONFIGURATION();
$HOST = $newlist[0];
$DBNAME = $newlist[1];
$UNAME = $newlist[2];
$PSWD = $newlist[3];
$conn = mysqli_connect($HOST, $UNAME, $PSWD, $DBNAME);
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
$query_result = mysqli_query($conn, $Lquery);
if(mysqli_num_rows($query_result) > 0){
echo "ok";
}else{
echo "Proceed";
}
}
}
mysqli_close($conn);
ob_flush();
As, i am using this AJAX in my one of input keyup method so whatever I will type, each and everytime, it will execute PHP script. I am having a item as FOOD in databse. When i type "F", I got Proceed, "O" - Proceed, "O" - Proceed, "D" - ok....
When I type D, i should get "Inserted" instead of Ok....
This is my doubt that why i m getting this????
The above problem is resolved by using exit() statement in PHP as I am getting five ↵↵↵↵↵ after my values and it means I am having 5 lines of html without closing ?>. So the best way to resolve the issue is to use exit() in PHP as per need
I've been working on a website for quite some time, but it was all done on localhost. After making login form work properly I decided to upload it to hosting.
Issue is that callback functions of ajax don't seem to work if I use method: POST
If I change POST to GET it will work...
Ajax code:
$.ajax({
method: 'POST',
url: "php/login.php",
data: { username: val_username, password: val_password },
success: function(response) {
if (response == 0) {
location.reload();
} else {
alert("Wrong username or password. Error #"+response);
}
}
});
login.php
<?php
session_start();
require "../php_includes/mysql.php";
// Create connection
$conn = new mysqli($db_server, $db_user, $db_pass, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// escape your parameters to prevent sql injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql = "SELECT * FROM korisnici WHERE username='$username'";
$sql_result = $conn->query($sql);
if ($sql_result->num_rows > 0) {
$row = $sql_result->fetch_assoc();
if (password_verify($password, $row["password"])) {
$_SESSION["loggedin"] = true;
$_SESSION["userid"] = $row["id"];
echo 0;
} else echo 2;
} else echo 1;
?>
I have checked all the file locations, no issue there, since everything works if I change method to GET.
I tried changing datatypes in ajax, tried adding some headers to php file that I've found searching around stackoverflow, but nothing helps...
Make sure you have the same version of PHP on the hosting server (at least PHP 5.5 since you're using password_verify() which is for >= PHP 5.5).
At the lessons i learn how to pass result from a sql request to js via JSON/AJAX. I need the value of the row from this request in my js but it doesnt work. Via console i have an error: Uncaught SyntaxError: Unexpected token <
part of PHP:
<?php
//get all the course from db and reply using json structure
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_hyp");
$id = $_POST['id'];
if (mysqli_connect_errno()) { //verify connection
exit(); //do nothing else
}
else {
# extract results mysqli_result::fetch_array
$query = " SELECT * FROM course WHERE course_category='$id'";
//query execution
$result = $mysqli->query($query);
//if there are data available
if($result->num_rows >0)
{
$myArray = array();//create an array
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = array_map('utf8_encode', $row);
}
$response = array();
$response['rows'] = $row;
$response['query'] = $myArray;
echo json_encode($response);
}
//free result
$a=num_rows;
$result,$a->close();
//close connection
$mysqli->close();
}
?>
first part of Script:
$.ajax({
method: "POST",
//dataType: "json", //type of data
crossDomain: true, //localhost purposes
url: "./query/cate_has_courses.php", //Relative or absolute path to file.php file
data: {id: i},
success: function(response) {
console.log(JSON.parse(response));
var course=JSON.parse(response.query);
var row=JSON.parse(response.rows);
Seem you use JSON.parse in wrong way.
The JSON.parse must be done one time only. The result of JSON.parse is store in course the the access to the data is due by response.query or respons.row .. and so on and not by JSON.parse(respose.query)
I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json_encode for append it.
Jquery sent two type data to php file:
1st: page id
2nd: post ids (a jquery array sent them to php file)
If I used print_r($_REQUEST['CID']); exit; on php file for test what he get from jquery, Its return and display all post ids well.
But if I make any reply on particular post, Its only return recent post reply.
That means, if I have 3 post like: post-1st, post-2nd, post-3rd ; my php return only post-3rd activities.
I want my script update any post reply when it submitted at sql.
my wall.php
// id is dynamic
<div class="case" data-post-id="111"></div>
<div class="case" data-post-id="222"></div>
<div class="case" data-post-id="333"></div>
//Check for any update after 15 second interval by post id.
<script type="text/javascript" charset="utf-8">
var CID = [];
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>");
});
}
var tutid = '<?php echo $tutid; ?>';
function waitForRep(){
$.ajax({
type: "GET",
url: "/server.php",
cache: false,
data: {
tutid : tutid,
CID : CID
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(
waitForRep,
15000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForRep,
15000);
}
});
}
$(document).ready(function(){
waitForRep();
});
</script>
server.php (may be problem in my array or something else)
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
} // array close
$rows = mysqli_fetch_assoc($res);
$row[] = array_map('utf8_encode', $rows);
$data = array();
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
Try to declare CID array like this:
var CID = new Array();
It looks like you're looping through the CIDs and running an SQL query for each one, but you're only retrieving the results once, outside of the loop. You'll only get the last query's results if you run
$rows = mysqli_fetch_assoc($res);
outside of the CIDs foreach loop.
#koc:
Unfortunately, it won't be as simple as moving the closing loop bracket. If you're trying to retrieve multiple datasets in one AJAX call, then you'll need to handle multiple datasets in your AJAX's success callback, or in your addrep() function. Here's one way to do it, but you can do it many different ways depending on what you're ultimately trying to do:
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
$data = array();
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"
SELECT *
FROM comments_reply
WHERE post_id =".$value."
AND qazi_id=".$_REQUEST['tutid']."
AND date >= '$datetime'
ORDER BY id DESC LIMIT 1
") or die(mysqli_error($dbh));
$row = mysqli_fetch_assoc($res)
$data[] = array_map('utf8_encode', $row);
} // array close
//$rows = mysqli_fetch_assoc($res);
//$row[] = array_map('utf8_encode', $rows);
//$data = array();
//$data['id'] = $rows['id'];
//$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
then in your Javascript:
...
success: function(data){
for (var i=0, len=data.length; i<len; i++) {
addrep("postreply", data[i]);
}
setTimeout(waitForRep, 15000);
},
...
But again, that's just an example. I don't really know what your datasets look like or how you want the data to be passed around and used. This is just an idea that hopefully gets you going in the right direction.
I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?