Below is my code for the problem. I am trying to call php file via AJAX.
I have an HTML file where after form submission, the AJAX calls the PHP file.
Unfortunately, I cannot see any output.
HTML File(Body):
<form>
<label for="">Username</label>
<input type="text" name="username" value="">
<br><br>
<label for="">Password</label>
<input type="text" name="password" value="">
<br>
<button name="button" id="button" value="Submit">Submit</button>
</form>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="login.js"></script>
My login.js file(for AJAX):
$("#button").click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'login.php'
});
});
My PHP file:
<?php
// Server credentials
$serverName = "localhost";
$username = "root";
$password = "root";
$dbName = "Blog";
//Creating connection
$db = mysqli_connect($serverName,$username,$password,$dbName);
if(!$db){
echo "error";
die($db);
}
else{
echo "er22ror";
}
mysqli_close($db);
?>
Your AJAX call doesn't do anything with the result:
$.ajax({
type: 'POST',
url: 'login.php'
});
In order to see output, you have to output something. Use a callback for that. For example, you can log the result to the console:
$.ajax({
type: 'POST',
url: 'login.php'
}).done(function (result) {
console.log(result);
});
$.ajax({
type: 'POST',
url: 'login.php',
success: function (res) {
alert('hi'+res);
}
});
used above. you can also show in console window
Related
I am trying to hide the submit button if the email is the same with the one in the database from action.php. How could I implement this in my following code:
<form onsubmit="return submitdata();">
<input type="text" id="mail">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('mail').value;
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
console.log(data);
$('#msg').html(data);
}
});
return false;
}
</script>
action.php:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "Response: ".$email;
$hide = 1;
}else{
echo 'hmmmm';
}
?>
When the email coincide I get the correct message, but how could I call back $hide to determine to hide my submit button?
Instead of returning a message, return an indication.
(In the JS script write the message accordingly)
A detailed json string would be a good idea but for simplification see the following.
PHP:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "already_exists";
}else{
echo 'not_exists';
}
?>
JS:
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
if(data == 'already_exists'){
$('#buttonId').hide();
} else if(data == 'not_exists'){
$('#msg').html('Response: ' +name);
}
}
});
I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.
<script>
function submitForLogin()
{
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" }}).done(function(data){alert(data);});
}
</script>
When user clicks on login button it calls submitForLogin() function.
Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.
Note : example#abc.com and 123 both email and password stored in Wamp server database.
This is the PHP file :
<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection
$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
echo "userExist";
}
else
{
echo "fakeUser";
}
mysqli_close($con);
?>
Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.
Is there something I missing? I'm running the website in wamp server too.
UPDATE
When I check console errors it shows;
And when I click on login.html line 112, it shows;
And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.
There was a jquery error and now it's fixed. But syntax error exists.
Try this code working for me on my machine. Don't forgot to place Jquery File.
PHP (ajax.php) :
<html>
<head>
<script src="jquery.min.js"></script>
<script>
function submitForLogin()
{
alert("23");
var email = document.getElementById("txtUserName").value;
var password = document.getElementById("txtPassword").value;
$.ajax({
type: "POST",
url: "login1.php",
data: { email: email,password:password },
success : function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<input type="text" placeholder = "Enter user name" id="txtUserName"/>
<input type="password" placeholder = "Enter password" id="txtPassword"/><br>
<input type="button" onclick="submitForLogin();" value="Login"/>
</body>
</html>
Server Side (login1.php) :
<?php
var_dump($_POST);
?>
You need to include a function for when the request is successful, which includes the response.
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success:function(data){
alert(data)
};
});
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success: function (data) {
alert(data);
}
});
your data in AJAX call is in JSON format.
in your php script you should use json decode as below
$data = file_get_contents("php://input");
$data = json_decode($data,true);
$userEmail=$data['email'];
$userPass=$data['password'];
i hope this might help you. your login will work as u expect it
Change your php file like below :
<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection
header('Content-type: application/json');
$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
$res = "userExist";
$data = json_encode($res);
echo $data;
die();
}
else
{
$res = "fakeUser";
$data = json_encode($res);
echo $data;
die();
}
mysqli_close($con);
?>
And your script :
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success:function(data){
alert(data);
};
});
I have a html file where users can input a value.
I wrote a script in PHP that checks if this value is present in the databse. If it's present it returns
{"active":true}
Now my goals is that when the user inputs their value and submit they will be redirected to a certain page if this active is true. If it's false they should see an error message.
So here's what I've tried with my AJAX call:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
data: data,
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
Here is my HTML:
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="#" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue" />
</form>
For some reason I get an error:
Uncaught ReferenceError: data is not defined
I am new to AJAX and I am not sure if what I am trying is correct.
Any help would be greatly appreciated!
Thanks in advance.
Can you try:
$(".aanmeldenmodal").submit(function(e){
e.preventDefault();
I am updating my answer in whole
<html>
<body>
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="txt1" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue checkform" />
</form>
</body>
</html>
jQuery part is like
$("document").ready(function () {
$("body").on("click", ".checkform", function (e) {
e.preventDefault();
var request = $("#txt1").value;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {request: 'request'},
dataType: 'json',
success: function (data) {
if(data.active==true){
alert("success");
}else{
alert("failure");
}
}
});
});
});
ajax.php should be like this
if(isset($_GET['request'])){
//check for the text
echo json_encode($arr);
}
In api/check.php
You can pass data in json format
$json = json_encode($data);
retrun $json;
You can also not share any data so You can remove data from jQuery.
data:data
Your Jquery look like this:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
I've seen lots of questions on this subject, but none of them seem to address my issue. It all seems pretty straight forward, but I just get a blank array, am I missing something really simple here?
Thanks.
Here is the html / javascript code:
<script type="text/javascript" src="/javascript/jquery.js"></script>
<form enctype="multipart/form-data" action="" id="frmProduct" method="post">
<input type="file" id="pdffile" name="pdffile" size="50" />
<br />
<input id="pdffileupload" type="submit" value="Upload" />
</form>
<script>
$('#pdffileupload').bind('click', function ()
{
var files=document.getElementById('pdffile').files[0];
var fd = new FormData();
fd.append( "pdffile", files);
$.ajax({
url: '/info.php',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function(data) { alert("YES"); },
error: function(data){ alert("NO"); }
});
return false;
});
</script>
& PHP info.php
<?php
var_dump($_FILES);
?>
Changes needed (just check once by trying all my suggestions):-
1.In the same folder put both files (same working directory).
Code changes:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <!-- add jquery library like this -->
<form enctype="multipart/form-data" action="" id="frmProduct" method="post">
<input type="file" id="pdffile" name="pdffile" size="50" />
<br />
<input id="pdffileupload" type="submit" value="Upload" />
</form>
<script>
$('#pdffileupload').bind('click', function ()
{
var files=document.getElementById('pdffile').files[0];
var fd = new FormData();
fd.append( "pdffile", files);
$.ajax({
url: 'info.php', // remove /
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function(data) { alert("YES"); },
error: function(data){ alert("NO"); }
});
return false;
});
</script>
And in php
<?php
print_r($_FILES);
?>
Note:- Check in your browser console (response tab).
You might try this:
<?php print_r($_FILES); ?>
instead of
<?php var_dump($_FILES); ?>
Because the var_dump doesn't work with $_FILES.
I have very very little knowledge of javascript but somehow I managed to post form data to a php file.
Now I am facing a little problem, there are some validations on php file, what I want is if there is any validation fails and the php file returns $error = 'Invalid data'; I want this ajax request to simply display the error message.
Or, if it returns no error, or $error = ''; this ajax request redirect to thankyou.php page.
HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if (data == 'true') {
window.location.href="thankyou.php";
};
if (data !== 'true') {
$("#status").html(data);
};
},
error: function(){
}
});
}));
});
<form id="frmContact" action="" method="post">
<div id="status"></div>
<div>
<label>Email</label>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="demoInputBox">
</div>
<div>
<input type="submit" value="Send" class="btnAction" />
</div>
</form>
data.php
<?php
// PHP code above...
//Lets add $error variable for test purpose...
$error = 'Invalid data';
?>
Change only success function like this
success: function(data){
if (data === 'Invalid data') {
$("#status").html(data);
}
else {
window.location.href="thankyou.php";
}
}
and in php you should echo $error
Echo out "Success" if everything goes according to what you wanted in the posted data i.e all validations passed or echo out any specific validation error. The echoed response will be the response according to which our JS will act accordingly.
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false
})
.done(function(response){
if(response=="Success")
window.location.href="thankyou.php";
else
$("#status").html(response);
});
}));
});