AJAX loaded php page not letting $_GET's find values - javascript

I have a PHP project that I'm using AJAX in to refresh a part of the page, part of that page grabs options from the URL on what it's going to show. On load and refresh this works perfectly. When AJAX is introduced to reload the php file inside of the div, the only part that doesn't work is the $_GET.
I really don't know anything about AJAX and am trying to learn, but can not figure this out for the life of me. And Google searches haven't lead me in the right direction.
AJAX:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( data ) {
$('#footer-holder').html( data );
$('#authCheck').load('authentication.php');
},
error : function(){
alert('Something wrong');
}
});
return false;
});
});
authentication.php has some $_GET commands, the page executes perfectly on refresh and everything else executes perfectly with this AJAX call except the $_GET requests.
Sample authentication.php
if(isset($_GET['test'])){
echo $_GET['test'];
}else{
echo "nothing in GET";
}
Sample index.php
echo "<div id='authCheck'>";
include 'authentication.php';
echo "</div>";

If I could understand your question then , you are trying to authenticate user. Using GET method for login is never ever a good way of doing it, even if you are using ajax,
This may help you
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : '/authentication.php',
type : 'POST',
data : $(this).serialize(),
success : function( data ) {
if(data == 'success')
//Successfully authenticated
} else {
console.log('Invalid Credentials')
}
},
error : function(){
alert('Something wrong');
}
});
return false;
});
});
in PHP
//Check username and password, Checking isset POST is not enough for security
if($_POST['username'] != '' && $POST['password'] != ''){
//Do you logic to check password id correct or not
//if true
//echo success
//else
//echo 'fail'
}else{
echo "Invalid credentials";
}
hope this will help you

Related

How to redirect url after login successful via Ajax call in php?

I want to know that how to redirect url after login successful via Ajax call in php? Kindly check my code what I am doing wrong.
Below is the registration.php file on url http://localhost:8080//myproject/adminseller/registration.php:
<script>
function createLogin () {
//alert("Hello! I am an alert box!!");
var data = {
'email' : jQuery('#email').val(),
'password' : jQuery('#password').val(),
}; // data obect End
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/login.php',
method : 'POST',
data : data,
success : function(data){
//alert(data); // For checking Code in alert
if (data != 'passed') { // passed is else statement in
check_address.php when no errors are showing
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//alert('passed!');
//clear the errors if any
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Below is the Login.php File
<?php
if (isset($_POST['email'])) {
$email = sanitize($_POST['email']);
}
if (isset($_POST['password'])) {
$password = sanitize($_POST['password']);
}
// echo $email; // Output x2a0889#gmail.com
// echo $password; // 123456
// Email and password matched and no erros so I am removing validations code from here, So else condition will execute here
// Check for Errors
if (!empty($errors)) {
echo display_errors($errors);
}else{
// Assume here login is successful
echo 'passed';
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is: http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
}
?>
My problem is that after successful login the url is not changing it still
http://localhost:8080//myproject/adminseller/registration.php
And I want to redirect my page http://localhost:8080//myproject/adminseller/index.php
After successful login.
Any idea or suggestion would be welcome.
You need to use window.location.href not location.reload();
<script>
function createLogin () {
//alert("Hello! I am an alert box!!");
var data = {
'email' : jQuery('#email').val(),
'password' : jQuery('#password').val(),
}; // data obect End
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/login.php',
method : 'POST',
data : data,
success : function(data){
//alert(data); // For checking Code in alert
if (data != 'passed') { // passed is else statement in
check_address.php when no errors are showing
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//alert('passed!');
//clear the errors if any
jQuery('#modal_errors_1').html("");
window.location.href = "http://localhost:8080//myproject/adminseller/index.php";
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Below is the Login.php File
<?php
if (isset($_POST['email'])) {
$email = sanitize($_POST['email']);
}
if (isset($_POST['password'])) {
$password = sanitize($_POST['password']);
}
// echo $email; // Output x2a0889#gmail.com
// echo $password; // 123456
// Email and password matched and no erros so I am removing validations code from here, So else condition will execute here
// Check for Errors
if (!empty($errors)) {
echo display_errors($errors);
}else{
// Assume here login is successful
echo 'passed';
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is: http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
}
?>
You are currently redirecting the AJAX request.
You cannot redirect from the PHP side on a successful AJAX request.
You can catch the returned value from Javascript however and redirect from there.
Rather than calling the header location within your PHP script, put this within the if statement checking if the response was passd
window.location.href = 'index.php';
This will cause the browser to go to index.php.
You are redirecting in Ajax call, which should not be the case. Please remove this line from PHP code:
**// Here is the problem via Ajax Call url is not redirecting after login successful, and always getting url is:
http://localhost:8080//myproject/adminseller/registration.php **
header('Location:index.php');
And then replace your following JS code:n.
//clear the errors if any jQuery('#modal_errors_1').html("");
location.reload();
With Following code:
//clear the errors if any jQuery('#modal_errors_1').html("");
window.location.href = 'index.php';

Update a DIV tag from PHP

I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});

Returning html as ajax response

I have web page that submits a form via AJAX in codeigniter, submission works great, and the php script works as well, but when php is done it return an HTML view as a response to Ajax so it repopulates a div but instead of repopulating it try's to download the file. Chrome console shows
Resource interpreted as Document but transferred with MIME type application/text/HTML
has me confused because I use the same code in another page and it works fine.
This is my Jquery script
$("#addpaymentform").submit(function (event) {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
data: formdata,
url: baseurl + 'sales/add_payment',
success: function (data, status, xhr) {
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
$('#paymets').html();
$('#payments').html(data);
$('#addpaymentform').each(function() { this.reset() });
}
if (ct.indexOf('json') > -1) {
$("#Mynavbar").notify(
data,
{position: "bottom center"}
);
$('#addpaymentform').each(function() { this.reset() });
}
}
});
event.preventDefault(); // this will prevent from submitting the form.
});
and this is my controller
function add_payment()
{
$this->form_validation->set_rules('fpay', 'Type of payment', 'trim|required|alpha');
$this->form_validation->set_rules('payment', 'Payment', 'trim|numeric');
$this->form_validation->set_error_delimiters('', '');
if ($this->form_validation->run() == FALSE) { // validation hasn't been passed
header('Content-type: application/json');
echo json_encode(validation_errors());
} else {
$fpay = filter_var($this->input->post('fpay'), FILTER_SANITIZE_STRING);
$payment = filter_var($this->input->post('payment'), FILTER_SANITIZE_STRING);
if(isset($_SESSION['payments'][$fpay]))
{
$temp = $_SESSION['payments'][$fpay] + $payment;
$_SESSION['payments'][$fpay] = $temp;
header('Content-type: application/html');
echo $this->_loadpaymentcontent();
}
}
}
function _loadpaymentcontent() {
$this->load->view('payment_content');
}
Hope someone can point me in the right direction I've been stuck on this for 2 days.
Thanks everyone.
I had the same problem and i successfully solved it by putting an exit; after the value which is returned to the ajax call in the controller method.
In your case it will be:
echo $this->_loadpaymentcontent();
exit;
What exit does here is it limits the returned value to the value which should be returned to the ajax call and exits before the html is appended to the returned value.
This is what is obvious per the effect it produces.
Yo need to set up your AJAX.
$.ajax({
type : 'POST',
url : baseurl + 'sales/add_payment',
dataType : 'html', // Will set the return type of the response as AJAX.
... Keep rest of the code same.

How to make javascript work as a response to php events?

I am developing a website for practice, and I would like to know how to use JS to notify the user that the username he picked is already in use, all works fine, if my function(check_username) returns false, the user succesfully registers himself into the site, otherwise the register won't happen.
When the user can't register I would like to know how can I notify the user with a js script.
<?php
//database includes
include_once('../config/init.php');
include_once('../database/users.php');
if(!check_username($_POST['username'])) {
insertUser($_POST['name'], $_POST['username'], $_POST['email'], $_POST['pass']);
}
else header('Location: ../index.php');
?>
One way would be to change your redirect on failure to a javascript message
else
{
echo "<script>alert('Username already exists');</script>";
}
That's a very trivial example to get you started since you mentioned you're learning JS. You can build a lot of improvements on that.
You can set the returns into a javascript variable and use it to display message if the user is not registered.
var x = <?php echo check_username($_POST['username']); ?>;
if(x) {
alert("You are not registered");
}
You can use php ajax for a live notification to users.
<script>
$(document).ready(function() {
$("#InputFieldID").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
//Getting value of input field.
var username = $(this).val();
//Check only if the username characters are above 4
if(username.length >= 4){
$("#IndicatorDivID").html('<p style="color:#ffbf25;">Checking..!</p>');
$.ajax({
type: 'POST',
url: 'check_username.php',
data: {"username": username},
dataType: 'json',
success: function (data) {
if(data.response=='true')
alert("Already Exist");
}
});
}
});
});
//Username Checker
</script>
The result fo check_username.php must be in json format.
eg: {"response":"false"}

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Categories