I need to send post data to another page programatically.
I have 2 DateTime in Database I want to compare these DateTimes. and if one of them is bigger than another automatically send post data to another page.
this is simple code:
require('connect.php');
$sql = 'SELECT * FROM POSTS ORDER BY POSTDATETIME ASC';
$result = $conn->query($sql);
if($result->num_rows>0)
{
while($row=$result->fetch_assoc())
{
echo $row["ID"].".".$row["PostDateTime"]."<br/>";
$text = $row["Text"];
$d = new DateTime("now");
$d1 = new DateTime($row["PostDateTime"]);
if($d>$d1)
{
// Send Post Data to another page;
}
else
{
echo "false<br/>";
}
}
}
I googled but there is no way to send automatically post data without any form or ajax .
ajax needs to some event occurs.
And I don't have any Idea how to do that . I will appreciate any tips.
You could use CURL to send a post request.
require('connect.php');
$sql = 'SELECT * FROM POSTS ORDER BY POSTDATETIME ASC';
$result = $conn->query($sql);
if($result->num_rows>0)
{
while($row=$result->fetch_assoc())
{
echo $row["ID"].".".$row["PostDateTime"]."<br/>";
$text = $row["Text"];
$d = new DateTime("now");
$d1 = new DateTime($row["PostDateTime"]);
if($d>$d1)
{
$ch = curl_init('http://www.linktoyourotherpage.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, $row);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
}
else
{
echo "false<br/>";
}
}
}
The only way to achieve what you're doing is with a intermediate page that sends the user to Page C. Here's a small/simple snippet on how you can achieve that:
<?php
if($d>$d1) { ?>
<form id="myForm" action="Page_C.php" method="post">
<?php
foreach ($_POST as $a => $b) {
echo '<input type="hidden" name="'.htmlentities($a).'" value="'.htmlentities($b).'">';
}
?>
</form>
<script type="text/javascript">
document.getElementById('myForm').submit();
</script>
<?php } else {
echo "false<br/>";
}
?>
store the data in a global variable say for example $_SESSION and redirect to another page ... session start and use the global variable.
Related
I'm sending a request to an API that sends back a response to a page/url (response.php). Details from this response are stored in a db table as well as the page's session id. Obtaining the data stored in the db with the session id as the reference value returns null because I noticed the session id sent to the db alongside the response body changes each time making it different to session ids from all other pages in the folder (processor.php, app.js, fromdb.php) which are similar each other. How do I handle the issue seeing as I need the device from which the button that initiated the process got clicked to be able to receive an alert with some details based on data saved to db, on whether their payment was successful or not.
The js page that initiates action when a button is clicked:
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded',ready);
}else{
ready()
}
function ready() {
var btn = document.getElementById('sub')
btn.addEventListener('click',btnClicked)
console.log("ready")
}
function btnClicked() {
let amount = document.getElementById('Amt').value;
let phone = document.getElementById('Number').value;
let name = document.getElementById('Name').value;
//using ajax post data
$.ajax({
url: "http://localhost/textEditor/processor.php",
method: "POST",
data: {
amount: amount,
phone: phone,
name: name
},
});
getResult();
}
async function getResult() {
//using ajx Get method to obtain data from db echoed on fromdb.php page
return await setTimeout($.ajax({
url: "http://localhost/textEditor/fromdb.php",
method: "GET",
success: function(data) {
console.log("The data is:", data)
}
}), 5000)
}
Below is page that makes request to the API and provides callbackurl on which response is sent:
<!-- processor.php -->
<?php
session_start();
$sess_id = session_id();
include_once "db.te.php";
// if (isset($_POST['submit'])) {
date_default_timezone_set('Africa/Nairobi');
$Passkey = 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919';
$Amount= $_POST['amount'];
$BusinessShortCode = '174379';
$PartyA =$_POST['phone'];
$AccountReference =$_POST['name'];
$TransactionDesc = 'test';
$Timestamp =date('YmdHis');
$Password = base64_encode($BusinessShortCode.$Passkey.$Timestamp);
$headers=['Content-Type:application/json; charset=utf8'];
$initiate_url='https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
$callBackURL ='https://c28d-197-231-178-65.ngrok.io/textEditor/response.php';
// ------------------------------
function newAccessToken() {
$ConsumerKey = 'uhsjjsjbVGatHuJKK';
$ConsumerSecret = 'Yh29KHAY17LKjahh';
$credentials = base64_encode($ConsumerKey.":".$ConsumerSecret);
$url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Basic ".$credentials,"Content-Type:application/json"));
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
$access_token=json_decode($curl_response);
curl_close($curl);
return $access_token->access_token;
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $initiate_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization:Bearer '.newAccessToken()));
$curl_post_data = array(
'BusinessShortCode' =>$BusinessShortCode,
'Password' => $Password,
'Timestamp' => $Timestamp,
'TransactionType' => 'CustomerPayBillOnline',
'Amount' => $Amount,
'PartyA' => $PartyA,
'PartyB' => $BusinessShortCode,
'PhoneNumber' => $PartyA,
'CallBackURL' => $callBackURL,
'AccountReference' => $AccountReference,
'TransactionDesc' => $TransactionDesc
);
$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
$curl_response = curl_exec($curl);
curl_close($curl);
// }
The callbackurl page where response is sent and inserted into db:
<!-- callbackurl: response.php, page where response body is sent to the db alongside its session id-->
<?php
include_once "db.te.php";
session_start();
$sess_id = session_id();
$homepage = file_get_contents('php://input');
$nowNow = json_decode($homepage);
if ($nowNow->Body->stkCallback->ResultCode==0) {
$Items = $nowNow->Body->stkCallback->CallbackMetadata->Item;
foreach($Items as $Item) {
if ($Item->Name =='MpesaReceiptNumber') {
$MpesaReceiptNumber = $Item->Value;
}
}
}else{
$ResultCode = $nowNow->Body->stkCallback->ResultCode;
$MerchantRequestID = $nowNow->Body->stkCallback->MerchantRequestID;
$CheckoutRequestID = $nowNow->Body->stkCallback->CheckoutRequestID;
$ResultDesc = $nowNow->Body->stkCallback->ResultDesc;
$sql = "SELECT * FROM duka;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed 1!";
}else{
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$sql = "INSERT INTO duka(ResultCode, MerchantReqID, CheckoutReqID, ResultDesc, SessionId) VALUES (?,?,?,?,?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed 2!";
}else{
mysqli_stmt_bind_param($stmt,"sssss", $ResultCode, $MerchantRequestID,$CheckoutRequestID,$ResultDesc,$sess_id);
mysqli_stmt_execute($stmt);
}
}
}
Selecting data from db and sending it to the js page to be logged:
<!-- fromdb.php -->
<?php
include_once "db.te.php";
session_start();
$sess_id = session_id();
//retrieving data from db where Session ID is equal to this page's session ID
$sql="SELECT * FROM duka WHERE SessionId = $sess_id;";
$result = mysqli_query($conn, $sql);
$resultCheck=mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data = $row["CheckoutReqID"];
}
}
//value to be printed using console.log following an ajax get method
echo json_encode($data);
If you set a cookie for the id, instead of the session, you'll be able to maintain the id in the callback url.
I want to get the id_user data based on the desired row table by doing onclick jquery, then the id_user data can be passed to the controller and redirect page to edit_user, how do I get the id_user data with onclick using the jquery function? I beg for your help, sorry if any of my questions are unclear, if unclear, you can ask me
This is my code
function edit(){
var id_user = $(this).attr("id_user");
var url = $(this).attr("href");
alert(id_user);
console.log(id_user);
$.ajax({
type:'post',
url : url,
data :{id_user:id_user},
success:function(data){
alert(data)
},
error:function(err){
alert(err)
}
});
}
This is my code
<a onclick="edit()" id_user="<?php echo $row ['idx'] ?>" href="<?php echo BASE_URL. 'app.php/usermanagement/edit_user' ?>" class="edit">Edit</a>
This is my controller
public function edit(){
Template::setTitle('Edit User Management');
$id_user =(int)Request::post('id_user');
//$id_user = (int)$_POST['id_user'];
echo $id_user; die;
//$id_user = (int)Session::get('idx');
$result = $this->getUserbyId($id_user);
$dataresult = json_decode($result, true);
if($dataresult === NULL) {
echo "<script language = \"javascript\">window.alert(\No Have Data\");";
echo "javascript:history.back();</script>";
return false;
}
$data = $dataresult;
return $data;
This is my controller code for function getUserbyId
public function getUserbyId($id_user){
//$id_user = Request::post('id_user');
echo json_encode($id_user);
if(!empty($id_user)){
$url="http://localhost:8585/get-user/$id_user";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPGET, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
if($result === FALSE){
die('Curl failed: ' .curl_error($curl));
}
curl_close($curl);
return $result;
}
}
my problem is
id_user undetified
Try following code:
Change html code: You need to pass reference this object in edit function.Also href should be void otherwise page will be redirected to url.
<a onclick="edit(this)" data-id_user="<?php echo $row ['idx'] ?>" href="javascript:void(0)" data-url="<?php echo BASE_URL. 'app.php/usermanagement/edit_user' ?>" class="edit">Edit</a>
Changes in javascript code
function edit(obj){
var id_user = $(obj).data("id_user"); //GET data attribute id_user
var url = $(obj).data("url"); //Get data attribute url
alert(id_user);
console.log(url);
$.ajax({
type:'post',
url : url,
data :{'id_user':id_user},
success:function(data){
alert(data)
},
error:function(err){
alert(err)
}
});
}
I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.
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?
I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>