how to obtain registration ids when sending push notifications in curl php - javascript

So basically... here are working two files, one is a curlphp script and the other an angular1 js file.
in the js file, When an admin user clicks on 'send notification' an event is triggered in order to send a message by invoking curl through a function.
That function looks like this
$scope.notify = function(title, content, ¿¿ userId ??){
$.ajax({
url: 'app/backend/src/curl-service.php',
type: 'POST',
data: {
userId: 'the problem is here',
title: title,
message: content
},
success: function(data) {
console.log('time to use curl service');
},
error: function(){
console.log('Error! you can't use curl service');
}
});
};
as you can see, I pass some data with ajax to fill the notification's content that will be pushed by this curl-service.php file
<?php
// Incluimos el api asignada al app
define('API_ACCESS_KEY', 'AIzaSyAJvT_Tx7vwZzViWkwUcQHdhx2osTiSXHA');
$registrationIds = array($_POST['userId']);
$title = array($_POST['title']);
$message = array($_POST['message']);
// preparamos los array
$msg = array
(
'title' => $title,
'message' => $message,
'sound' => default,
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Content-Type: application/json',
'Authorization: key=' . API_ACCESS_KEY
);
//iniciamos el servicio conectando con la url
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch);
curl_close($ch);
echo $result;
//ejecutamos el servicio
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//verificamos posibles errores y se genera la respuesta
if ($err) {
echo "Se ha producido el siguiente error:" . $err;
} else {
echo $response;
}
?>
What I actually need to know, is how can I obtain the registration ids so then I can use it in my php file too

What you are doing wrong is right here in this bit of code:
$registrationIds = array($_POST['userId']);
$title = array($_POST['title']);
$message = array($_POST['message']);
// preparamos los array
$msg = array
(
'title' => $title,
'message' => $message,
'sound' => default,
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
)
You are creating Arrays from your POST data and then using then as Strings afterwards, if you change the first bit to:
$registrationIds = $_POST['userId'];
$title = $_POST['title'];
$message = $_POST['message'];
or even better with security in mind:
$registrationIds = filter_input(INPUT_POST, 'userId', FILTER_SANITIZE_STRING);
$title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_STRING);
You should be good to go

Related

Javascript redirect works unexpectedly after success:true server response

I am developing a wordpress login plugin for my website. I have now implemented the social login function which works fine. I am sending an ajax request to the server containing the login data, also I have defined the success property so that it will redirect the user if the success server response is true, otherwise it will redirect to the login page again.
The redirect works, but not as expected. When logged in social I get the success: true response, but it redirects for branch else instead of if. Why is this happening?
Sorry, I'm new and trying to learn. Below is the Js and Php code of my plugin.
Full Javascript
<script src="https://www.google.com/recaptcha/api.js"></script>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>
<script src="https://apis.google.com/js/platform.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- <div class="social-login">
<button class="facebook-login">Login con Facebook</button>
<button class="google-login">Login con Google</button>
</div> -->
<form id="login-form" method="post">
<label for="username">Username o Email:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="remember">Ricordami</label>
<input type="checkbox" id="remember" name="remember">
<div class="g-recaptcha" data-sitekey="xxxxxxxxxxxxx"></div>
<div id="login-form-message"></div>
<button type="submit">Accedi</button>
</form>
<button id="facebook-login-button">Accedi con Facebook</button>
<div id="google-login-button"></div>
<script>
// Manage Login Form
jQuery(document).ready(function($) {
$('#login-form').submit(function(e) {
e.preventDefault(); // stop the form from submitting the normal way
// Add Regex Data validation for input fields email, username and password
// La regex utilizzata in questo esempio è composta da due parti separate da un pipe (|): /^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/: Questa parte della regex verifica se l'input è un indirizzo email valido. -- /^[A-Za-z0-9._-]+$/: Questa parte della regex verifica se l'input è un nome utente valido.
// Per eseguire l'escape di caratteri speciali viene utilizzato "encodeURIComponent".
var form = $(this);
var username = encodeURIComponent(form.find('#username').val());
var email = encodeURIComponent(form.find('#email').val());
var regex = /^[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,}$|^[A-Za-z0-9._-]+$/;
var isValid = regex.test(username) || regex.test(email);
// Error Message if Wrong email or password
if (!isValid) {
$('#login-form-message').html("Username o email non validi");
return;
}
// Google ReCaptcha Verification
var recaptcha_response = grecaptcha.getResponse();
if(recaptcha_response.length == 0) {
$('#login-form-message').html("Per favore completa il recaptcha");
return;
}
// Data Object
var data = {
'action': 'login',
'username': username,
'password': encodeURIComponent(form.find('#password').val()),
'remember': encodeURIComponent(form.find('#remember').val()),
'nonce': encodeURIComponent(form.find('input[name="nonce"]').val()),
'recaptcha_response': recaptcha_response
};
$.ajax({
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: data,
success: function(response) {
if (response.success) {
location.reload();
} else {
$('#login-form-message').html(response.data.message);
}
}
});
});
/* Manage Social Login Script */
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxxx',
cookie : true,
xfbml : true,
version : 'v15.0'
});
document.getElementById('facebook-login-button').addEventListener('click', function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', {fields: 'name,email'}, function(response) {
var data = {
'action': 'facebook_login',
'facebook_id': response.id,
'access_token': FB.getAuthResponse().accessToken
};
// Send Ajax Request
$.ajax({
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: data,
success: function(response) {
console.log(response);
if (response.success) {
// Redirect to Homepage
window.location.href = '/';
} else {
// Redirect to Login Page
window.location.href = '/member-login';
}
}
});
});
} else {
document.getElementById('login-form-message').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
});
}
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
});
Full PHP
// Actions Plugin
add_action( 'wp_ajax_login', 'login_handler' );
add_action( 'wp_ajax_nopriv_login', 'login_handler' );
add_action( 'wp_ajax_facebook_login', 'facebook_login_handler' );
add_action( 'wp_ajax_nopriv_facebook_login', 'facebook_login_handler' );
add_action( 'wp_ajax_google_login', 'google_login_handler' );
add_action( 'wp_ajax_nopriv_google_login', 'google_login_handler' );
// Shortcodes
add_shortcode('login_form', 'render_login_form');
// LOGIN FORM FUNCTIONS
// Render login-form temlate inside shortcode
function render_login_form(){
if ( is_user_logged_in() ) {
return __( 'You are already signed in.' );
} else {
$template = require( plugin_dir_path( __FILE__ ) . 'templates/login-form.php' );
}
}
// Ajax action handler for login-form.php
function login_handler() {
$recaptcha_response = $_POST['recaptcha_response'];
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
$recaptcha_data = array(
'secret' => $recaptcha_secret,
'response' => $recaptcha_response
);
$recaptcha_options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($recaptcha_data)
)
);
$recaptcha_context = stream_context_create($recaptcha_options);
$recaptcha_verify = file_get_contents($recaptcha_url, false, $recaptcha_context);
$recaptcha_response = json_decode($recaptcha_verify);
if(!$recaptcha_response->success) {
wp_send_json_error( array('message' => __( 'Invalid reCAPTCHA.', 'text-domain' ) ) );
}
if ( !wp_verify_nonce( $_POST['nonce'], 'login-form-nonce' ) ){
wp_send_json_error( array('message' => __( 'Invalid security token.', 'text-domain' ) ) );
}
// rest of the login code
$creds = array();
$creds['user_login'] = $_POST['username'];
$creds['user_password'] = $_POST['password'];
$creds['remember'] = $_POST['remember'];
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ){
wp_send_json_error( array('message' => __( 'Invalid username or password.', 'text-domain' ) ) );
} else{
wp_send_json_success();
}
wp_die();
}
//** Facebook Login AJAX Handler **/
function facebook_login_handler() {
// Verify ID token
$facebook_id = $_POST['facebook_id'];
$access_token = $_POST['access_token'];
$response = wp_remote_get( 'https://graph.facebook.com/v3.3/' . $facebook_id . '?access_token=' . $access_token . '&fields=name,email' );
$facebook_response = json_decode( wp_remote_retrieve_body( $response ), true );
// use access token and check whether it's expired or not, make a request to the debug_token Facebook API.
$debug_response = wp_remote_get( 'https://graph.facebook.com/debug_token?input_token=' . $access_token . '&access_token=' . $app_token );
$debug_response = json_decode( wp_remote_retrieve_body( $debug_response ), true );
if ( ! isset( $debug_response['data']['is_valid'] ) || ! $debug_response['data']['is_valid'] ) {
// Handle error, access token is invalid or expired
}
// Verify response object to check if the email and name fields exist in the $facebook_response object.
if ( isset( $facebook_response['email'] ) && isset( $facebook_response['name'] ) ) {
$email = $facebook_response['email'];
$username = $facebook_response['name'];
} else {
// Handle error, email or name not found in response
}
if ( ! isset( $facebook_response['id'] ) ) {
$response = array(
'success' => false,
'message' => 'Invalid Facebook ID token'
);
echo json_encode( $response );
wp_die();
}
// Check if the user already exists in our database
$user = get_user_by( 'email', $email );
if ( ! $user ) {
$user = get_user_by( 'login', $username );
}
if ( $user ) {
// Update user meta with Facebook ID
update_user_meta( $user->ID, 'facebook_id', $facebook_id );
// Log the user in
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID );
$response = array(
'success' => true,
'message' => 'Login successful'
);
} else {
// If the user does not exist, create a new account
$user_data = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => wp_generate_password()
);
$user_id = wp_insert_user( $user_data );
if ( is_wp_error( $user_id ) ) {
$response = array(
'success' => false,
'message' => $user_id->get_error_message()
);
echo json_encode( $response );
wp_die();
} else {
update_user_meta( $user_id, 'facebook_id', $facebook_id );
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
$response = array(
'success' => true,
'message' => 'Registration and login successful'
);
}
}
echo json_encode( $response );
wp_die();
}

Wordpress - Javascript redirect after login success not working

I'm building my wordpress login page, everything is working fine. So I decided to implement facebook social login using their SDK. Social login works fine and login successfully.
The problem is that after login the user should be directed to the homepage of the website "www.mywebsite.com". I tried to manage the redirect with javascript code, but after successful login no redirection happens.
Can anyone help me figure out what I'm doing wrong?
This is the part where I'm trying to create the redirect
jQuery.post(ajaxurl, data, function(response) {
if (response.success) {
wp_safe_redirect( '/' );
exit;
} else {
document.getElementById('login-form-message').innerHTML = response.message;
}
});
This is the complete code that concerns the social login of facebook
/* Manage Social Login Script */
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxx',
cookie : true,
xfbml : true,
version : 'v15.0'
});
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
document.getElementById('facebook-login-button').addEventListener('click', function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', {fields: 'name,email'}, function(response) {
var data = {
'action': 'facebook_login',
'facebook_id': response.id,
'access_token': FB.getAuthResponse().accessToken,
'email': response.email,
'username': response.name
};
jQuery.post(ajaxurl, data, function(response) {
if (response.success) {
wp_safe_redirect( '/' );
exit;
} else {
document.getElementById('login-form-message').innerHTML = response.message;
}
});
});
} else {
document.getElementById('login-form-message').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
});
}
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
This is the PHP code that handles the ajax request
//** Facebook Login AJAX Handler **/
function facebook_login_handler() {
// Verify ID token
$facebook_id = $_POST['facebook_id'];
$access_token = $_POST['access_token'];
$email = $_POST['email'];
$username = $_POST['username'];
$response = wp_remote_get( 'https://graph.facebook.com/v3.3/' . $facebook_id . '?access_token=' . $access_token );
$facebook_response = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! isset( $facebook_response['id'] ) ) {
$response = array(
'success' => false,
'message' => 'Invalid Facebook ID token'
);
echo json_encode( $response );
wp_die();
}
// Check if the user already exists in our database
$user = get_user_by( 'email', $email );
if ( ! $user ) {
$user = get_user_by( 'login', $username );
}
if ( $user ) {
// Update user meta with Facebook ID
update_user_meta( $user->ID, 'facebook_id', $facebook_id );
// Log the user in
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID );
$response = array(
'success' => true,
'message' => 'Login successful'
);
} else {
// If the user does not exist, create a new account
$user_data = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => wp_generate_password()
);
$user_id = wp_insert_user( $user_data );
if ( is_wp_error( $user_id ) ) {
$response = array(
'success' => false,
'message' => $user_id->get_error_message()
);
echo json_encode( $response );
wp_die();
} else {
update_user_meta( $user_id, 'facebook_id', $facebook_id );
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
$response = array(
'success' => true,
'message' => 'Registration and login successful'
);
}
}
echo json_encode( $response );
wp_die();
}
Man, wp_safe_redirect() - this is wordpress function, not javascript...
Use location.href = 'Your Url'
After several hours of searching I figured out that the problem lay in: jQuery.post(ajaxurl, data, function(response). So I changed the code as follows and the redirect is working fine.
From this
jQuery.post(ajaxurl, data, function(response) {
if (response.success) {
location.href = '<?php echo home_url(); ?>';
} else {
document.getElementById('login-form-message').innerHTML = response.message;
}
});
To this
// Invia la richiesta ajax al server per elaborarla
$.ajax({
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: data,
success: function(response) {
console.log(response);
if (response.success) {
// reindirizzamento alla pagina home
window.location.href = '/';
} else {
// reindirizzamento alla pagina di login
window.location.href = '/experimental-layout';
}
}
});

jsGrid: How to pass additional variables from javascript to php using ajax

I'm using jsGrid for my project. View here for original source code
I want to pass an additional variable call $user_session to use for mysql select query in fetch.php but failed. Below is what i have been trying.
<script>
var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//......
controller: {
loadData: function(){
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: {user_session:user_session} //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
});
},
//......
Here's the fetch.php file
<?php
if($method == 'GET')
{
$user_session = $_GET['user_session']; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute($user_session); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'id' => $row['id'],
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'age' => $row['age'],
'gender' => $row['gender']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
//......
?>
What is the proper way to do this?
First of all, anyone could open up a dev console inside a browser and start fuzzing your session id. While you are correctly preparing your query, defusing sql injection, it does does not protect you from an IDOR, or, i could enumerate your users by just querying your application repeatedly.
If you really want to pass your session id client-side, maybe you could consider using a cookie, as it is less easily editable by a normal user.
I'm able to do by this way.
<script>
//......
controller: {
loadData: function(filter){
var user_session = "<?php echo $user_session; ?>"; //<<<<<<<<<<<<<<<<<<<<<<<<<<<
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: {filter,
user_session:user_session //<<<<<<<<<<<<<<<<<<<<<<<<<<<
},
});
},
//......
</script>
In fetch.php i do this.
<?php
if($method == 'GET')
{
$user_session = $_GET['user_session'];//<<<<<<<<<<<<<<<<<<<<<<<<<<<
$query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'id' => $row['id'],
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'age' => $row['age'],
'gender' => $row['gender']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
//......
?>
For the security issue mentioned by #Andrea Golin, i will post another question.Thanks.
Finally, i found a better way.
I can directly call $user_session inside fetch.php.
<?php
require('user_session.php'); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
require('includes/db.php');
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'GET')
{
$query = "SELECT * FROM sample_data WHERE first_name=? ORDER BY id DESC";
$statement = $conn->prepare($query);
$statement->execute([$user_session]); //<<<<<<<<<<<<<<<<<<<<<<<<<<<
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'ChildID' => $row['ChildID'],
'Name' => $row['Name'],
'BirthDate' => $row['BirthDate'],
'Gender' => $row['Gender'],
'StudyorWorking' => $row['StudyorWorking'],
'CourseorOccupation' => $row['CourseorOccupation'],
'Married' => $row['Married']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
?>

Json Encoded PHP array has null appended to it

At this point in the debugging this is what I am sending to my javascript
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array());
and here is my ajax call
jQuery.get( "non public api sorry ")
.done(function(data) {
console.log("I got a response")
console.log(data)
})
.fail(function(data) {
console.log("Error?")
console.log(data);
})
It errors everytime and in the data my response string for the empty array is
"[]null"
Entire function being called for reference same thing I get an error and at the end of my json there is "null" appended.
function getAllProducts() {
$full_product_list = array();
$loop = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => -1 ) );
$pf = new WC_Product_Factory();
while ( $loop->have_posts() ) : $loop->the_post();
$post_id = get_the_ID();
$product = $pf->get_product($post_id);
$attributes = $product->get_attributes();
$attrs = array();
foreach ($attributes as $attr) {
$name = str_replace("pa_fablab_", "", $attr["name"]);
$attrs[$name] = $attr["value"];
}
$item = array(
"id" => $post_id,
"name" => get_the_title(),
"price" => $product->get_price()
);
if (sizeof($attrs) > 0) {
$full_product_list[] = array_merge($item, $attrs);
}
endwhile; wp_reset_query();
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array());
}
Return something from your php page, add die() after to remove the null
header("Content-Type: application/json");
//echo json_encode($full_product_list);
echo json_encode(array("message"=>"ok"));
die();

Passing Php Variable to another variable using ajax?

I have this JS/jQuery code
window.onload = function(){
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "GET",
dataType: "html"
//data: {$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
EDIT: This is the method where I get the $lastid.
<?php
function woocommerce_dashboard_recent_orders() {
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'shop_order',
'post_status' => 'publish'
);
$orders = get_posts( $args );
if ($orders) :
echo '<ul class="recent-orders">';
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
$lastid = $order->ID;
echo '</ul>';
else:
echo '<p>' . __( 'There are no product orders yet.', 'woocommerce' ) . '</p>';
endif;
}
?>
That calls a php file called test.php.
test.php
<?php
//woocommerce_dashboard_recent_orders_realtime();
/**
* Init the dashboard widgets.
*
* #access public
* #return void
*/
function filter_where( $where = '' ) {
$oid = 2100;
$where = " AND ID > $oid";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'shop_order',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
$orders = get_posts( $args );
if ($orders) :
foreach ($orders as $order) :
//echo " $order->ID";
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
//echo (gettype($time3));
endforeach;
endif;
//}
?>
What I want to do is to pass the $lastid from the javascript to the test.php file and receive it as something like $lastid also.
I know I should post, but I'm having trouble using it. Can anyone lead me to the right method?
My CODE now
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" >
window.onload = function(){
//setInterval(function(){
//var lastid = '<?php echo $lastid; ?>';
//alert(lastid);
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "POST",
dataType: "html",
data: { lastid : '<?php echo $lastid; ?>'},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
//addElement();
//},1000);
setInterval(function(){
},1000);
}
</script>
<?php
function woocommerce_dashboard_recent_orders() {
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'ASC',
'post_type' => 'shop_order',
'post_status' => 'publish'
);
$orders = get_posts( $args );
if ($orders) :
echo '<ul class="recent-orders">';
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
$lastid = $order->ID;
echo '</ul>';
else:
echo '<p>' . __( 'There are no product orders yet.', 'woocommerce' ) . '</p>';
endif;
}
?>
<?php
function filter_where( $where = '' ) {
$oid = 2110;
$where = " AND ID > $oid";
return $where;
}
$lastid = $_GET['lastid'];
add_filter( 'posts_where', 'filter_where' );
$args = array(
'numberposts' => 8,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'shop_order',
'post_status' => 'publish',
'suppress_filters' => FALSE
);
$orders = get_posts( $args );
echo "LAST ID: $lastid";
if ($orders) :
foreach ($orders as $order) :
$this_order = new WC_Order( $order->ID );
echo '
<li>
<span id = "order-$order->ID" class="order-status '.sanitize_title($this_order->status).'">'.ucwords(__($this_order->status, 'woocommerce')).'</span> ' . get_the_time( __( 'l jS \of F Y h:i:s A', 'woocommerce' ), $order->ID ) . '<br />
<small>'.sizeof($this_order->get_items()).' '._n('item', 'items', sizeof($this_order->get_items()), 'woocommerce').' <span class="order-cost">'.__('Total:', 'woocommerce' ) . ' ' . woocommerce_price($this_order->order_total).'</span></small>
</li>';
endforeach;
endif;
remove_filter( 'posts_where', 'filter_where' );
//}
?>
I'm not sure if I understand if I understand your question, but it seems like your first page has already evaluated $lastId, most likely from an insert query... and you want to also set it to a javascript variable, while also using post method. Assuming all that this is how I would for the first page
<script>
var $lastid = <?php echo $lastid ?>;
...
window.onload = function(){
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php",
type: "POST",
dataType: "html"
data: {"lastid":$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
....
</script>
Then on the second page use this to access the post
<?php
$lastid = $_POST['lastid'];
?>
That is how you do post in php hope this helps.
Try the following in the original code
...
url: "../wp-content/plugins/woocommerce/admin/test.php?lastid=2098"
...
Then in test.php, access the variable using
$lastid = $_GET['lastid'];
There are several other ways that this can be done, this is just a quick and dirty method.
1. Send the variable:
Change:
//data: {$lastid},
to:
data: { lastid : '<?php echo $lastid; ?>'},
2. Get variable in test.php:
$lastid = $_GET['lastid'];
window.onload = function(){
var lastId = <?php echo $lastId; ?>;
var request = $.ajax({
url: "../wp-content/plugins/woocommerce/admin/test.php" + "?lastid=" + lastId,
type: "GET",
dataType: "html"
//data: {$lastid},
});
request.done(function(msg) {
$(".recent-orders").append(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
on test.php add this line
$lastId = $_GET['lastid'];

Categories

Resources