Jquery form plugin - php

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";

Related

php script response to ajax does not work

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.

Post form and redirect to PHP

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
}
}
});

How to stop jQuery post page refresh

I am getting data from an MySQL database through PHP. I am sending the and getting the data from PHP using jQuery. Here is the code.
$.POST("SubmitCode.php", $("#questionCodeForm").serialize(),'json').done(function(data) {});
Now the problem is that once I send this data the page refreshes. How can I stop the page refresh. If I delete 'json' then the page stops refreshing but the problem is that I want to get the json data without page refresh. How can I do this?
-------------------------------------------after edit-----------------------------------------------------------------------------
Here is the updated code
$(document).ready(function() {
initialization();
codeSubmission();
});
function initialization() {
$("#answerForm").hide();
}
function codeSubmission() {
$("#submitButton").click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize()).done(function(data) {
var questionName = data.questionName,
options = data.options,
pollingStatus = data.pollingStatus,
codeExist = data.codeExist;
alert(data);
alert(data[1]);
alert(questionName);
alert(options);
if(codeExist == true) {
$("#questionTitle").text("questionName");
for(rowNum=1;rowNum<=5;rowNum++) {
$("#checkbox-"+rowNum).val("Answer1");
$("#checkbox"+rowNum+"label").text("Answer"+rowNum);
}
$("#answerForm").slideDown(500);
} else if(codeExist == false) {
alert("This quiz code is invalid");
}
},'json');
//return false;
});
//return false;
}
Now the problem is that the output of alert(questionName) is undefined. The data is passed as a string. How do I get the correct information in the correct variables?
Try this instead: (note the placement of the callback function, and lowercase .post method)
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
Also make sure that whatever is triggering the post isn't an actual link and if it is, you need to stop the default action from occuring. For example:
Click here to submit
javascript:
$(a).click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
});
You also have to parse the json on the client side. You can do this using
obj = jQuery.parseJSON(data);

How to clear the session using a button and javascript

Session is client side staff, but is it possible through clear it using javascript code?
I would like too have the idea like this and ,can it convert to jquery format? Thank you.
js
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
$.post("clear.php",function(data){
});
});
});
php
<?
if (isset($_SESSION['lname']))
unset($_SESSION['lname']);
if (isset($_POST['creminder']))
unset($_SESSION['creminder']);
?>
Is this one ok ?
make an ajax call to the server and let your server page kills/ends the session
HTML
<a href="#" id="aKill" > Kill Session</a>
Script
$(function(){
$("#aKill").click(function(){
$.post("serverpage.php",function(data){
// if you want you can show some message to user here
});
});
and in your serverpage.php, Execute the PHP script to terminate the session.
Create a separate file to clear the session only. clearsession.php
session_start();
session_destroy();
Now, make a simple request
$("#aKill").click(function(){
$.get("clearsession.php");
}
The below covers the basics more or less.
The Function:
function destroySession(){
var theForm = $("#yourForm");
//we don't need any ajax frame.
theForm.each(function(){ this.reset() });
$.ajax({
url: 'destroysession.php',
type: 'post',
data: 'sure=1', //send a value to make sure we want to destroy it.
success: function(data);
alert(data);
}
});
}
The PHP (destroysession.php):
<?php
//whatever logic is necessary
if(!empty($_POST['sure'])){
$sure = $_POST['sure'];
if($sure == 1){
//logic to destroy session
echo 'Session Destroyed!';
}else if($sure != 1){
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
}else{
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
?>
The HTML:
<input type='button' value='reset' onclick='destroySession()'>

JQuery and PHP validation problem?

I want to do the validation on my PHP side and then have my JQuery code display your changes have been saved when the submit button is clicked but the JQuery code states that the changes have been saved even when the validation fails.
How can i fix this so that PHP can do the validation and then JQuery can do its thing when PHP has finished its validation?
Here is my Jquery code.
$(function() {
$('#changes-saved').hide();
$('.save-button').click(function() {
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(html) {
$('div.contact-info-form').html(html);
$('#changes-saved').hide();
$('#changes-saved').html('Your changes have been saved!').fadeIn(4000).show();
});
$('a').click(function () {
$('#changes-saved').empty();
$('#changes-saved').hide();
});
return false; // prevent normal submit
});
});
Here is part of my PHP code.
// Check for an email address:
if (preg_match ('/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) {
$email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));
} else {
echo '<p class="error">Please enter a valid email address!</p>';
}
in the jquery you can add a if statment that check if the php validation pass,
in the php you need to return a value like 1\0 or true \ false.
and check this parameter in jquery
i add example its using json but is the same issue
jquery :
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(data_pack){
if(data_pack.msg ==1){
# success do something ....
.........
}
alert(data_pack.html);
}, 'json');
the php code like :
if($validation_ok){
$arr = array('msg'=>1,'html'=>$html);
}
else {
$arr = array('msg'=>0,'html'=>$error_msg);
}
echo json_encode($arr);
exit;
You should validate it with both client-side and server-side (ie. with both JavaScript and PHP). If this is not possible, I'd consider posting the form asynchronously and parsing the reply from the server with javascript to determine whether the changes were saved.

Categories