For a hobby, I am building a simple chat script and would like to implement a "/kick" feature in it. For that, I have a form for chat input and send.php file that processes input. I would like to be able to /kick all users and redirect them to login.php with ajax. But the problem I have is that echo from send.php seems not to get to ajax and it does not fire redirect. So far I have:
send.php
...
elseif($_POST['text'] == "/kick")
{
unset($_SESSION['username']);
unset($_SESSION['enterTime']);
session_destroy();
$sql = "DELETE FROM sjednice";
mysqli_query($conn, $sql);
echo "1";
}
...
ajax
var intervalTimer = window.setInterval(function kick(){
$(document).ready(function(){
$.ajax({
method: 'post',
url: 'send.php',
dataType: 'text',
success: function(data) {
if(data == "1")
{
//this is not getting executed
window.location.href = "login.php";
}
}
});
});
},100);
Edit:
I have this jquery form library that handles form submit without refreshing the whole page, so chat would not refresh all the time. The form action is to send.php separate file and send.php caontains header redirect in this elseif in the above code.
Could this be the reason why php header location is not redirecting? Because I have tried php header to redirect but only in this case it does not work.
Related
I have this following code that works at the moment. What I want is to remove the url and process the ajax request on the same page. Since I am not sending any data, how can I have php check when my ajax function is ready to send a request to the database?
I'm using jquery mousedown to hold on to a button, then after 1 second the user receives a prompt to delete. If the user holds button 5 on the list, it will delete row 5 in mysql table, button 10 will delete row 10 etc.
$("#outter_div_5").mousedown('#button_5', function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user== "d")
{
$.ajax({
url: './ajax/5/delete.php', // <-- I want to remove this line and process this ajax request on the same page
type:'POST',
data: {},
success:function(result){
$("outter_div_5").fadeOut(125);
},
complete:function(data){
$.ajax({
url:'reload_table.php',
method:'POST',
success:function(data){
// reload javascript variables and html table
$("#my_table").html(data);
}
});
}
});
}
}, 1000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});
And my delete.php page is a simple mysql query, I'm not using a php isset since I am not passing any data.
include_once './includes/db.inc.php';
$sql = "UPDATE my_table SET row = '' WHERE id = '5' ";
mysqli_query($conn,$sql);
I need to create a php isset so that I can process this ajax request on the same page. How can I do this?
<?php
if( isset($_POST['']) ){
$sql = "UPDATE my_table SET row = '' WHERE id = '5' ";
mysqli_query($conn,$sql);
}
?>
<script>
$("#outter_div_5").mousedown('#button_5', function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user== "d")
{
$.ajax({
url: './ajax/5/delete.php', // <-- I want to remove this line and process this ajax request on the same page
type:'POST',
data: {},
success:function(result){
$("outter_div_5").fadeOut(125);
},
complete:function(data){
$.ajax({
url:'reload_table.php',
method:'POST',
success:function(data){
// reload javascript variables and html table
$("#my_table").html(data);
}
});
}
});
}
}, 1000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});
</script>
The main advantage of an HTTP (with AJAX in your case) request is that you don't have to reload the page or redirect the user to pass information the server. Some other advantages and more info can be found here. Note that php code is run before any of your javascript is run.
If you don't want to use an HTTP request, you have multiple solutions. Here's mine:
Rather than such HTTP request, you can use a form with method="POST" (read all about that) that uses a prompt before submitting:
$("#delete_button").click(function( event ){
event.preventDefault();
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user == "d") {
console.log("submitted");
//$("#myForm").submit();
}else if( prompt_user == "e" ) {
console.log("editing");
// Add your actions for editing the thing you want to edit.
}else {
console.log("aborted");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form id="myForm" action="" method="POST">
<!-- You can add inputs here to add to your POST
This data can be read when the form is submitted and the page is consequently reloaded. -->
<input id="delete_button" type="submit" value="delete">
</form>
However, if I'm being honest, I would stick with the HTTP request as this can provide a more slick user experience.
I understand you are a beginner so please feel free to ask questions if you don't understand something, we have all been there (and maybe I am still there :p).
I'm using this jQuery code to submit a dynamic form :
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('inc/siteform.php', $(this).serialize());
});
but this method only sends the data to the PHP file. I want also that it redirects me to there, as an ordinary PHP POST submission.
How can I do it?
Here is the full testing site: http://edge-americas.com/control/main.html
UPDATE:
Using the method JQuery redirects me but it doesn't send the formdata at the same time so I can't use $_POST[] variables:
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('inc/siteform.php', $(this).serialize(),function(response){
window.location = "inc/siteform.php";
});
});
Is there any other way to keep using jquery and solve it?
You can also use window.location.replace() and pass in the URL of where you want to be redirected as a paramter.
Location.replace() for more information on the method.
Javascript works perfectly for this:
window.location.href = "URL";
Or as Andy pointed out if you want users to go back without issues simply drop the .
window.location = "URL";
You can redirect or refresh page after succcess or server answer. For example:
$.ajax({
url:"?show=ajax_request&action=add_offer",
type:"POST",
data: {var_to_send : somevar},
dataType: "json",
success: function(answer){
if ( answer.result == 'success' )
{
location.reload(); // refresh the page
}
else if ( answer.result == 'error' )
{
window.location.href = "http://google.com"; // redirect to another page
}
}
});
I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions
I am using the Jquery form plugin to submit a login form data. This works well but I have problem redirecting a successful logged in user to the client panel from the login page in my PHP script, that is whenever the user is logged in successfully, I redirect using header("location:panel.php") in my php script, this page is sent back to the login page as a response and it will be embedded in the login page instead of showing as a whole page.
jquery code;
$(document).ready(function(){
$("#loginform").ajaxForm({
target: '#responselogin'
}).submit();
});
php code;
<?php
$username=$_POST['username'];
$password=$_POST['password'];
if($username=="tarhe" && $password=="oweh") {
header("location:panel.php");
} else {
echo"login failed";
}
?>
Please I need help, thanks in advance
your using ajax, so your 301 location header will have no effect to the overall browser window. you will have to return a structured data to your javascript and have javascript redirect instead.
$(document).ready(function(){
$("#loginform").ajaxForm({
success: function (data) {
if (data == "login failed") {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
its actually better if you use json response for this. Since it's formatted better for browser consumption.
for handling this using json you can do the following. first change your php code to return a json response
$success = 0;
if($username=="tarhe" && $password=="oweh") {
$success = 1;
}
echo json_encode(array('success' => $success));
Then in your javascript code
$(document).ready(function(){
$("#loginform").ajaxForm({
type: 'json',
success: function (data) {
if (data.success == 0) {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
I don't think you can use the location flag inside the http header with ajax. Think about it: You submit a form with ajax, so you're getting the response back in Javascript, and not into the browser.
Bind a success handler to the .submit() form, and set window.location.href=http://your-url.com
You are using ajax so make a response data and on success redirect the user.
window.location.href = "somewhere.html";
I have a php script, only for learning purposes. I would like to use on my web app ajax form. Never did it, this is testing php script. So I would like to send via ajax form name and password, in php script will be checked if its correct and it will return either success(when login and password correct) or error(when no match). My problem is how to send it and receive it correctly in js or jQuery. Anyone who could help me maybe with better idea and/or better secure function of doing this?
I found on stackoverflow and tryed this script:
//bind an event handler to the submit event for your login form
$('#login_form').live('submit', function (e) {
//cache the form element for use in this function
var $this = $(this);
//prevent the default submission of the form
e.preventDefault();
//run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
$.post($this.attr('action'), $this.serialize(), function (responseData) {
//in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
});
});
And I was wondering if in php script it could work like this?:
<?php
$username = $_GET["name"];
$password = $_GET["password"];
if($username="*****" && $password==********)
{
header('Location:http://*****************/jaz/imes/index.html?login="success"');
}else{
header('Location:http://*****************/jaz/imes/index.html?login="error"');
}
?>
And as I said this is just a test script just for learning more about it.
First of all, try to use on() method if you're using jQuery 1.8+
Another thing is that you should set the session for that user in the PHP script, then redirect the user using the js:
jQuery:
$('#login_form').on('submit', function(){
$.post($this.attr('action'), $this.serialize(), function (responseData) {
if(responseData == 'success'){
window.location = "userpanel.php"
}else{
alert('NO MATCHES');
}
});
});
PHP:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// VALIDATING HERE, in db maybe?
if($username == 'blah' && $password == 'blah'){
$_SESSION['username'] = $username;
echo "success";
}else{
echo "failed";
}
?>
And in your HTML form you need to have 2 inputs with IDs as "username" and "password" so the above code could work.