I am tring to send data from ajax but getting post error. I also took help form ReCaptcha 2.0 With AJAX but still I am getting the same POST error in php fle.
$("#submit").click(function(){
var name = $("#name").val();
var mobile = $("#mobile").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message= $("#message").val();
if(name=='' || mobile=='' || email=='' || subject=='' || message==''{
$("#errmsg").html("All fields are required");
} else {
//$("#reqmsg").html(username);
$.ajax({
type: "POST",
url: "insertquery.php",
data: "name="+name+"&mobile="+mobile+"&email="+email+"&subject="+subject+"&message="+message+"&g-recaptcha-response="+grecaptcha.getResponse(),
success: function(data){
if(data=="ok"){
alert("query submitted");
window.location="http://www.intuitioninteriors.in";
} else {
$("#errmsg").html("some went wrong.please try again");
}
}
});
return false;
}
});
Above is the ajax file.
include("database.php");
$name=$_POST["name"];
$mobile=$_POST["mobile"];
$email=$_POST["email"];
$subject=$_POST["subject"];
$message=$_POST["message"];
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
$url="http://www.google.com/recaptcha/api/siteverify";
$privatekey="xxxxxxxxxxxxxxxxxxxxxxxxx";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$privatekey."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
if ($response["success"] != false) {
$query="insert into query values(NULL,'$name','$mobile','$email','$subject','$message')";
$result=mysqli_query($conn,$query)or die(mysqli_error($conn));
if($result){
echo 'ok';
} else {
echo 'not ok';
}
} esle{
echo 'not verified';
}
This is php file.
Error: POST http://intuitioninteriors.in/insertquery.php 500 (Internal Server Error)
How can I fix it?
Related
I don't really understand why this does not work - I have read a whole lot about this specific problem, but I must be missing something.
I want to alert the "echo" from the PHP - which it doesn't.
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "json",
success: function(data){
alert(data);
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "This is your current email";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "Your email is changed";
}
} else {
echo "Please provide a correct email";
}
The database is updating, do the script itself runs perfectly, but after the "success" - it doesn't alert anything.
UPDATE
I have now tried this:
AJAX:
$("#SaveChangesEmail").click(function() {
var newemail = $("#mynewemail").val();
$.ajax({
type: "POST",
url: "checkemail.php",
data: {newemail:newemail},
datatype: "text",
success: function(data){
if(data == 1) {
alert("This is your current email");
}
else if(data == 2) {
alert("Your email is changed");
}
else if(data == 3) {
alert("Please provide a correct email");
}
}
});
});
PHP (checkemail.php)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
if($email == $row['myemail']){
echo "1";
}
else if($email != $row['myemail']){
$results = $con->query("
UPDATE members SET
myemail='".$email."'
WHERE m_id = '".$m_id."'") or die(mysqli_error($con));
echo "2";
}
} else {
echo "3";
}
The console is returning the raw data (1,2,3) but the alert is still not showing!
Here my php code. I need to redirect to another page when if($users[$name] === $password) or when $users[$name] = $password; but it does not work.What is wrong?Here ajax too.
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
alert(a);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
if(!isset($_POST['user'])||!isset($_POST['pass'])){
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] === $password){
header("Location:chat.html");
exit;
}
else {
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
header("Location:chat.html");
exit;
}
Because you're fetching the page with ajax the redirection will happen to the ajax request which means you will get back a 301 response.
This should work:
$(document).ready(function() {
$('#submit').click(function() {
var name = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'php/login_script.php',
data: {
user: name,
pass: password
},
success: function(a) {
document.location = 'chat.html';
},
error: function() {
alert('Invalid password');
}
});
});
});
and
<?php
if(!isset($_POST['user'], $_POST['pass']) || empty($_POST['user']) || empty($_POST['pass'])){
// Send bad request so redirect doesn't happen
http_response_code(400);
die();
}
$file = "users.json";
$users = json_decode(file_get_contents($file), true);
$name = $_POST['user'];
$password = $_POST['pass'];
if(isset($users[$name])) {
if($users[$name] != $password){
http_response_code(400);
echo "Wrong password";
}
}
else {
$users[$name] = $password;
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}
This will return 200 on success and 400 on failure which will trigger the success and error parts of the $.ajax request.
The thing you need to realize about PHP is all of the PHP stuff is done before sending the page to the user, so calling a redirect on php/login_script.php does nothing.
What you need to do is return something to indicate success of the login.
Here's what you should do to understand my explanation:
Replace header("Location:chat.html"); with echo "success"; in your PHP code.
Change your jQuery to the following:
success: function(a)
{
if (a === "success")
{
window.location.replace("chat.html");
}
}
In my case I am sending POST request by $.post using JQuery and PHP.
But I am gettinh this error in while posting data.
POST https://xxxxxxxxxxxxx/xxxxxxxxxxx/php/control/LoginControl.php 500 (Internal Server Error)
here is my jquery code :
var url = 'php/control/LoginControl.php';
$.post(url,
{
task : "login_verify",
username:_username ,
password:_user_password,
})
.error(function(er){
console.log(er);
})
.success(
function(data){
if(data == true){
window.location = 'index.php';
}else{
$("#user_password" ).css({border:'1px solid red'});
}
}
);
PHP - LoginControl.php
<?php
try{
if(isset($_POST) && $_POST['task'] == 'login_verify'){
$user_name = $_POST['username'];
$password = md5($_POST['password']);
require '../class/login.php';
if(class_exists('Login')){
$user = Login::verifyCredentials($user_name,$password);
if($user != NULL){
if(isset($_SESSION)){
session_destroy();
}
session_start();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
echo true;
}else{
echo false;
}
}
}
} catch (Exception $ex){
echo $ex;
}
?>
note: I deploy successfully this code on live test server. and it is completely working fine. But on new server I am getting this error. I am using SSL on this new server this might be issue.
Please comment if its not enough information.
Please help.
Here's an edit to your scripts. Maybe something along the lines of this will help.
JS:
$(function()
{
var url = 'php/control/LoginControl.php';
$.post(url, {
task: "login_verify",
username: _username,
password: _password
}, function(data, status, xhr)
{
// success
if(data.error===false)
window.location = 'index.php';
else
$("#user_password").css({border: '1px solid #ff0000'});
}).error(function(xhr, status, error)
{
console.log("Error loading page. Status: "+status+" | Error: "+error);
});
});
PHP:
<?php
// Session must be started before session checking and destroying can happen
session_start();
// Set error true by default
// Error is always returned.
// If no error, it'll be set to false in if statement
// So a value will always be returned.
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
require_once __DIR__.'/../class.login.php';
if(class_exists('Login'))
{
$uname = $_POST['username'];
$passwd = $_POST['password'];
$user = Login::verifyCredentials($uname, $passwd);
if(!empty($user))
{
if(isset($_SESSION))
session_destroy();
$_SESSION['uid'] = $user[0]->ADMIN_ID;
}
else
$return['error'] = false;
}
}
echo #json_encode($return);
One thing I did notice in your PHP script that I corrected in my edits, is you're using $_SESSION and session_destroy() when no session is open. You must first define session_start() before any of the session methods or magic variables become available to you. That's why I placed it at the very top of the PHP script.
Also, if you want to use another data type rather than json, it's easiest just to use the $.ajax() function
var loginData = {
username: _username,
password: _password,
task: 'login_verify'
};
$.ajax({
url: url,
type: 'post',
data: loginData,
dataType: 'html',
success: function(data, status, xhr)
{
// If page loading was a success. i.e. 200 OK status message
},
error: function(xhr, status, error)
{
// error. Status other than 200
}
});
======================================================================
EDIT: New Code
Take a look at this, see if this will help.
PHP:
<?php
$return['error'] = true;
if(isset($_POST) && $_POST['task'] == 'login_verify')
{
if(!empty($_POST['formData']['username']))
{
if(!empty($_POST['formData']['password']))
{
$return['error'] = false;
$message = "The AJAX call was successfull! The data passed is listed below.\n\n"
. "task: " . $_POST['task'] . "\n"
. "username: " . $_POST['formData']['username'] . "\n"
. "password: " . $_POST['formData']['password'];
$return['message'] = $message;
}
else
$return['message'] = 'Password is empty!';
}
else
$return['message'] = 'Username is empty!';
}
else
{
$return['message'] = 'Invalid request! ' . $json->task;
}
echo #json_encode($return);
JavaScript:
$(function()
{
$("#login").click(function()
{
var jdata = {
task: 'login_verify',
formData: {
username: $("#username").val(),
password: $("#password").val()
}
}
$.ajax({
url: 'login.php',
type: 'post',
dataType: 'json',
data: jdata,
cache: false,
success: function(data, status, xhr)
{
var dataStatus = (data.error===true) ? "Error" : "Success";
var message = "Status: " + dataStatus + "\n"
+ data.message;
alert(message);
},
error: function(xhr, status, error)
{
alert('Error: ' + error);
}
});
return false;
});
});
This code, works. I have a live version of it. Exact code and all.
AJAX/PHP Example
I hope this helps
hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});
I'm running some ajax on my website to handle form submission, However, For some reason whenever I check the response from PHP, it ignores my handling and goes straight to the bottom.
//Login Form Submission
$('form.loginform').on('submit', function (e) {
e.preventDefault();0
//Grab Data
var that = $(this),
url = that.attr('action'),
method = 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: method,
data: data,
success: function (response) {
console.log("Ajax Response: \"" + response + "\"");
console.log(typeof response);
if(response === "0"){
document.getElementById('error_message').innerHTML = "Incorrect password";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
}else if(response === "1"){
window.location.href = "./index.php";
}else if(response === "2"){
document.getElementById('error_message').innerHTML = "Please fill all required fields.";
document.getElementById('error_message').style.color = 'red';
} else if(response === "3"){
document.getElementById('error_message').innerHTML = "That username does not exist. Please try again.";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
} else if(response === "4"){
document.getElementById('error_message').innerHTML = "Your account has been banned on this website. Please contact an administrator.";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
} else {
document.getElementById('error_message').innerHTML = "Error while logging in. Please try again.<br />If you continue to recieve this error, Please contact an administrator.";
document.getElementById('error_message').style.color = 'red';
document.getElementById('error_message').style.borderColor = 'red';
}
//This is the output from the php script
}
});
return false;
});
That is my current code, The output I get is
Ajax Response: "1"
String
However, It then goes straight to
'Error while logging in, Please contact an Administrator'
My question is Why is it ignoring the 'if' statements above the 'else', even though the response is '1'?
Try
response.trim() == "1"
since log shows its 1 and String so may be some white space is the issue.