I'm trying to learn OOP in PHP but I'm having some troubles at the moment. Whenever method is executed i don't know what value should i return to be able to handle it with jQuery in both cases - true and false. For example, in Pick_data() if false i want to get value like: "Fill in all fields" and most important, to be able to display it for user using jQuery or Ajax. I will leave code down below. Places commented ,,//I NEED HELP HERE" is my problem. I'm not asking you to write whole code and just need reference to information how can i deal with it. I would appreciate that because i'm completely lost. I will leave code down below(it's working fine expect my problem). Thanks!
<?php
require ('db_connect.php');
Class Registration {
public $username, $password;
public function Pick_data() {
if (isset ($_POST['username']) && isset ($_POST['password'])) {
$this->username = trim($_POST['username']);
$this->password = trim($_POST['password']);
} //end of if isset
if (!empty($this->username) && !empty($this->password) ) {
return true;//NEED HELP HERE
} //end of is empty
else //NEED HELP HERE
} //end of Pick_data
public function Username_equivalent_check() {
$find_username_equivalent = mysql_query("SELECT * FROM websiteusers WHERE Username='".$this->username."'");
if (mysql_num_rows($find_username_equivalent) == 0) {
return true;//NEED HELP HERE
} //end of (mysql_num_rows)
else //NEED HELP HERE
} //end of Username_equivalent_check
public function Input_data() {
$input_user = mysql_query("INSERT INTO websiteusers (Username, Password)
VALUES ('$this->username','$this->password')");
if ($input_user) {
return true; //NEED HELP HERE
}//end of inputing new user data
else //NEED HELP HERE
} //end of input_data
} //end of class
$var = new Registration;
$var->Pick_data();
$var->Username_equivalent_check();
$var->Input_data(); ?>
There are several ways to do this. Here are a few suggestions:
When an error occurs, you do not just want to return a true/false result, but you want to return a text message. That text message can then be displayed (or can be passed to jQuery or whatever). Since you are a beginner, I would say just change your functions to return a string value (the actual error message text) instead of returning just false in case of an error. Something like this:
public function Pick_data() {
if (isset($_POST['username'])) $this->username = trim($_POST['username']);
if (empty($this->username)) return 'User name must be specified.';
if (isset($_POST['password'])) $this->password = trim($_POST['password']);
if (empty($this->password)) return 'Password must be specified.';
return true;
}
As you can see above, your Pick_data function will return with an error message (a string value) if either one of the required fields were empty. It will only return true if there were no errors.
Then when you call this function, you must check its return value:
$var = new Registration;
$result = $var->Pick_data();
if ($result !== true) {
echo 'Error: ' . $result; // This gets executed when Pick_data returned an error message
} else {
// This gets executed when Pick_data returned true, so only here you should continue:
$result = $var->Username_equivalent_check();
// you must check here the $result variable again as it now contains the return value of your Username_equivalent_check function
// ...and so on
}
If you must do a lot of checks one after the other, you'll end up with a lot of nested if / else statements. Which is not so great. But as a beginner programmer you need to learn that you should almost always need to check the return value of each(!) function you call!
A more advanced solution is to use a try / catch block, something like this:
try {
$var = new Registration;
$var->Pick_data();
$var->Username_equivalent_check();
$var->Input_data();
} catch(Exception $e) {
// Get the error message:
$error_msg = $e->getMessage();
// and print it out
echo 'Error: ' . $error_msg;
}
To make the above try / catch block work, you must(!) also change your functions to throw an exception (error) when something goes wrong, something like this:
public function Pick_data() {
if (isset($_POST['username'])) $this->username = trim($_POST['username']);
if (empty($this->username)) throw new Exception('User name must be specified.');
if (isset($_POST['password'])) $this->password = trim($_POST['password']);
if (empty($this->password)) throw new Exception('Password must be specified.');
}
Using try / catch blocks are much more elegant because you do not end up with a lot of nested if / else statements. Note: when an exception is thrown while the program is running within a try / catch block the program execution stops there immediately and the catch block gets executed.
I think now you have a better idea on how to handle error events in PHP.
If you want to display the error message in the user's web browser with jQuery then you must pass the error message from the server which runs your PHP code to the browser which can only run javascript (jQuery is written in javascript). Nowadays forms are being submitted from the browser to the server via an Ajax call. It looks something like this: First the form gets being displayed in the browser (PHP sends the page containing the form to the browser when the user visits your page). The user fills the form and when hitting the Submit button javascript takes over and sends the form data to the server. This way the user is still on the same page, in other words the page does not get reloaded. When your server receives the Ajax request from the javascript code running in the browser, it does the actual processing, in your example checks the values of the form fields, etc. Finally the server sends the results back usually as a JSON object to the browser, to the calling javascript program. Then the results can be displayed by the javascript code running in the user's browser. So for what you want to do you need to learn both PHP and javascript programming and you need to learn using jQuery and the JSON format as well.
Related
I am working on a project where I use a lot of http requests. Most of the time the server will respond as a json with either:
{"error": "Request invalid"}
or
{"success": "Request successful"}
The server side page that returns the response looks like this:
<?php
header('Content-type: application/json');
$data = [];
if (isset($_POST['action']) {
if ($_POST['action'] == 'function_one') {
/* Arbitary Function... */
$data['success'] = 'This works...';
} elseif ($_POST['action'] == 'function_two') {
/* Arbitary Function... */
$data['error'] = 'Example error';
} elseif ($_POST['action'] == 'function_that_is_not_working') {
$data['success'] = 'This unexpectedly does not interpret correctly...';
}
}
$post_data = json_encode($data);
print_r($post_data);
?>
The javascript file does the http request and handles the data similar to:
if (xml_http.readyState == 4 && xml_http.status == 200) {
try {
console.log(JSON.parse(xml_http.responseText));
return JSON.parse(xml_http.responseText);
} catch (e) {
console.log(xml_http.responseText);
return xml_http.responseText;
}
}
So this all works absolutely fine, I have multiple functions all using the same code without an issue. The problem I have is that I have one specific action that does a request, if I set $data['success'] it does not interperet as a JSON object, but a string. If I set the key as anything else, it works fine.
I have tried commenting out the function in case there is some unexpected echo's etc.
The JSON string is a valid JSON string, it's just this one action when using the success key that the JSON.parse doesn't see it as valid JSON so just outputs the string.
Am I missing something obvious? Are there other ways that I could test this?
Edit After a little more playing around I found out there was nothing wrong with the response, nor the JSON.parse.
I had an issue with some of the script after causing an error.
Solution: Always look at the bigger picture, and the subsequent processes.
I've done some hunting around, and I haven't seen my question asked by anyone yet. So, I'll ask here.
I'm new to computers in general and very new to web development specifically. I'm currently building my first website. It has a back-end database, server side scripting, the whole shebang.
Also, I'm on a Linux/Apache/PHP platform using a LAMPP local host server.
Preliminaries discussed, I was coding an AJAX call today (my first!) and came across some strange behavior on the front end. I'll post the code, but I'll briefly explain first.
My code is for a log-in form that verifies your password and username and then either lets you move on into the site or puts up an error message on the screen. I use JS for front end error checking just to stop any unnecessary data exchange from the client to the server.
Of course, you can't trust anything on the front end, so I wrote some PHP to error check on the back end as well. To test the efficacy of my back end error checking, I intentionally changed the parameters of the back end code so that my input would be accepted by JS but rejected by PHP.
Here is the code:
function serverValidation(x, y){
var z;
if (window.XMLHttpRequest){z=new XMLHttpRequest();}
else{z=new ActiveXObject("Microsoft.XMLHTTP");}
z.onreadystatechange=function(){
if (z.readyState==4 && z.status==200 && z.responseText == "false"){
$("#submit_error_3").show();
$( "#submit_error_3" ).text("X INVALID ENTRY");
$( "#username, #password").css("border-color", "red");
}
if (z.readyState==4 && z.status==200 && z.responseText == "true"){
$("#hidden_form_profile").submit();
}
}
z.open("POST","login.php",true);
z.setRequestHeader("Content-type","application/x-www-form-
urlencoded");
z.send("username=" + x + "&" + "password=" + y);
}
As you can see, I'm using POST to send form-like data, and I'm receiving ordinary text. The response is either the string "true" or the string "false". If "true" is received, the JS goes one way. If "false" is received, the JS goes another.
Here's the back end:
<?php
session_start();
if(!isset($_POST['email']) && isset($_POST['username']) && isset($_POST['password'])){
$x = trim($_POST['username']);
$y = $_POST['password'];
if(validate($x, $y)){$_SESSION["logged_in"] = "true"; echo "true";}
else{
echo "false";
}
}
function validate($x, $y){
if( strlen($x) < 6 || strlen($y) < 6 ){
return false;
}
return true;
}
?>
This all works great, just as expected.
But, the back end isn't done. Once the format of the input is verified, I then plan on going into the database and matching the username and password to see whether the input is valid.
To that end, I included a PHP file with: include "login_info.php"; at the very top of the AJAX back-end script. This file just holds basic variables for the database server address, the database name, the username, and password.
Once I included that file, saved, and refreshed, things got VERY strange.
Basically the AJAX call stopped working. Through troubleshooting with alert boxes and such, I ascertained that the PHP script did its job, but the front end script wouldn't interpret the data properly.
As far as the JS was concerned, the returning data was a string and it took on the values "true" and "false" under the expected circumstances, but if(z.responseText == "false") and (z.responseText == "true")both evaluated to false in all cases.
Further, if(z.responseText) always evaluated as true in all cases. That is, when I included that extra file, somehow the JS considered the returning data to be a string with the expected value but treated it as a boolean that was always true.
Can someone explain to me what happened when I included that file in the back-end script?
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 years ago.
I have a simple checklist form with a number of input fields and counters to check them. Form consists of only few text fields and some radio buttons, whose value is set to either conforms or notConforms:
error counter ($errCounter) = counts errors like illegal input format and missing fields
non conformance counter ($notConforms) = checks if/how many input fields are set to notConforms.
I am trying to alert the user and get their confirmation if any inputs are set to notConforms.
Two problems with the outcome of my code below:
it makes two entries (duplicate) into database
after database update, it does not header the user to the indicated page (inspectionbatch.php)
What is wrong with the following?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if($errCounter == 0){ // provided there are no errors found during form validation
// warn user if there is a non-conformance
if($notConforms !== 0){ ?>
<script>
if(confirm("A not-conforms 'N/C' result has been recorded for one or more inspection criteria. If this is accurate, click OK to continue.")) {
<?php echo updateDatabase(); header("location: inspectionbatch.php");?>
} else {
<?php echo updateDatabase(); header("location: inspectionbatch.php");?>
}
</script>
<?php } else {
updateDatabase(); header("location: inspectionbatch.php");
}
} else { // if errors are found during form validation, return how many errors were found
echo "Error count: " . $errCounter;
}
}
I also tried putting the header() function inside the updateDatabase() immediately after the syntax to update database. Database was updated fine but header() did not work...
This code doesn't work because PHP, a server-side technology, runs to completion before javascript, a client-side technology, even begins. All the PHP code will execute on your web server, and a response will be sent to the client and then all the javascript will run in the the web browser.
If you want to mix the 2, you'll have to imagine how the completely rendered dynamic result will look to a web browser.
Additionally, a call to the header() function cannot be made if any bytes have already been written to the HTTP body. From the docs:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
I'm trying to check the db to make sure a user name doesn't already exist during a registration process. I have it getting the count from the db.
PHP Code:
if($result=mysql_query("SELECT count(*) from users where username='$requsername'"))
{
while($row=mysql_fetch_array($result))
{
$usercount=$row[0];
echo $usercount;
}
}
else
{
$goof=mysql_error();
$error = "<b>Error:</b> $goof";
echo $error;
}
jQuery code:
$('#newusername').blur(function() {
var requsername=$('#newusername').val(),
dataString='requsername=' + requsername;
$.ajax({
url:'scripts/checkusername.php',
data: dataString,
type:'POST',
success: function(data) {
var response=data;
if(response==="0") {
$('#usernamestat').html('Username Available');
$('#addusrbtn').removeAttr('disabled');
alert(response);
}
}
}
}
But it is ignoring the value of data. I did an alert and it is alerting the number from the db but it isn't running the code to enable my button and say username available. I do not know what I"m doing wrong! I want it to either pass or fail - if it passes (no users found with that username requested) it enables the submit button and lets them continue; but if it does not pass and has a value of greater than 0, it displays an error message that the username is already taken. It is not working at all or recognizing the numbers at all!
Are you even sure whether your ajax call is made? From what i recall you don't supply data to jquery ajax functions in form key=value but in form {key: value}
When you can't guess what you do wrong, do some debugging:
use console.log(data)
or use developer tools or firebug and put a breakpoint inside you success function.
Or have a look at network tab and see what your ajax request headers was and what was the response.
Put vardump in php code.
Use a decent IDE that allows real tume line by line debugging of PHP ...
install xdebug
So many ways to do it...
I use Php storm debugger 3 hours a day , Dev tools another 3 :)
1)
//Hope this might help
//check wether control goes to else part
success: function(data) {
var response=data;
if(response==="0") {
$('#usernamestat').html('Username Available');
$('#addusrbtn').removeAttr('disabled');
alert(response);
}else{
alert("Username not available");
}
//if it goes to else part then change your if condition to
if(response === 0) {//return from php might be of integer operator(===) needs value along with type to be same
-----
-----
}
OR
if(response == "0")
use mysql_num_rows instead of
while loop.
it will give you number of rows.
then you check as
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
{
echo 'usename already exist.';
}
I'm using AJAX to make a call to a PHP script. The only thing I need to parse from the response is a random ID generated by the script. The problem is that the PHP script throws a number of errors. The errors are actually fine and don't get in the way of the program functionality. The only issue is that when I run
$.parseJSON(response)
I get:
Uncaught SyntaxError: Unexpected token <
Since the PHP response starts with an error:
<br />
<b>Warning</b>:
I'm wondering how to change the PHP or JS such that it can parse out the ID despite the errors.
PHP:
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
...
JS:
function returnReport(response) {
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
I know that the warnings should be resolved, but the warnings are not functionality critical for now and more importantly
1) Even if these warnings are resolved new ones may come up down the line and the JSON should still be properly parsed and
2) In addition to the warnings there are 'notices' that cause the same issue.
Why not deal with and eliminate the warning so that the result from the server is actually JSON?
There are several ways this could be solved (any one of which would work):
1. Fix your warnings. : PHP is saying something for a reason.
2. Turn off error reporting & error display:
At the top of your file place the following
error_reporting(false);
ini_set('display_errors', false);<br/>
3. Use the output buffer:
At the top of your file place
ob_start();
When you have your data array and your ready to echo to browser clear the buffer of all notices warnings etc.
ob_clean();
echo json_encode($returnData);
ob_flush();
4. Set a custom error handler:
set_error_handler("myCustomErrorHandler");
function myCustomErrorHandler($errno, $errstr, $errfile, $errline){
//handle error via log-to-file etc.
return true; //Don't execute PHP internal error handler
}
5. Optionally in JavaScript:
Sanitse your response to be a JSON array:
function returnReport(response) {
response = response.substring(response.indexOf("{") - 1); //pull out all data before the start of the json array
response = response.substring(0, response.lastIndexOf("}") + 1); //pull out all data after the end of the json array
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}
Like everybody else has said, you SHOULD really fix your errors and handle them accordingly.
This is something more to have under circumstances that you will not control and yet want to handle errors accordingly:
<?php
//Change it to 'production' or something like that
//so that you don't send debug data on production
define('ENVIRONMENT', 'testing');
//Set your error handler globally
set_error_handler('handle_error');
function handle_error($errno, $errstr, $errfile, $errline, array $errcontext )
{
//Set your headers to send a different than 200 so you can
//catch it on error on jQuery
header($_SERVER["SERVER_PROTOCOL"].' 500 Internal Server Error');
//Set output as json
header('Content-Type: application/json');
//Create some sort of response object
$response = new stdClass;
$response->message = "Application error details";
//You dont want to give debug details unless you are not on prod
if(ENVIRONMENT == 'testing') {
$severity = get_err_severity($errno);
$response->error_detail = "({$severity}) [{$errfile}#L{$errline}]: {$errstr}";
$response->context_vars = $errcontext;
}
//Return the json encoded error detail and exit script
$json = json_encode($response);
exit($json);
}
function get_err_severity($severity)
{
switch($severity) {
case E_ERROR:
return 'E_ERROR';
case E_WARNING:
return 'E_WARNING';
case E_PARSE:
return 'E_PARSE';
case E_NOTICE:
return 'E_NOTICE';
case E_CORE_ERROR:
return 'E_CORE_ERROR';
case E_CORE_WARNING:
return 'E_CORE_WARNING';
case E_COMPILE_ERROR:
return 'E_COMPILE_ERROR';
case E_COMPILE_WARNING:
return 'E_COMPILE_WARNING';
case E_USER_ERROR:
return 'E_USER_ERROR';
case E_USER_WARNING:
return 'E_USER_WARNING';
case E_USER_NOTICE:
return 'E_USER_NOTICE';
case E_STRICT:
return 'E_STRICT';
case E_RECOVERABLE_ERROR:
return 'E_RECOVERABLE_ERROR';
case E_DEPRECATED:
return 'E_DEPRECATED';
case E_USER_DEPRECATED:
return 'E_USER_DEPRECATED';
}
}
function test_error()
{
$test = array('foo'=>'bar');
$baz = $test['baz'];
echo $baz;
}
test_error();
While this doesn't solve the broader issue of warnings, I used this hack to parse the response:
function returnReport(response) {
var pdfID = parseID(response);
...
}
function parseID(response) {
var responseIndex = response.indexOf('{"id');
var start = responseIndex + 7;
var pdfID = response.slice(start, start + 6);
return pdfID;
}
I know everybody has recommended you fix the errors, I would agree, but if you do not want to then there is another a solution.
If you are getting a number of warnings and expect new warnings could appear, simply disable reporting of warnings and notices:
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
If ob is enabled
ob_end_clean();
ob_start();
echo json_encode($returnData);
Or, in top of your file
error_reporting(0);
I am sure that there would be some mistakes in your PHP code due to that error is coming please check few things:
Make sure that there should not be more than one echo or print in your php code for printing response.
jQuery must be included properly.
And check the other php code in your function/page that should not produce any run time errors/warnings because it will also create same problem.
I am saying this because I have tried your code and it working fine for me you can check that also:
PHP File: myContentPage.php
<?php
$returnData = array();
$returnData['id'] = 123;
echo json_encode($returnData);
?>
HTML File:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='js/jquery.js'></script>
</head>
<body>
<h1>Demo Example</h1>
<script>
function loadResponse() {
var dataString={};
$.ajax({
url:"myContentPage.php",
type: 'POST',
cache:false,
data: dataString,
beforeSend: function() {},
timeout:10000000,
error: function() { },
success: function(response) {
var parsedResponse = $.parseJSON(response);
pdfID = parsedResponse['id'];
console.log(pdfID);
alert(pdfID);
}
});
}
loadResponse();
</script>
</body>
</html>
And for handling the warnings you can do these this:
To skip warning messages, you could use something like:
error_reporting(E_ERROR | E_PARSE);
or simply add the # sign before the each line of php code on that you think warning can come
Happy Coding!!
Script used in Ajax call just must have perfect constrution, shall not thrown any warnings just by convenience, for production you should have erros disabled, so fix it into development, edit the question with the warning that's phps givin to we help you with directly on the point.
1st alternative:
Solve the problem causing the warning. A good PHP system should never show a PHP Notice, Warning or Error. This may expose some critical information.
2nd alternative:
Just disable error reporting by setting
error_reporting(0);
This will work, but will hide even to you any errors.
3rd alternative:
Set a error handler function that treat the error and show a JSON friendly error message that does not cause any trouble.
Also I recommend you to log this exceptions. It will allow you to debug any system trouble.
My recomendation?
Use 1st and 3rd alternatives together, and be HAPPY!
You can use Try..Catch construct in the javascript function code as shown below.
function returnReport(response) {
try
{
var parsedResponse = $.parseJSON(response);
console.log(parsedResponse);
pdfID = parsedResponse['id'];
}
catch(err)
{
//Do something with the err
}
}
This will work even if your php code generates debug info in response.
If you want to see the error in JavaScript, you should handle the error on PHP with a "try catch" and the "catch" to do something like "echo json_enconde ($ error);" on this way you can parse from JavaScript.
Example:
try{
$returnData = array();
$returnData['id'] = $pdfID;
echo json_encode($returnData);
}catch (Exception $e) {
echo json_encode($e);
}
I hope this helps :)!