Return Single Response using PHP_SELF - javascript

I'm using $_SERVER['PHP_SELF'] to run a function because of the way it's included and called within my plugin page I can't directly call the functions.php file, so what I'm trying to do now is work on the registration script, the problem is my returns can't be utlized the way I would like. For instance.
public function CheckUserName() {
$query = <<<SQL
SELECT id
FROM {$this->tprefix}accounts
WHERE username = :posteduser
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
':posteduser' => $_POST['username'],
));
if($resource->rowCount() == 0 ) {
//Self Continue to run checks
}
else {
echo "1";
}
}
is my check to make sure that a username isn't already taken, whereas two will be my response echoed if the email is already in use. My Ajax is
$(function() {
$("#register_").submit(function(event) {
event.preventDefault();
var username = $("#username").val();
if(username == "") { $("#unameerror").html("Username is Required"); }
$.ajax({
type: "POST",
url: $("#register_").attr("action"),
data: $("#register_").serialize(),
success: function(data) {
if(data==1) { alert("Username is taken. Please choose another!" };
if(data==2) { alert("Email already registered. Please select lost password
if you have forgotten your password" };
if(data==0) { alert("Account Created!") }; //0 is returned after all checks passed and scripts executed
},
error: function() {
alert("Something isn't right");
}
});
});
});
My issue is since it's running from PHP_SELF it's putting out all information(IE <html><title>reg script</title><body><form id = "reg"></form></body><html>
The best way I can think to put this is how can I parse all my data return to simply return the script code?

This worked for my framework. Since everything is included into the index.php file and then just pulled through variables as includes it's always the index.php file
which is currently
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once(dirname(__file__).'/config.php');
require_once(dirname(__file__).'/directives.php');
LoadClasses();
$Theme->Load(ACTIVETHEME);
I simply changed the bottom part to
if(isset($_POST['process'])) {
}
else {
$Theme->Load(ACTIVETHEME);
}
Now it has no problem loading my pages, but when I execute a form with process input ( IE <input type="hidden" name="process" id="process" value="register"> )
It now loads the page if no form is executed, but since I want all plugins to run through ajax it works great with that addition if a process was posted then it only returns the php scripts data.

Related

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

ajax request is successful, but php is not running

I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:
function getObdDescription(){
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if($length == 5){
window.confirm($length);
$.ajax({ url: '/new.php',
data: {action: 'test'},
type: 'post',
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});
}
return false;
}
Here is new.php
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
?>
I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?
This isnt the way it works if you need to alert the text, you should do it at the front-end in your ajax success function, follow KISS (Keep It Simple Stupid) and in the php just echo the text . that is the right way to do it.
You should do this:
function getObdDescription() {
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if ($length == 5) {
window.confirm($length);
$.ajax({
url: '/new.php',
data: {
action: 'test'
},
type: 'post',
success: function (result) //we got the response
{
alert(result);
},
error: function (exception) {
alert('Exception:' + exception);
}
});
}
return false;
}
In your php
<?php
echo 'message successfully sent';
?>
You are exactly right Muhammad. It was not going to work the way I was expecting it. I wasn't really trying to do an Ajax call, but just to get an alert box to pop up; I just wanted confirmation that the call was working, and the PHP was running. Changing the alert('Successfully called'); to alert(result); and reading the text from the php definitely confirmed that the php was running all along.
I want to stay on topic, so will post another topic if that's what's needed, but have a follow-up question. To elaborate a bit more on what I'm trying to do, I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
Now, I know that this function works. I can then access this function in my Javascript with:
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
This is a block loop, and will loop through the block variable set in the php function. This work upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the php runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the html. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
I'm using this conditional and switch to call the function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. It appears that the block variable is not being set.

show a div based on a conditional ajax result in php form

I have a PHP form`looks like this
<form>
<div id="inid">
National ID: <input type="text" id="individual_nid" oninput="getIndividualName(this.value)" />
</div>
<hr />
name: <div id="individual_name_fetch"></div>
<hr />
<div id="other_inputs fields" style="display: none;">
more inputs fields...
</div>
</form>
In my PHP form I have an input textbox where the user inserts a number
<input id="individual_nid" oninput="getIndividualName(this.value)" />
this textbox fires on the fly the following ajax function
function getIndividualName(val)
{
$.ajax({
type: "POST",
url:"get_individual_name.php",
data: 'individual_nid='+val,
success: function(data){
$("#individual_name_fetch").html(data);
}
});
}
in this function, I pass the user's input to the get_individual_name.php page.
in the get_individual_name.php page, I have a PHP script that searches for the inserted number in the database and gets the corresponding individual name and fetches it to the id="individual_name_fetch" div.
the PHP script in the get_individual_name.php page looks like this:
$q = mysqli_query($link, "SELECT * FROM table WHERE national_id = '".$_POST['individual_nid']."' ");
if(mysqli_num_rows($q) == 1)
{
while($r = mysqli_fetch_assoc($q))
{
echo $individual_name = $r['individual_name'];
}
}
else
{
echo $individual_name = 'Not in db';
}
up to here everything is fine
What I need to do now...
If the searched user founded in the db (mysqli_num_rows($q) == 1) then I want to display the other inputs div id="other_inputs fields" in the form. and if not, then the other_inputs fields div hides again
How can I accomplish this?
please be aware that the ajax function and the PHP script run on the fly
NOTE & UPDATE
the script's output will be HTML code, for example
if the result found the output will be:
<span style="color: green;"><i class="fa fa-check fa-fw fa-lg"></i> <?=$individual_name;?></span>
OR
in case no result found:
<span style="color: red;"><i class="fa fa-times fa-fw fa-lg"></i> No user found.</span>
What I am thinking about is to assign a variable e.g. $show_extra_fields = true or $show_extra_fields = false and pass it back to the ajax function and from there I check the value of the $show_extra_fields variable and based on the value I show/hide the other fields div.
is this possible?
To do what you're asking you would add show and hide functions to the AJAX callback:
function getIndividualName(val)
{
$.ajax({
type: "POST",
url:"get_individual_name.php",
data: 'individual_nid='+val,
dataType: 'json',
success: function(data){
$("#individual_name_fetch").html(data);
if(data[0] != 'Not in db') {
$('#other_inputs').show();
} else {
$('#other_inputs').hide();
}
}
});
}
Keep in mind that ID's Must Be Unique, specifically because it will cause problems in JavaScript and CSS when you try to interact with those elements. ID's must not have spaces in them.
EDIT: Return JSON with PHP (CAUTION: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!)
$q = mysqli_query($link, "SELECT * FROM table WHERE national_id = '".$_POST['individual_nid']."' ");
$json = array();
if(mysqli_num_rows($q) == 1)
{
while($r = mysqli_fetch_assoc($q))
{
$json[] = $r['individual_name'];
}
}
else
{
$json[] = 'Not in db';
}
echo json_encode($json);
You can do that using JavaScript. Check the AJAX response then take an action depending on this response.
Note: Don't use spaces in the id in your html
success: function(data){
$("#individual_name_fetch").html(data);
if (data === 'Not in db') {
document.getElementById('other_inputs_fields').style.display = 'none';
} else {
document.getElementById('other_inputs_fields').style.display = 'block';
}
}
The quick fix: Don't produce any output in case there is no data. Just check for empty string in response.
success: function(data) {
if (data === "") {
$('#other_inputs_fields').hide();
$("#individual_name_fetch").html('No data available');
} else {
$('#other_inputs_fields').show();
$("#individual_name_fetch").html(data);
}
}
Long term solution: This code still looks OK for student's assignments work or hobby project. But in all other cases, you better look for some WEB framework, like Symfony https://symfony.com/. Frameworks will help you to build your application in a more structured way, offering the best practices our of the box, including the security issues pointed out in comments.

Why Its not working: Jquery Ajax success data with PHP return variable [duplicate]

This question already has answers here:
When should I return true/false to AJAX and when should I echo "true"/"false"
(4 answers)
Closed 6 years ago.
I am trying to create a Ajax functions that made a decision based on a return var from PHP. The main issue I have is the return var will display correctly when I print it to an html class, but the decision within ajax still produces the same result of false.
Below is the PHP form:
<form class="LogInForm" method="post" action="Auth.php" >
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email Address" value="<?php echo $_SESSION['email'];?>">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pw" placeholder="password">
</div>
<button type="submit" class="btn btn-default btn-block">Submit</button>
And below is the jquery script:
$('.LogInForm').on('submit', function(e){
var values = $(this).serialize();
// get value of action attribute
var desination = $('.RemoveProd').prop('action');
// get current location url
// prevent page from leaving to desination
e.preventDefault();
$.ajax({
url: desination,
type: 'post',
data: values,
success: function(data){
if(data == 1){;
alert("True");
$('.Test').html(data);
}
else{
alert("False");
$('.Test').html(data);
}
},
error: function(){
}
});
});
The PHP Function:
function Auth()
{
//start session and compture login info
$pass = md5($_POST['pw']);
$user = $_POST['email'];
//connect to DB
$conn = Connect();
//Select all queries
$select = "SELECT Email, Password FROM customers WHERE Email ='".$user."' AND Password = '".$pass."'";
$results = $conn->query($select);
//search in db for user and passwrod, also store quires in var to store in sessions.
if ($results->num_rows > 0) {
$bool = true;
}
else{
$bool= false;
}
echo $bool;
}
What happens is if I don't put in the right password if alerts me False and under the submit button tell me what the data is (which is null). When I put in the correct password, it still alerts me False but the data displays under the submit button as 1.
Also note when I bypass the Ajax function The PHP function works correctly.
Update
I was able to get this working. All i did was move the php file Auth.php to another directory and it seem to fixed the issue. I know it wasn't a file path issue. I thank you all for your time and thank you for answering and pointing me in the right direction with security vulnerabilities.
Javascript == is false if the values are of different types. I suspect the value you're getting back through AJAX is being read as the string "1" instead of the integer 1 (or the boolean TRUE). Try changing your comparison to:
if(data == '1')...
i have tested this, its working correct
$('.LogInForm').on('submit', function(e){
var values = $(this).serialize();
// get value of action attribute
var desination = $('.RemoveProd').prop('action');
// get current location url
// prevent page from leaving to desination
e.preventDefault();
$.ajax({
url: desination,
type: 'post',
data: values,
success: function(data){
//remember the returned value is a type string if not changed or maybe it a raw integer from php
if(parseInt(data.trim().replace(/\D*/g,'')) == 1){
alert("True");
$('.Test').html(data);
}
else{
alert("False");
$('.Test').html(data);
}
},
error: function(e){
//check the logged error for more details
console.log(e)
}
});
});

Use AJAX and PHP to "Alert" the user if the username exists on the same page?

I have found many AJAX scripts that do a live check on if the username exists in a MySQL database. For example, most will maybe show a green check image if it does not exist or a red x if it does already exist.
I am interested in a slightly different method for this form.
Users fill out a 10 question quiz and then are taken to a user registration form. I only want to insert the user's answers into the database if they complete the quiz.
Currently, if a user enters a username or email that already exists, they will receive an error on the next page and be told to be go back only to find that the form has been reset.
That is why I want the information validated all on the same page.
Upon clicking the submit button, a javascript function is called that verifies a few things such as if the user has entered a date of birth, has not left a form blank, if passwords match, etc.
It returns false if any of the criteria is not met so that the form does move to the next page unless all of the functions return true.
Here is what it looks like.
function checkForm() {
if (checkUser() && checkPassword() && checkMonth() && checkDay() && checkAddress() && checkYear()) {
document.getElementById("quizForm").method="post";
document.getElementById("quizForm").action="register.php";
}
else {
return false;
}
}
I am interested in creating a username/email check function that uses ajax to access a php page that searches the database and returns true or false to javascript on if the username/email exists in the database.
That way, I can just use the old javascript alert to say if a username/email exists and then return false so that the form is not submit.
This is an example of how I am writing the functions for this:
function checkPassword() {
var pass1 = document.getElementById("pass").value;
var pass2 = document.getElementById("c_pass").value;
var pass1l = pass1.length;
if (pass1l < 5) {
alert("Please create a password that is longer than 5 characters.");
return false;
}
else {
if (pass1 != pass2) {
alert("Your passwords do not match.");
return false;
}
else {
return true;
}
}
}
Can anyone point me in the right direction for this? I have been searching around but have not found anything that is this specific.
Thank you.
You could AJAX Post on change event of the <input> where the user enters the username. Consider the example below I quickly put together. It assumes you have the database table users with columns id and username. It also assumes you have a file check.php connecting to this database table with a MySQLi connection in the variable $mysqli. When the input changes, it will call check.php, with the only data being the username entered. Depending on the response, it will update <span id="info">.
HTML:
<input id="username" type="text" /><span id="info">Exists/Does not exist</span>
Javascript(jQuery):
$(function() {
$("#username").on("change", function() {
var data = "user="+$("#username").val();
$.ajax({
type: 'POST',
url: 'check.php',
data: data,
dataType: 'json',
success: function(r)
{
if(r=="1")
{
//Exists
$("#info").html("Username already exists");
}else{
//Doesn't exist
$("#info").html("Username available!");
}
}
});
});
});
PHP(check.php):
$user = $_POST['user'];
if($stmt = $mysqli->prepare("SELECT id FROM users WHERE username = ?"))
{
$stmt->bind_param('s', $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id);
$stmt->fetch();
if($stmt->num_rows>0)
{
echo "1";
}else{
echo "0";
}
}
I'm using similar functionality on my current project, and it works fine. Especially with local files as response time is improved!
(Reserved for typos, was in a rush-ish)
Hope this helped.

Categories

Resources