HTTP POST does not work after switching DNS - php

Recently I swapped out a GoDaddy hosting and directing the requested DNS server to another mine.
The direction is pointing into a folder.
What happens is that I'm trying to make a validation by ajax login before submitting the form to actually login.
The AJAX calls and executes a php but data is not passed by POST as if they were lost in the request.
However, PHP is running in the AJAX request and even returns a message as I wanted, but the data is sent through ajax as if they got anything.
I tried to send the form by post Direct and caused the same error. I'm believing in the possibility that the POST is getting lost in directing the DNS. Is it possible?
Anyway, I'm leaving the HTML, AJAX and PHP:
Note: I'm using CodeIgniter.
HTML:
<?php echo form_open('usuarios/login', array('method' => 'post', 'id' => 'form-login')) ?>
<div class="boxform">
<label for="loginnome">Usuário ou E-mail:</label>
<input type="text" name="loginnome" required id="loginnome" placeholder="Usuário ou E-mail" title="Usuário ou E-mail">
</div>
<div class="boxform">
<label for="loginsenha">Senha:</label>
<input type="password" name="loginsenha" required id="loginsenha" placeholder="Senha" title="Senha">
</div>
<div class="boxform">
<input type="submit" class="button submit-claro" value="Logar" title="Logar">
</div>
<?php echo form_close(); ?>
AJAX:
$('#form-login').validate({
rules: {
loginnome: {
required:true,
maxlength:100
},
loginsenha:{
required:true,
maxlength:30
}
},
submitHandler: function( form ){
$.ajax({
type : "POST",
url : get_url()+"usuarios/validar_login",
dataType : 'json',
data : {
'usuario' : $('#loginnome').val(),
'senha' : $('#loginsenha').val()
},
success : function(data){
console.log(data);
if (data.usuario === false) {
$('.msg_error p').show();
$('.msg_error p').html('');
$('.msg_error p').html('Usuario inválido');
$('#loginnome').val('').focus();
}
else {
if (data.senha === false) {
$('.msg_error p').show();
$('.msg_error p').html('');
$('.msg_error p').html('Senha incorreta');
$('#loginnome p').val('').focus();
}
else {
inicia_sessao(data.url);
}
}
}
});
//return false;
}
});
PHP:
public function validar_login()
{
$usuario = $this->input->post('usuario');
$senha = $this->input->post('senha');
$return = $this->usuario->valida_login($usuario,$senha);
$return['url'] = site_url();
echo json_encode($return); die;
}

You may have to contact your provider to resolve this as it is directly / indirectly under their control.

Related

redirect page after jquery submit using header() function on another page using php

i have this login form
<form autocomplete="off" id="login_form">
<div class="login-wrapper">
<input required type="text" class="login-input" name="email" id="email" placeholder="email">
<span class="fas fa-envelope mail_name-email"></span>
<span class="err_output err_email"></span>
</div>
<div class="login-wrapper">
<input required type="password" class="login-input" name="pwd" id="pwd" placeholder="password">
<span class="fas fa-lock pwd_password"></span>
<span class="err_output err_pwd"></span>
</div>
<input type="submit" class="login_btn" id="login_btn" name="login" value="log in">
</form>
the submission is handled using jquery, like so
$(document).ready(function() {
$(document).on("submit", "#login_form", function() {
Login();
//send values to post
const mail = document.getElementById("email").value;
const pwd = document.getElementById("pwd").value;
$.ajax({
type: "POST",
url: "./inc/login.php",
data: {
email: mail,
password: pwd
}
});
return false;
});
});
so it works well but i wanted to do all the validation on the serverside particluarly in the login.php file included in the url within the jquery code because the data entered is sensitive and i cannot just redirect usin javascript. So even before i started the validation i tried a redirect to another page after the form was submitted but it wouldn't work, i tried header("Location: ../main.php") and echo "<script>location='../dashboard.php'</script>"; but on the console all i saw was this
jquery.js:9837 XHR finished loading: POST "http://localhost/My%20portfolio/admin/inc/login".
i have even included an action attribute on my form pointing to the action page but it doesn't work, this is the only way i can proceed with validation otherwise i am stuck, i dont know what's wrong
You can't use a redirect in PHP on an ajax call. You need to return something to the JS page and redirect from there. For example, your PHP can return a json object with the status and the URL to forward to.
You can output something like this:
{
"status" : "success",
"url" : "http://www.example.com/url-to-redirect"
}
Or if it fails
{
"status" : "error",
"message" : "Error message to show"
}
Then in your javascript, check for the answer and validate the status
$.ajax({
type: "POST",
url: "./inc/login.php",
data: {
email: mail,
password: pwd
},
dataType: "json"
}).done(function( data ) {
if (data.status === "success") {
window.location.href = data.url;
}
else if (data.status === "error") {
alert(data.message);
}
});
In your PHP script you need to output something like an array.
So in your PHP validation, if everything is validated, you can simply do
echo json_encode(array('status' => 'success', 'url' => 'http://www.example.com/url-to-redirect'));
But if it fails:
echo json_encode(array('status' => 'error', 'message' => 'Error message to show'));
I suggest you read more on json_encode and ajax calls with PHP.

303 error using the remote method of jquery validation

I am using CodeIgniter, I have one field which is called as change_password_id. The user can enter the id and it will check the id exist or not in the database using the remote method of Jquery validation.
I am getting the 303 error in the network tab.
The controller is not calling from AJAX.
$(function() {
$("#reset_password_request").validate({
rules: {
change_password_id: {
required: true,
remote: {
url: "<?php echo base_url()?>Employee_control/checkemp_exist",
type: "post",
data: {
change_password_id: function() {
return $("#change_password_id").val();
}
}
}
},
},
messages: {
change_password_id: {
remote: "This emp Id is not registered with us."
}
},
submitHandler: function(form) {
// console.log(form.submit)
form.submit();
}
});
});
Controller
public function checkemp_exist(){
echo $correct_emp_id= $this->input->post('change_password_id');
/*I will add code here after some time*/
}
form
<?php echo form_open('','id="reset_password_request"'); ?>
<div class="form_group">
<input type="text" class="form_control" id="change_password_id" name="change_password_id">
<?php echo form_error('change_password_id'); ?>
</div>
<div class="btn_container">
<button class="btn_default orange_bg" type="submit"> Send request </button>
</div>
<?php echo form_close(); ?>

AJAX not receiving POST variables

I've read at least 20 of these similar questions and can't figure out what's wrong with my code.
I've got a login form as shown below:
<div class="login-form">
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="submit" value="Log in"/>
</div>
</form>
</div>
My login.js script is as below:
$(document).ready(function(){
$("#login-button").click(function(e){
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php", //.js file is in a diff directory
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
This is supposed to get sent back to 'index.php', which has included a separate php file that handles the login information. The reason for this is so I can update the page with the user's successful login without refreshing.
My other php file is simply checking for the post data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
if (isset($_POST['login']) && $_POST['login']) {
} else if (isset($_POST['reg']) && $_POST['reg']) { //this is for registration, which will be used once this login is working
} else {
echo 'Neither login/reg were set';
}
The var dump shows:
array(0) { }
So the data is not being received. However, it clearly reaches the php page. I don't know what's wrong, any suggestions?
Edit: I figured I would add, that adding an alert at the top of login.js with the username/password does print the entered values. So the login.js is being reached, and the data is accessible there. But it doesn't go beyond that.
Edit2: Here is my updated HTML and login.js code:
index.php:
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="button" value="Log in"/>
</div>
</form>
login.js
$(document).ready(function(){
alert(1);
$("#login-button").click(function(e){
alert(0);
//e.preventDefault();
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php",
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
The solution was to change my
$("#login-button").click(function(e){
to
$(document).on("submit",".login-form-container",function(e) {
which will handle the form submit, and this includes pressing the button as well as hitting enter (ideal situation).
Now the data is being sent successfully and I can handle the actual login/registration SQL, so thank you to #Ashokkumar M. Prajapati for helping to come to the conclusion that the .js script was not actually firing upon submit (not that the rest of you didn't help!)
please replace type: "POST" with method: "POST"
you mentioned it wrong in jquery ajax function.
Default is "GET" in case you don't specify it. So, if you had checked both $_POST & $_GET then you would have found your data in $_GET.
try var_dump($_REQUEST) if it don't show up anything then your client is not sending data to server.
also, check net panel of you browser developer console. so, you will know what data are passed to server.

CodeIgniter and AJAX form

I'm using CodeIgniter for my web app and I'm currently stuck with AJAX forms.
I've made an view for my "forget password" modal and it looks like this:
<form action="<?=base_url()?>users/forgot_pass" method="post" id="forget_pass_form">
<div class="form_header">
<h1>Forgot your password?</h1>
</div>
<?php if($ajax_error == 0) { ?>
<div class="front_success">
<p>Password was succesfully sent to your email address.</p>
</div>
<?php } ?>
<?php if($ajax_error == 1) { ?>
<div class="login_error">
<p>Email address was not found in the database.</p>
</div>
<?php } ?>
<div id="loading_spinner"></div>
<p><input type="text" name="to_email" placeholder="Sähköpostiosoite" class="user" style="background-postion: -200px; margin-top: 20px;" />
<input type="submit" name="to_submit" value="Lähetä salasana" class="login_submit" id="forget-pass" /></p>
</form>
And here's my controller for it:
<?php
class Users extends CI_Controller {
public function forgot_pass()
{
if(isset($_POST['to_submit'])) {
$this->load->model('user');
$email = $_POST['to_email'];
$email_addr = $this->user->get_email_address($email);
if($email_addr) {
foreach($email_addr as $row) {
$this->load->library('email');
$this->email->from('me');
$this->email->to($email);
$this->email->subject('Testing');
$this->email->message('Your password is: ' . $row['password']);
if(!$this->email->send()) {
$data['ajax_error'] = 1;
} else {
$data['ajax_error'] = 0; }
}
}
}
$this->load->view('header');
$this->load->view('index', $data);
$this->load->view('footer');
}
}
?>
I won't post my Model since I know 100% sure it works and it only contains that one method to check if email is found in the database.
Now I want to make it more dynamic by using AJAX. I want it to echo the success message inside a div if the email address was found in the database and the mail was sent
to that email address, otherwise I want it to echo out the error "User was not found in the database".
Here's my js file which for now:
$(document).ready(function() {
$("form#forget_pass_form").on('submit', function(){
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
}
});
return false;
});
});
The AJAX part itself is working, but I just don't know how to implement those messages. Any help would be much appreciated.
make your html code like this
<div class="front_success" style="display:none">
<p>Password was succesfully sent to your email address.</p>
</div>
<div class="login_error" style="display:none">
<p>Email address was not found in the database.</p>
</div>
small change in controller:-
if($this->email->send()) {
echo '1';
} else {
echo '0';
}
so what ever your controller return based on that success function will make the dive show
try to make you ajax code like this :-
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data:$(from).serialize(),
beforeSend: function(){
$("#loading_spinner").show();
},
success: function (data) {
//alert(data); alert it if you want to check the function output
if(data == '1'){
//if the email is send then it return 1 so that you show success msg
$("#login_success").show();
}else{
//if the email is not send then it return 0 so that you show error msg
$("#front_error").show();
}
$("#loading_spinner").hide();// hide when ajax complete
}
});

Form when submitted to display a result (Firstname) on the thank you page

Stuck on a thing with PHP, i know it is something simple but am not sure of the correct way of doing it, either by jquery or php.
I have a contact form which when it submits its form, i want the results of some of the fields to display on the results thank you paeg saying:
Thank you for entering YOURNAME. Blah blah blah
Is this acheivable with a simple line of php or does it need to called through jquery.
Thanks, only new to php so somethings are still bit confusing
<?php
define('is_freetrial-celebrity', 1);
include_once('includes/header.inc.php');
?>
<div role="main" id="main">
<article id="mainFreetrial" class="greyBlock twoColumnsLayout">
<header>
<h1>Get Started</h1>
</header>
<div>
<form method="get" action="/forms_validation/freetrial.php" class="trialForm ajaxForm">
<div class="column">
<p>
<label for="firstNameTrial">First name<sup class="red">*</sup></label><input type="text" id="firstNameTrial" name="firstNameTrial" value="" required/>
</p>
<p>
<label for="lastNameTrial">Last name<sup class="red">*</sup></label><input type="text" id="lastNameTrial" name="lastNameTrial" value="" required/>
</p>
<p>
<label for="ageTrial">Age</label><input type="text" id="ageTrial" name="ageTrial" value=""/>
</p>
<p>
<label for="celebrityTrial" style="display: block; width: auto; margin-bottom: 5px;">Name the celebrity you would most like to meet, and why?<sup class="red">*</sup></label>
<textarea id="celebrityTrial" name="celebrityWhyTrial" style="width: 430px; height: 3em;" required></textarea>
</p>
<p class="ajaxFormBeforeValid">
<input type="submit" value="Submit now" class="redButton"/><span class="ajaxFormWait"></span><span class="ajaxFormError error"></span>
</p>
<div class="ajaxFormValid">
<p>
Thank you! Your local consultant will contact you soon. 'Like' us while you wait for all the latest VIP offers and promotions!
</p>
</div>
<p>
<small>
<sup class="red">*</sup>These are mandatory fields.
</small>
</p>
</div>
</form>
</div>
</article>
</div>
<?php include_once('includes/footer.inc.php'); ?>
Heres the jquery part
/*************************
plugin to manage ajax forms
*************************/
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm'),
ajaxForm = $('<div />', {
text : $this.attr('title')
});
// If the plugin hasn't been initialized yet
if ( ! data ) {
$(this).data('ajaxForm', {
target : $this,
ajaxForm : ajaxForm
});
//get the spinner, the valid box and the error box
var mySpinner = $this.find('.ajaxFormWait');
var myValid = $this.find('.ajaxFormValid');
var myError = $this.find('.ajaxFormError');
var myBeforeValid = $this.find('.ajaxFormBeforeValid');
myError.hide();
mySpinner.hide();
//add an event to send the form via AJAX
$this.submit(function(){
// get all the inputs into an array.
var $inputs = $this.find(':input:not([type="submit"], [type="button"])');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
if (this.type == "radio" || this.type == "checkbox"){
if($(this).is(':checked')){
if(typeof(values[this.name]) === 'undefined'){
values[this.name] = $(this).val();
}else{
values[this.name] += ', '+($(this).val());
}
}
} else
values[this.name] = $(this).val();
});
function defineTheInvalidsFields(fieldsList){
for(var i in fieldsList){
if(fieldsList[i] == 'closestStudio'){
$this.find('[name="'+fieldsList[i]+'"]').parent().addClass('invalid');
}else{
$this.find('[name="'+fieldsList[i]+'"]').addClass('invalid');
}
}
}
//send an AJAX request
$.ajax({
url: $this.attr('action'),
dataType: 'json',
data: values,
beforeSend: function(){
mySpinner.show();
},
success: function(result){
mySpinner.hide();
$this.find('.invalid').removeClass('invalid');
//error management
if(typeof(result.valid) === 'undefined'){
if(result.multipleSend){ //if multiple send
myError.html('Your request is already sent.');
}else if(result.required){ //if fields are required
defineTheInvalidsFields(result.required);
myError.html('The fields in red are required.');
}else if(result.format){ //if the forma is incorrect
defineTheInvalidsFields(result.format);
myError.html('The fields in red have invalid content.');
}else if(result.loginInvalid){
myError.html(result.loginInvalid);
}else{
myError.html('An unknown error occured.');
}
myValid.slideUp(300);
myError.slideDown(300);
}else if(typeof(result.loginUrl) !== 'undefined'){
window.location.href = result.loginUrl;
}else{
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
}
}
});
return false;
});
//special case for the heardAbout
$('#heardAbout').change(function(){
if($(this).find('option:selected').attr('value') == 'Other'){
$('#otherHeardAbout').slideDown(300);
}else{
$('#otherHeardAbout').slideUp(300);
}
});
}
});
},
destroy : function(){
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm');
// Namespacing FTW
$(window).unbind('.ajaxForm');
data.ajaxForm.remove();
$this.removeData('ajaxForm');
})
}
};
$.fn.ajaxForm = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.ajaxForm' );
}
};
})( jQuery );
The form gets sent to the other page, is there a way to target a specific div and add the custom message with the name.
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
if You wand to fetch specific element div via ajax call You can do like this:
$.ajax({
url: 'page.html',
success: function(data) {
item=$(data).filter('#specific_element');
$(selector).html(item);
}
});
If You wand to redirect to other page using
window.location = '/free-trial-thank-you/';
and then show data on a different page You should pass needet parameters like
window.location = '/free-trial-thank-you/page.php?name1=Daniel&name2=Pablo;
and on different site show parameters using _GET or _POST for example:
echo $_GET['name1'] or echo $_POST['name1'] if You use PSOT method in Your Ajax request
One way that I can think of is using session to store the information.
At freetrial.php store the form information in session like this:
session_start();
$_SESSION['firtNameTrial'] = $_GET['firstNameTrial'];
On ajax success, redirect the page to the thank you page using javascript windows.location.replace:
// similar behavior as an HTTP redirect
window.location.replace("http://yourwebpageaddress.com/thankyou.php");
Get the session on the thank you page. If you don't know, you may look at this example: Click here for session example

Categories