Post the data failed in php - php

I have some trouble during post my data, show 500 internal server error.
So, I think it must be unsyncronize between client side and server side. I have check but I dont have any clue.This the following php script:
<input type="text" id="use" name="use">
<input type="password" id="pass" name="pass"></td>
<input type="hidden" name="action" value="logaccept">
if ($("#passlog").valid()){
var params = $("#passlog").serialize();
$.ajax({
type:"post",
url:"process3.php",
data:params,
cache:false,
async:false,
success: function(data){
//do something
}
});
}
This the server side:
switch(postVar('action')) {
case 'logaccept' :
passlog(postVar('use'),postVar('pass'));
break;
}
function passlog($use,$pass){
$Use = mysql_real_escape_string($use);
$Pass= mysql_real_escape_string($pass);
//build query
$sql = "SELECT Privilege FROM admin WHERE user='".$Use."' AND password='".$Pass."'";
echo $sql;
$data=mysql_query($sql) or die(_ERROR26.": ".mysql_error());
if($data){
$priv = mysql_fetch_assoc($sql);
}else{
echo 0; // If login fails
}
?> //show Parse error: syntax error, unexpected $end in /var/www/html/process3.php on line 74
Could you tell me what's wrong with my script?

You have a syntax error in file process3.php - thats why you get the internal server error - that is the first thing you have to correct

Related

PHP Script doesnt return variables to AJAX

The code is for simple login validation.
The PHP script doesnt seem to run when returning values to JavaScript but runs fine when there are not variables to return.
So is there anything wrong or do I need to add anything else to return the values from PHP.
<?php
header('Content-type: application/json; charset=utf-8');
include("config.php");
$formd=array();
//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];
$query = mysqli_query($db,"SELECT username FROM login WHERE username = '$username2'");
$result=mysqli_fetch_assoc($query);
$sql=mysqli_query($db,"SELECT password FROM login WHERE username = '$username2'");
$resul=mysqli_fetch_assoc($sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$count = mysqli_num_rows($query);
$pass=$resul['password'];
if((password_verify($password2,$pass))and($count==1)) {
echo "ds";
} else {
echo "no";
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit();
?>
JavaScript
<script>
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ username + '&password1='+ password;
if(username==''||password=='') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
dataType: "json",
data: dataString,
success: function(data){
alert(data.no);
}
});
}
return false;
});
});
</script>
your Php code has 2 echo statements
if((password_verify($password2,$pass))and($count==1))
{
echo "ds"; // first
}
else
{
echo "no"; // first
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd); // second
This way, your php script returns malformed JSON data and hence $.ajax() cannot handle it.
Also, as others pointed out, please use the developer console to verify your script returns the expected data.
The if else part of your php script has an echo statement and then outside the if else you echo the array $formd. This malforms the JSON response. Also, you should use exit(1) as there is no exception being raised in your code.
Here the snippet you should use to get the script working.
if((password_verify($password2,$pass))and($count==1))
{
echo "ds";
}
else
{
// echo "no"; this is not required
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit(1);

My AJAX query isnt validating properly

New to web design here. I have a login form that validates and works perfectly in php but when I try and validate using ajax it doesn't work. When i run the page it says it is a success no matter the input into the form. I have tried for days trying to get it to validate in many different methods. If there is a better way please let me know!
php here and is on same page as login form
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
} else {
echo json_encode('false');
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: "POST",
url: "header.php",
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
});
});
<form id="login_form" form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
<label class="login_form_labels"> Email:</label>
<input type="email" id="email" class="login_input" name="email"><br><br>
<label class="login_form_labels"> Password:</label>
<input type="password" id="password" class="login_input" name="password"><br>
<div id="stay_log">
Stay logged in.
<input type="checkbox" name="stayLoggedIn" value=1 id="checkbox_1">
</div>
<input class="login_form_btn" name="login" value="Submit" type="Submit" id="login_submit">
<button class="login_form_btn" type="button">Forget your Password?</button>
</form>
Please help!
set dataType as Json in your ajax as like given below
$.ajax({
type: "POST",
url: "header.php",
dataType: json,
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
Try this...
I think you need to require pure JSON response from server side and handle it in your ajax success method.
In your PHP code.
$response=array();
if (!empty($_POST)) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
$response['type']="success";
$response['message']="Login done successfully";
} else {
$response['type']="error";
$response['message']="Incorrect Email or Password!!!";
}
}
else
{
$response['type']="error";
$response['message']="invalid post request";
}
ob_clean();
echo json_encode($response);
die();
In above way from server you can response in only json format.
In you ajax call javascript code
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: 'post',
url: $('#login_form').attr("action"),
data: form,
dataType:'json'
success:function (response){
if(response.type=="success")
{
alert(response.message);
// write code for handle your success login;
}
else
{
alert(response.message);
// write code for handle your failure login;
}
},
error: function(response){
alert('Nope');
}
});
});
});
You have to handle JSON response from server side in your ajax success response
In jQuery/AJAX, the HTTP response code termines whether it is a success or not. So if the login failed, you should set a header in PHP indicating this failure.
if (.. login has failed .. ) {
// HTTP 401 = 'Unauthorized'.
http_response_code(401);
}
By doing this, you won't even have to process the resulting JSON, only maybe to get additional info. But the basic result will tell you enough: if the success callback was called, logging in was successful. If error was called, it was not successful for whatever reason.
This sets out your basic flow, and after that you could parse the result message to see any details of what's going on (internal server error, user unknown, password doesn't match, etc).
See List of HTTP response codes, for a list of alternatives and this question for an argumentation about using 401.
First use alert(response) to find out the response you are getting. It should be true or false.
success:function (response){
if(response === "true")
{
alert("hi");
}
else
{
alert("nope");
}
},

Database slice the last two characters of the password (?!)

I have a very frustrating problem. I have a client which send a registration form to the server. The handler is a php file.
The problem is the following: the client send the form data to the php, the php store it in the mysql database. But if I try to give a name which is contains a space - I don't know why - in the database the the password's length is reduced by two.
I searched long hours, but found nothing. I'm on the edge of madness, so I would like to ask you to help me to find the problem.
Here is the registration form:
<!-- REGISTRATION -->
<div data-role="page" id="regScreen">
<div data-role="content">
<div class="profileCircle">
<img src="img/iskola.jpg" />
</div>
<div class="space"></div>
<form action="" method="post" id="regForm" name="regForm">
<input type="text" name="nev" id="regName" placeholder="Teljes név" data-mini="true"/>
<input type="email" name="mail" id="regEmail" placeholder="Email cím" data-mini="true"/>
<input type="password" name="jelszo" id="regPassword" placeholder="Jelszó" data-mini="true"/>
<input type="submit" data-inline="true" data-mini="true" value="Regisztráció" name="rendben" id="rendben" />
</form>
</div>
<a href="#loginScreen"><div class="circle leftBottom c1">
<img src="img/ikonok/vissza.png" />
</div></a>
</div>
This is the script which should handle the registration on the client side:
function registration(){
var name = $('#regForm #regName').val();
var email = $('#regForm #regEmail').val();
var password = $('#regForm #regPassword').val();
if((password == "" || password == null) || (email == "" || email == null)){
navigator.notification.alert("Nem töltött ki minden adatot!", function(){}, "Figyelem!");
}else{
$.ajax({
url: host + "regisztracio.php",
type: 'post',
dataType: 'json',
data: {rendben:'ok', nev: name, mail: email, jelszo: password},
success: function(data){
if(data.ok){
navigator.notification.alert('Sikeresen regisztrált!\nMostmár be tud jelentkezni a saját felhasználónevével!',function(){
$.mobile.changePage("#loginScreen");
},'Üdvözöljük!');
}else{
navigator.notification.alert(data.uzenet,function(){},'Figyelem!');
if(data.help){
navigator.notification.confirm('Kívánja, hogy új jelszót küldjünk erre az email címre?',function(){
console.log(button);
}, 'Segíthetünk?', 'Igen, Nem');
}
}
},
error: function(err){
console.log('jajj');
navigator.notification.alert(err.message,function(){},'Hiba!');
}
});
}
}
And finally here is the php code:
<?php
if (isset($_POST['rendben'])) {
require("mysql.php");
$nev = $_POST['nev'];
$mail = $_POST['mail'];
$jelszo = $_POST['jelszo'];
if (empty($_POST['nev']) OR empty($_POST['mail']) OR empty($_POST['jelszo'])) {
$string = array("ok" => false, "uzenet" => "Nem töltött ki minden adatot!");
echo json_encode($string);
}else{
$sql = "SELECT *
FROM felhasznalok
WHERE mail = '{$mail}'";
$eredmeny = mysql_query($sql);
if (mysql_num_rows($eredmeny) == 0) {
$sql = "INSERT INTO felhasznalok
(nev, mail, jelszo, kep)
VALUES
('{$nev}', '{$mail}', '{$jelszo}', '{$kep}')";
mysql_query($sql);
$string = array("ok" => true);
echo json_encode($string);
}else{
$string = array("ok" => false, "help" => true, "uzenet" => "Ezzel az email címmel már regisztráltak, lehet, hogy elfelejtette a jelszavát?");
echo json_encode($string);
}
}
}?>
If you need I will upload a picture from the database table.
I hope you can help me.
Please forgive not a full answer as such but the formatting is better than a comment:
As others have already suggested:
Echo your sql statement. This is what is being stored in the db after all. This will show you whether your problem lies before or after the data is stored in the db.
var_dump($_POST) if your sql is good as this checks the code in between the receipt of data and its storage in the DB - you can see what your script actually sends.
escape your text to prevent 'sql injection' - Always escape the text because you never know when you are going to change your client page and it is safer that way. Your case is a prime example of why you never trust data from the client.
FWIIW, I suspect that the problem lies in the javascript. One problem with the use of libraries like jquery is that they actually don't make easy stuff easier. They make it more complex. A bit like a slide rule though, once learned, they make some complicated stuff no harder than the easy stuff. There is a code-portability benefit too.
Even so, IMHO, for a simple ajax call, you're actually better off using pure JS, certainly as a beginner. w3schools.com has an excellent AJAX tutorial and code examples.
mysql_* extensions are deprecated. You would be wise to learn mysqli_ (which is nearly identical) or PDO.
My guess is that you are having troubles with jQuery.param encoding of spaces (+, one character, instead of %20, three characters).
You can try manually replacing the ' ' with '%20' in the password field (note: you probably have the same problem in all fields, only you haven't noticed it yet) using the .beforeSend setting:
url: host + "regisztracio.php",
type: 'post',
dataType: 'json',
data: {rendben:'ok', nev: name, mail: email, jelszo: password},
beforeSend: function (req, data) {
data.jelszo = data.jelszo.replace(/\+/g, "%20");
},
success: function(data){
...
Also (but this is unrelated), on the PHP side, notice that you can simplify a bit your code to encode the answer in one place only:
$string = array("ok" => false);
// Ez ad némi biztonságot
$fields = array('nev','mail','jelszo');
foreach($fields as $field)
{
if (empty($_POST[$field]))
$string['uzenet'] = "Nem töltött ki minden adatot: ${field}!";
else
${$field} = mysql_real_escape_string($_POST[$field]);
}
if (!isset($string['uzenet']) {
$sql = "SELECT *
FROM felhasznalok
WHERE mail = '{$mail}'";
$eredmeny = mysql_query($sql);
if (mysql_num_rows($eredmeny) == 0) {
$sql = "INSERT INTO felhasznalok
(nev, mail, jelszo, kep)
VALUES
('{$nev}', '{$mail}', '{$jelszo}', '{$kep}')";
if (false === mysql_query($sql))
$string['uzenet'] = 'Volt egy adatbázis hiba!';
else
$string['ok'] = true;
}else{
$string['help'] = true;
$string['uzenet'] = 'Ezzel az email címmel már regisztráltak, lehet, hogy elfelejtette a jelszavát?';
}
}
die(json_encode($string)); // No more output after this.

Jquery, php ajax post 500 Internal Server Error returns

I have some problem with jquery ajax & php. I'm not good in php, but I have to create a login page with php.
The promblem is, when I try to get some information from the server I get server error insted of the value.
Here is my php code (if someone know better method to create login on server side, please correct me):
<?php
//$link = mysql_connect('localhost', 'root', '') or die('A kapcsolódás nem sikerült: '+mysql_error());
$link = mysql_connect("127.0.0.1", "qm", "soR624gA") or die("Nem sikerült kapcsolódni az adatbázishoz!"+mysql_error());
mysql_query("SET NAMES UTF8");
mysql_select_db("qm", $link);
$uname = mysql_real_escape_string($_POST['name']);
$pass = mysql_real_escape_string($_POST['pass']);
$fetch = mysql_query("SELECT * FROM felhasznalok WHERE nev ='{$uname}' AND jelszo = Sha1('{$pass}')") or die(mysql_error());
if (mysql_num_rows($fetch) == 1) {
$a = array();
$['true'] = 'true';
echo json_encode($a);
}else{
$a = array();
$['true'] = 'true';
echo json_encode($a);
}
?>
And here is the code of the login on the client side:
function handleLogin(){
var _url = preUrl + "login.php";
var name = $("#loginForm #name").val();
var pass = $("#loginForm #pass").val();
$.ajax({
type: 'POST',
url: _url,
data: {name: name, pass: pass},
dataType: 'jsonp',
beforeSend: function(){
if((!name) || (!pass)){
notify('error','Kérlek tölts ki minden adatot!');
return false;
}else{
$("#loginForm #loginBtn").prop("disabled", true);
}
},
success: function(data){
if(data[0].true == 'true'){
window.localStorage["username"] = name;
window.localStorage["password"] = pass;
$.mobile.changePage("#wall",{transition:"slide", reverse:false});
}else{
$('#loginForm #name').val("");
$('#loginForm #pass').val("");
notify('error','Hibás adatok!');
}
},
error: function(err){
//átírni ha a cordovajs be lesz szúrva!!!
alert('Hiba: '+err.message);
}
});
$("#loginForm #loginBtn").prop("disabled", false);
return false;
}
I tried it out on different servers but nothing changed. I only get the error.
You made a typo:
$['true'] = 'true';
Should probably be
$a['true'] = true;
(note the $ a )
Also note that whether your login would succeed or not, it will always fill that 'true value' with true. Looking at your Javascript, that's not what you want. Consider setting it on false in your else statement.
learn basic php: $['true'] = 'true'; is a flat-out syntax error. this is the most likely cause of your server 500 error.
Add string like that to see errors in your php script:
error_reporting(E_ALL);
ini_set('error_log', 'path_to_log_file');
ini_set('log_errors_max_len', 0);
ini_set('log_errors', true);

"Uncaught SyntaxError: Unexpected token <" in jquery.js. Email signup form with AJAX

I'm trying to build a simple email signup, and I came across this tutorial which seemed to be exactly what I wanted to do (http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/). I don't have much programming knowledge, so this was my best bet at getting something up and running. I followed the tutorial, but unfortunately, I'm having some problems with it.
My problem is when I try to submit an email address, I get Uncaught SyntaxError: Unexpected token < in jquery.js, on line 565.
When I expand the error in Dev Tools, it shows:
jQuery.extend.parseJSON jquery.js:565
$.ajax.success common.js:36
jQuery.Callbacks.fire jquery.js:1046
jQuery.Callbacks.self.fireWith jquery.js:1164
done jquery.js:7399
jQuery.ajaxTransport.send.callback jquery.js:8180
As I said, I'm a rookie with this, so I greatly appreciate any help. I've been researching for a while, but haven't found any issue the same as mine. Some were similar, but I couldn't fix the issue with any of the solutions I came across.
This is the form code:
<form id="newsletter-signup" action="?action=signup" method="post">
<fieldset>
<label for="signup-email">Sign up for email offers, news & events:</label>
<input type="text" name="signup-email" id="signup-email" />
<input type="submit" id="signup-button" value="Sign Me Up!" />
<p id="signup-response"></p>
</fieldset>
</form>
This is the signup JS:
/* SIGNUP */
$('#newsletter-signup').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
And this is the PHP:
<?php
//email signup ajax call
if($_GET['action'] == 'signup'){
mysql_connect('host','user','password');
mysql_select_db('table');
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if(mysql_num_rows($existingSignup) < 1){
$date = date('Y-m-d');
$time = date('H:i:s');
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
Thanks!
UPDATE: Shad - I inserted that code right after 'success:function(data){' Is that correct? After doing that, when trying to submit an email address, I get this in the console, pointing to the line with the newly added code:
Failed:
SyntaxError
arguments: Array[1]
get message: function getter() { [native code] }
get stack: function getter() { [native code] }
set message: function setter() { [native code] }
set stack: function setter() { [native code] }
type: "unexpected_token"
__proto__: Error
<br />
<b>Warning</b>: mysql_num_rows(): supplied argument is not a valid MySQL result resource in <b>/homepages/37/d403623864/htdocs/_php/launch_notify.php</b> on line <b>22</b><br />
{"status":"error","message":"Ooops, Theres been a technical error!"}
Screenshot of Dev Tools with that error. Let me know if you need to see any of the lines expanded or anything: http://i.stack.imgur.com/IwnBr.png
UPDATE #2: Using the code provided by satoshi, I think I made a little progress on figuring out the issue, but I still haven't solved it. I think I narrowed it down to a MySQL connection issue. I tried this code:
<?php
mysql_connect("[DB]","[USER]","[PASS]")
or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("signups")
or die(mysql_error());
echo "Connected to Database";
?>
And the response I get is:
Connected to MySQL
Access denied for user '[USER]'#'%' to database 'signups'
I've tried a bunch of things, but can't figure it out. My host is 1&1, and I created the table through there using PHPMyAdmin. I've tried different tables, all get the same issue. Here's a screenshot showing the table in PHPMyAdmin: http://i.stack.imgur.com/Oe0Fm.png
Thanks again for all the help so far everyone. I appreciate it.
Your PHP file is warning you because $existingSignup is not a valid resource. This is because your SQL query is invalid. For this reason, because PHP is outputting something unexpected, the page doesn't return a valid JSON response.
Please verify that your mysql_query(...) call returns a valid resource before calling mysql_num_rows(...), like this:
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if($existingSignup !== FALSE)
{
if(mysql_num_rows($existingSignup) < 1){
// ...
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
else {
$status = "error";
$message = mysql_error();
}
Edit: please note that the query is syntactically correct, I guess you face the problem because you didn't set up the DB table correctly.

Categories