Q. Is there a way to pass values from ajax to a certain php class having functions? Let's say validating a username on the registration form whether the user exist or not.
This is a simple form that will accept username and has a span tag to display the message.
<form action="" method="POST">
<input type="text" name="username"><span class="check"></span>
<input type="submit" name="signup">
</form>
And for the php class:
<?php
class User {
function isUserExist($username) {
$query = mysql_query("SELECT username FROM users WHERE username='$username'");
$result = mysql_num_rows($query);
return ($result !== 0 ? true : false);
}
}
?>
It is initialized on the php class that established connection to the database.
So calling to the php page will become like this: $user->isUserExist($_POST['username']);.
So is it possible to pass values from the form to ajax and send it to the php class function?
From Html to ajax
var username = $("input[name='username']").value;
Fetch in ajax & Send it to php(server)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//set your span to this -> xhttp.responseText;
}
};
xhttp.open("POST", "your php script url", true);
xhttp.send("username="+username);
Receive it on the server(php)
$mUsername = $_POST['username'];
echo $mUsername;
Read this tutorial for more help
Tutorial on PHP + AJAX
Try this,
<script type="text/javascript">
$(document).ready(function(){
$("input[name = 'signup']").click(function(e) {
var username = $("input[name = 'username']").val();
$.ajax ({
url: "isUserExist_function_existing_file.php",
data: { username : username },
success: function( result ) {
if(result)
alert("Name allready Exist");
else
alert("Name available");
}
});
});
});
</script>
Related
Okay so i have php code which is supposed to check if there is an existing user in database when login is attempted and send back to javascript fail or success
Php code:
<?php
require_once 'Korisnik.php';
require_once 'dbconn/korisnikdb.php';
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// collect value of input field
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$korisnik = getKorisnikByUserPass($username, $password);
if ($korisnik == null) {
$statusArray = array("status"=>"fail");
echo json_encode($statusArray);
return;
} else {
session_start();
$_SESSION["prijavljeniKorisnik"] = $username;
$statusArray = array("status"=>"success");
echo json_encode($statusArray);
return;
}
}
?>
Here i have my javascript code :
$(document).ready(function() {
var usernameInput = $('#usernameInput');
var passwordInput = $('#passwordInput');
var pogresniPodaci = $('#pogresniPodaci');
var praznaPolja = $('#praznaPolja');
pogresniPodaci.hide();
praznaPolja.hide();
$('#submitButton').on('click', function(event) {
var username = usernameInput.val();
var password = passwordInput.val();
console.log(username);
console.log(password);
if (username == '' || password == '') {
praznaPolja.show();
event.preventDefault();
return false;
}
var params = {
'username': username,
'password': password
}
$.post('loginCheck.php', params, function(data) {
console.log(data.status);
if (data.status == 'fail') {
pogresniPodaci.show();
usernameInput.val('');
passwordInput.val('');
return;
}
if (data.status == 'success') {
location.href = 'pocetna';
}
});
event.preventDefault();
return false;
});
});
http://prntscr.com/skb37r -> here you can see status after i press that button
The problem is that php code in loginCheck.php never actually executes, I tried adding echo at start of php file but it doesn't execute.
You are sending http request to localhost. Even if file doesn't exist, your localhost will return status 200, unless it's configured to throw an error.
Try this:
go to http://localhost/loginCheck.php and echo anything there.
echo "This is loginCheck";
If it echoes, you are on the right route to loginCheck file.
If it works, go to browser dev tools > network > and see request headers and find "Request URL" header. it should be "http://localhost/loginCheck.php" - the route to file you visited previously. if its not, you have to fix it in $.post request.
I have a login form which is validated using javascript and then sent to php file for further processing. Form is submitted via ajax.
Currently, i have an if statement in php file that checks whether form has been submitted, problem is this if statement never evaluates to true. Hence my php code inside my if statement never runs. When request is sent via ajax, .onload event gets invoked without if statement inside php file evaluating to true.
Question
Once the form is submitted to php file via ajax, how can i detect in php file that form has been submitted via javascript.
Here's my php code
<?php
require 'DbConnection.php';
// if form is submitted
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
echo '<script>alert(\'form submitted\')</script>';
verifyLoginCredentials($username, $password);
} else {
echo '<script>alert(\'form not submitted\')</script>';
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
}
else { // if username/password combination is incorrect
echo 'Incorrect Username/Password Combination';
}
} else { // if username doesn't exists in the database
echo 'Entered username isn\'t registered';
}
} else {
echo 'Error while preparing sql query';
}
}
?>
and here's relevant javascript code
let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');
// submit login form to server using ajax
function ajaxFormSubmit() {
'use strict';
let ajaxRequest = new XMLHttpRequest();
let url = 'admin login.php';
// login form submitted on server successfully
ajaxRequest.onload = function () {
if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'success');
}
};
// error while login form submission on server
ajaxRequest.onerror = function () {
if (ajaxRequest.status !== 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'error');
}
};
ajaxRequest.open('POST', url, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(new FormData(loginForm));
}
function validateForm(e) {
'use strict';
// prevent form submission
e.preventDefault();
if (anyEmptyField()) {
displayInfoMessage('Please fill all the empty fields', 'error');
highLightEmptyFields();
//return false;
return;
}
// check if username is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
displayInfoMessage('Username not valid', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if username is atleast 3 characters long
if (usernameField.value.length < 3) {
displayInfoMessage('Username should contain atleast 3 characters', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if password is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
displayInfoMessage('Password not valid', 'error');
highLightTextField(passwordField);
//return false;
return;
}
// check if password is atleast 6 characters long
if (passwordField.value.length < 6) {
displayInfoMessage('Password should contain atleast 6 characters', 'error');
highLightTextField(passwordField);
//return false;
return;
}
//return true;
// submit form information to server via ajax
ajaxFormSubmit();
}
// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);
There is no guaranteed way to know that the form was submitted via ajax.
Normally this is done via headers, in our case HTTP_X_REQUESTED_WITH which can be retrieved via the global $_SERVER variable.
Do note that headers can easily be spoofed.
You can check like so:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
// code here
}
Here's a few links to look at:
https://paulund.co.uk/use-php-to-detect-an-ajax-request
How to check if the request is an AJAX request with PHP
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
I'm trying to insert data in a sql table using ajax and php, but it's not working. My ajax give me the result like it works, but when i look at the table, there's not in it. Doing it without ajax works fine, so i guess my php is working ok.
Here's the code:
HTML:
<form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>
<input type="submit" value="Enviar"/>
</form>
PHP:
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
switch($passo){
case "cadUsr":
cadUsr();
break;
default:
getRetorno();
break;
}
function getRetorno(){
echo "Este texto foi escrito via PHP";
}
function cadUsr(){
require("dbCon.php");
require("mdl_usuario.php");
$usr = $_POST["txtNome"];
$idade = $_POST["txtIdade"];
$resultado = usuario_cadastrar($con,$usr,$idade);
if($resultado){
echo "Cadastro efetuado com sucesso";
} else {
echo "O cadastro falhou";
}
}
?>
OBS: I need to pass the action of the form with the url parameter as cadUsr, so it call the function in php.
AJAX:
window.onload = function(){
var xmlhttp;
var frm = document.querySelector("#frmCadUsr");
var url = frm.getAttribute("action");
var nm = document.querySelector("#txtNome").value;
var idade = document.querySelector("#txtIdade").value;
frm.addEventListener("submit",function(e){
e.preventDefault();
try{
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("POST",url,true);
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//alert("Deu certo");
console.log(xmlhttp.responseText);
}
}
} catch(err){
alert("Ocorreu um erro.<br />"+ err);
}
});
}
The PHP function to insert the data:
function usuario_cadastrar($conexao,$nome,$idade){
if($nome == "" && $idade == ""){
return false;
}
$sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);
$resultado = mysqli_query($conexao,$sql);
return $resultado;
}
I think the problem is here servico.php?p=cadUsr. You copy the action-attribute from the form with a querystring. If you cut the querystring from it, I think it will work.
The main problem is being called by Hossein:
This :
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
Will not work. You're doing a post, you can't get GET variables.
You call value on value which will result in undefined and that will put no data in your database.
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
So remove value and add the cadUsr variable to the querystring in the send function. Update PHP to:
$passo = (isset($_POST['p'])) ? $_POST['p'] : "";
And it will work!
You can see your callback codes by adding console.log(xmlhttp.responseText); to your readystate success function.
Also you need to set the requestheader content-type to x-www-form-urlencoded when sending post.
I want to post data to a PHP file in a server (www.domaine.com) using a JavaScript located in computer / mobile app
example : test.php
<?php
$x = $_POST['count'];
for ($i = 0; $i < $x; $x++)
echo $x;
?>
data to be post using JavaScript and PSOT method to test.php
example
input
test.php / post data : count=5
output
01234
I want JavaScript to get me the output (01234) after posting (count=5) to (test.php) located in external server (www.domaine.com)
I basically develop in C# but as I'm obliged to do a cross-platform mobile app I switched to JavaScript (won't use Xamarin) for C# I was able to do everything using WebBrowser but not anymore in JavaScript, isn't there any object equivalent to WebBrowser in .NET ?
I need it for a mobile app that will load data from GPS Tracking website, API returns data in both XML and JSON
note : I don't have access to the external server
Here I'll give you a pretty good example of how these things are usually managed.
Still, it's up to you and your programming experience to grasp the meaning of it.
html and js example:
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
}
$("#submit").click(function(){
$("#formId").submit();
});
$(document).ready(function () {
$("#formId").bind("submit", function (event)
{
$.ajax({
async: true,
data: $("#formId").serialize(),
success: function(data, textStatus) {
getPhpResponse( data )
},
type:"POST",
url:"name/and/location/of/php/file.php"
});
return false;
});
});
</script>
file.php example:
<?php
$x = $_POST['count'];
echo '{"response":"';
for ($i = 0; $i < $x; $i++)
{
echo $i;
}
echo '"}';
Poxriptum:
There should be further input validation, one can't trust the type="number" just yet.
That the submit button is a span instead of an input is a personal choice that makes difference just for styling purposes.
You should read up on AJAX and JSON.
Consider using a PHP framework, such as CakePHP; it may serve you well.
This answer assumes you have access to the server. If you don't, then you should be reading the API documentation instead of asking questions on SO without even detailing which API you are talking about.
Edit:
Here is the $less version.
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
document.getElementById("submit").onclick = function () {
var url = 'name/and/location/of/php/file.php';
var userInput = encodeURIComponent(document.getElementById("inputNumber").value);
var data = "count=" + userInput;
makeRequest( data, url );
};
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
console.log(data);
parsed = JSON.parse(data);
console.log(parsed);
}
var xhr = new XMLHttpRequest();
var makeRequest = function( data, url ) {
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
if ( xhr.status == 200 || window.location.href.indexOf("http") == -1 )
{
getPhpResponse(xhr.responseText);
}
else
{
console.log("Manage error here");
}
}
}
</script>