I tried to reload the page if session is empty but I am unable to do this as the ajax code as below
function test()
{
$this = $(this);
$.ajax({
url: 'view/test/test.php',
datatype: 'html',
async:true,
beforeSend : function(){
$('#ajax_loader').show();
$('#content').hide();
},
success: function(data){
if(data=='cannot')
{
location.reload(true);
}
else
{
$('#ajax_loader').hide();
$box = $('#content');
$box.after(data);
$box.remove();
}
}
});
}
$(document).on('click','#test',$(this),test);
and the view test file as
<?php include '../../config.php';
if(empty($_SESSION['college_id']))
{
echo "cannot";
return;
}
?>
The above code is used to check whether session exist or not. If session is empty is simply send "cannot". As the I got the success data as "cannot", I tried to reload the page but the reload function does not work in if condition. Without if condition, it does work. What's wrong?
can u try this once in you code it may work for you
if($.trim(data)=='cannot')
{
alert("your session has been expired");
document.location.reload(true);
}
Try to change dataType to text and try . Also try to trim the success call back response data before string comparision
Before using the $_SESSION superglobal variables you must start or resume the session by writing
session_start()
Note: This has to be the very first thing (even before the HTML tags)
Related
Hi im having a problem refreshing my page when a condition is met in php using ajax, if the php script is successful i want it to reload the page but when it is not then i only want to echo the errors.
The following is the part of my PHP code that returns the 'success' or error message:
if ($login) {
echo "success";
} else {
echo '<p>Username and Password does not match</p>';
};
This is working as i have tested it separately and the user gets logged in even though ajax
The problem i think comes in the ajax call back with the if statement.
Here is the my js script that is running the ajax call back.
$('form.ajax').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
if(response == "success") {
//location.reload();
window.location = "index.php";
} else {
$('#loginError').html(response);
};
}
});
return false;
});
I have tried everything on the net but every time the PHP script is successful it just echo's out the word success rather then redirecting the page or reloading
Thanks chris85 for the perfect advice worked like gold and was able to fix the problem, that was that there was a extra line at the top of my PHP script that I missed and saw it when i used console.log(response), also read the post you linked and it will help with future problems like this for me so thanks again.
Here is my problem:
I try to make an Ajax call with JQuery,
this calls a PHP page, the code gets executed, and echoes OK if alright, STOP if not.
I don't get any text back (first problem),
and the real problem is that:
SOMETIMES the query succeeds, but ALWAYS returns an error. (even if my sql query in php page gets executed)
Here is the code :
<script>
$("a.confirm").click(function(event){
var id = event.target.id;
$.ajax({
type :"POST",
url :'./PHP/UTILS/confirm.php',
data :{ "id" : id,
},
beforeSend: function(){
alert("in progress");
},
complete: function(){
alert("done");
},
success: function(){
alert("OK");
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err + "\n");
}
});
});
</script>
This is for the ajax, now the page it calls :
<?php
include "./functionsExt.php";
$db = connectToDb('mydb');
$id = $_POST['id'];
$mysql = $db->prepare("UPDATE `test` SET `test_date_p` = CURRENT_TIMESTAMP, `test_status` = '2' WHERE `test_id` = '$id'");
if($mysql->execute()){
echo "OK";
}else{
echo "STOP";
}
?>
Thanks for help
i would like to suggest that you should try it after removing the comma in data after 'id'.
And i please do mention the following :
echo the post variable and check the response.
then echo that you want and check whether it is coming or not in response
a better way to write the success and failure
success: function(data)
{
alert(data);
}
failure : function(){
alert(failed);
}
It will eventually alert you with the data that you are receiving in response. So it is good for testing purpose.
hope it helps:)
i think i found something interesting...
i tried echoing the post...
The post is well sent to the php file,
But i noticed that :
if i add event.preventDefault(); in my jquery code, i have the post echo + the "ok" displayed in an alert (guess it's the success alert cuz i don't have the log message this time...)
i will try again... (if it works like this, i need then to find a way to re-enable default link click function, i need to refresh the page... the page content is not the same after calling the ajax...)
tried again, and it seems to work now...
but, i don't close the topic, cause i have to add few more queries in my php file now... and i still need a way to refresh the page after execution... any idea?
(thanx stacky, you advice seems to have solved the "main" problem :P )
I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.
hello all this is the code for ajax form submition which shows the error when there is any error otherwise it redirects the page to anothera page .
it works fine when i am working on my localhost(server2go) but when i put it on the host server it just dosent redirects
i want when the callback function receivs the data loginsu4343fu15 it should redirect to mypage.php but it just alers the code
function loginbyajax(){
$.ajax({
type: 'POST',
url: 'loginform_process.php',
data:$("#loginme").serialize()+ "&widthis=" + screen.width,
success: function(data){
if(data=='loginsu4343fu15'){
window.location.href = "Mypage.php";
}else{
alert (data);
}
}
});
return false;
}
please try this (this is only a possibility)
use this
if($.trim(data)=='loginsu4343fu15'){
instead of
if(data=='loginsu4343fu15'){
trim the white space and check the data.
I'm having trouble submitting an ajax request.
I've tried to set it up pretty simply just to see if i can get a response
Here is my js:
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
type: "POST",
url: "processform_ajax.php",
data: $(this).serializeArray(),
dataType: "json",
sucess: function (data) {
alert("data" . data);
//$("#response").append(data);
},
error: function(error, txt) {
alert(error.status);
}
});
});
});
My php is simply this
<?php
$errors = array ('a' => 'TEST!');
echo json_encode($errors);
?>
When I try to run this with the firebug extension i'm seeing the post looks okay. (which it shouldn't matter at this point, because my php just echo's out something)
On the response side I'm seeing this error : NS_ERROR_NOT_AVAILABLE
Which leads me to believe it can't find processform_ajax.php, but when i've tried the absolute url in url: "" option above. I can also hit the the php script through the browser's address bar and get the json response
Any clues?
Thanks
NS_ERROR_NOT_AVAILABLE seems like a Firefox "bug/feature" where it tries to submit the call twice.
Try this... add a return false in your code, like this:-
$(document).ready(function() {
$('#mainform').submit(function() {
$.ajax({
...
});
return false;
});
});
This way, once the form is submitted through your JS code, the return false will prevent your "Submit" button from submitting the same request again.
Is sucess a typo in your code, or just on SO?