Redirect in PHP on AJAX call - javascript

I need to redirect to another page in my PHP code on an AJAX call. The only thing I can seem to find online about this is to do it through JavaScript using window.location.href = 'url'; but it does not work.
If I try to redirect using the window.location.href to profile.php?user=person then it has the url localhost/profile.php?user=person but if I type in the full URL for the redirect like project/login/profile.php?user=person then it stays on the same page. The profile.php page only echo's what who the user in the url is.
Any ideas?
Here is my code:
$.ajax({
url: 'processes/login.inc.php',
type: 'post',
data: data,
success: function(res) {
if(res != '4502') {
var s = 'profile.php?user='+res;
window.location.href = s;
}
}
});
and the PHP:
<?php
require_once('../core/init.php');
$username = escape($_POST['ul']);
$password = escape($_POST['pl']);
$user = new User();
$login = $user->login($username, $password);
if($login) {
// Redirect::to('../profile.php?user='.$username);
echo $username;
} else {
echo '4502';
}

You have to assign the full path, not only the php file and parameters, for example:
Change:
location.href = 'profile.php?user=person';
To:
location.href = '/login/profile.php?user=person';

Related

Wordpress wp_signon() do not work in ajax call

I am trying to build an costum login to Wordpress in a AJAX call. I a remove the wp_signon() from the PHP function I do get the right echo. But then I add the wp_signon() it always return my whole login page in HTML. I can't see what I am doing wrong. And can't get the login to work.
Please help!
js
$.ajax({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
'action': 'getLoggedIn',
'user_name': user_name,
'user_password': user_password,
'user_remember': user_remember
},
success: function(response) {
if (response === 'ok') {
window.location = '/app/';
}
},
error: function(){}
});
PHP
function getLoggedIn() {
global $wpdb;
// Check if users is already logged in
if ( is_user_logged_in() ) {
echo 'You are already logged in';
die;
}
//We shall SQL escape all inputs
$username = $wpdb->escape($_REQUEST['user_name']);
$password = $wpdb->escape($_REQUEST['user_password']);
$remember = $wpdb->escape($_REQUEST['user_remember']);
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = $remember;
$user_signon = wp_signon( $creds, false );
// Check if error
if ( is_wp_error($user_signon)) {
echo $user_verify->get_error_code();
exit();
} else {
echo 'ok';
exit;
}
die();
}
add_action('wp_ajax_getLoggedIn', 'getLoggedIn');
add_action('wp_ajax_nopriv_getLoggedIn', 'getLoggedIn');
The problem was not the wp_signon() function. It was an other Wordpress action that redirects the page after user login has failed. This:
add_action( 'wp_login_failed', 'login_failed' );
I got caught up in the same situation. did you remove that wp_login_failed action or how did you work this out?

Reload data from database without refreshing page

My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function () {
var k = document.getElementById("balanceNumber");
k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
}
}
);
}
and the handler.php
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
//$link = mysqli_connect("localhost","username","password", "users");
$bal = $userRow['userBalance']+$_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
Can anyone suggest me how to update this information without refreshing the page?
The issue is that you are trying to run php in the client side when you wrote k.innerHTML="string"+php code
You should instead produce an output in the php file you request to and retrieve that output and put it in here.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
The link explains how to send data to server through POST and get data from server through GET.
there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type:
$.ajax({
'url': 'getdata.php',
'type': 'GET',
'dataType': 'json',
'data': {'topUpBalance':d},
'success': function(data) {
// if the request calls properly
},
'error': function(data) {
// if the request fails.
}
});
The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-
if(isset($_POST['topUpBalance'])){
$res=mysqli_query($link, "SELECT * FROM users WHERE
userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
$bal = $userRow['userBalance'] + $_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
//Send output echo ...... ;
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
In jquery side :-
receive data using parameter
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function (data) {
// use sent data or unsent data for processing
}
}
);
}

Ajax call using php file placed in theme folder in Osclass classified script?

I am using Osclass classified script, trying to alert a message returned by ajax call.
My ajax-test.php file which is saved in my theme folder contains
<?php
$name = $_GET["name"];
echo "I am " . $name
?>
and my JavaScript function code is
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
// url: "oc-content/themes/bender/ajax-test.php",
url: 'http://127.0.0.1/osclass/index.php?page=ajax&action=custom&ajaxfile=ajax-test.php',
data: { name : name },
success: function (data) {
alert(data);
},
})
}
Anybody tell me what am I doing wrong? it alerts
{"error" => "ajaxFile doesn't exist"}
Note: It works fine with commented line of code
You are using
> method: "POST",
in ajax then why are you using GET ?
$name = $_GET["name"];
Using Post to getting value for it.
$name = $_POST["name"];
Unfortunatelyn, that's not exactly how the ajax.php custom action works.
First, page=ajax&action=custom doesn't work with themes, only with plugins since it will search ajaxfile inside the plugins folder by doing something like this:
$filePath = osc_plugins_path() . $ajaxfile; // eg. /oc-content/plugins/$ajaxfile
You then have to pass in ajaxfile the name of the plugin to work. If you were using the Madhouse Messenger plugin, you would do something like:
page=ajax&action=custom&ajaxfile=madhouse_messenger/main.php
However, since 3.3, when using page=ajax&action=custom, you do not use the ajaxfile param anymore but the route param. You can take a look at how routes work here and some examples of routes here.
in your theme functions.php
add something like this:
//name of your custom ajax request
$my_custom_ajax_request_name = 'doSomethingCool';
osc_add_hook('ajax_' . $my_custom_ajax_request_name, $my_custom_ajax_request_name);
function doSomethingCool()
{
// set default response
$response = [
'status' => false,
'msg' => 'Default Error Message...',
];
// token protection
// read more about csrf token:
// https://dev.osclass.org/2013/02/19/make-your-plugins-more-secure-with-anti-csrf-functions/
osc_csrf_check();
// get request parameters
$param1 = Params::getParam('param1');
$param2 = Params::getParam('param2');
// do some logic here ex: check if user is logged in
if (osc_is_web_user_logged_in()) {
$response['status'] = true;
$response['msg'] = 'User is logged in. ;-) ' . $param1 . ' ' . $param2 . '! ' . osc_logged_user_name();
} else {
$response['status'] = false;
$response['msg'] = 'User is not logged in. :-(';
}
// return json response
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
some where in your template files like header.php, footer.php or everything else you need it...
<a data-param1="hello" data-param2="world" href="#" id="make-an-ajax-request">
Make an AJAX Request!
</a>
<script>
//here we hold some usefull info for easy access
var mySite = window.mySite || {};
mySite.base_url = '<?php echo osc_base_url(true); ?>';
mySite.csrf_token = '<?php echo osc_csrf_token_url(); ?>';
$(function(){
$('#make-an-ajax-request').on('click', function(e){
e.preventDefault();
// name of our custom ajax hook
var ajax_hook = 'doSomethingCool';
// get parameters
var param1 = $(this).data('param1');
var param2 = $(this).data('param2');
// build axjxa url
var url = mySite.base_url + '?page=ajax&action=runhook&hook='+ajax_hook+'&'+mySite.csrf_token;
//build data
var data = {
param1 : param1,
param2 : param2
};
$.ajax({
type: 'POST',
dataType: 'json',
data: data,
url: url
}).done(function (data) {
console.log(data);
if (data.status) {
} else {
}
});
});
});
</script>
OSCLASS WAY
to note that the current osclass way of doing an ajax request from a theme page is to call the
http://example.com/?page=ajax&action=runhook&hook=MY_HOOK_FUNCTION_NAME
and register it like osc_add_hook('ajax_MY_HOOK_FUNCTION_NAME',
'MY_HOOK_FUNCTION_NAME'); optionally but very recommended is the use
of the csrf token that you can implement like i have done for url or
by calling the osc_csrf_token_form() directly into your form.
NON OSCLASS WAY
just create a file in your theme or everywhere you want and make sure to put this into it <?php require_once __DIR__ . RELATIVE_PATH_TO_OC_LOAD_FILE . 'oc-load.php'; ?> then build your logic into it.

Setting a session variable in PHP using AJAX

After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?
Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});
Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.

How can i add a variable in AJAX URL

I have a function in php that need an id and i need to add a variable in my ajax url the id
PHP Code:
function get_json_selected($purpose)
{
//echo $this->input->post("ids");
$ids = explode(",", $this->input->post("ids"));
$site_url = site_url($this->router->class);
if ($purpose == "EQUIPEMENT"){
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get("equipments a")->result_array();
echo json_encode(array("spares" => $result));
} else {
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get($this->active_table." a")->result_array();
echo json_encode(array("spares" => $result));
}
}
Ajax Code:
this is just example of the variable of id.
$purpose = "EQUIPMENT"; // how can i add this php variable to ajax url
url: "<?=site_url('equip_request/get_json_selected');?>", // this is the current code how can i add id in this url
or is this code right?
url: "<?=site_url('equip_request/get_json_selected/'.$purpose);?>"
var purpose = '<?php echo json_encode($purpose); ?>';
url: 'example.php?=' + purpose;
+ is the concatenator in javascript. hope this helps. spend plenty of time and add plenty of security to echoing that var into javascript. else you could find yourself viction of xss.

Categories