AJAX call display response from php script in html - javascript

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;
});
});

Related

How do I detect submitted button with ajax and php?

I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});

Can't ajax reload without page reloading

I want it to only "reload" into the #searchuserc. I have searched so much information but I can't solve the problem.
$(document).ready(function() {
$("#onlineusers").load("online.php");
$("#searchuserc").show();
setInterval(function() {
$("#onlineusers").load("online.php");
}, 5000);
$(".search").click(function() {
$("#onlineusers").hide();
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'searchuser.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data) {
$('#searchuserc').fadeOut('slow', function() {
$('#searchuserc').fadeIn('slow').html(data);
});
})
.fail(function() {
alert('Ajax Submit Failed ...');
});
});
});
this is my HTML file
<form method="POST">
<input type="text" id="searchuser" name="searchuser" placeholder="Sök efter en användare..." />
<input type="submit" class="search" name="searchbtn" value="Sök" />
</form>
<div id="searchuserc">
</div>
Instead of
$(".search").click(function() {
...
use
$(".search").closest("form").submit(function(e) {
...
Code inside the handler can stay the same.

How to validate data in an AJAX call

I am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});

How to solve this jQuery ajax post method undefine index problem while uploading images?

I want to Upload photos by using Ajax Post method,
Here is my html and javascript code
<script>
$(document).ready(function(){
$('#multiple_upload_form').submit(function(e){
e.preventDefault();
var upload = $('#images').val();
$.ajax({
type:'POST',
url:'album.php',
data:
{
upload : images
},
cache:false,
contentType:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
},
error:function()
{
$('#image_preview').html('error');
}
});
return false;
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="album.php" name="upload_form" id="multiple_upload_form" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="email">Album Name</label>
<input type="text" name="aname" class="form-control" id="aname">
</div>
<div class="form-group">
<label for="file">Upload Photos:</label>
<input type="file" id="images" name="images" />
</div>
<div id="images_preview"></div>
</div>
<center class="feedback" style="display:none">Loading...</center>
<button id="submit" name="submitt" class="btn btn-default">Submit</button>
</form>
and this is my PHP CODING
if(isset($_FILES['images']['name']) )
{
$img = $_FILES['images']['name'];
if(!empty($img))
{
echo 'MaxSteel';
}
}
else
{
echo 'Same Problem';
}
I am having undefine index : images
it works fine with input type="text" but when it comes to "file" type is shows error help me solving this problem
Go through this code, it may help
var data = new FormData();
data.append("Avatar", file.files[0]);
$.ajax({
url: "http://192.168.1.1:2002/,
type: "POST",
data:data,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
Its posible that the file is not upload becouse of some error. You should review the parameters related to file upload as UPLOAD_MAX_SIZE, etc.
You can use var_dump($file) to see the $_FILE content.
You need to be sending your data through FormData().
Try something like this:
var images = $("#images").get(0).files;
var formData = new FormData();
$.each(images, function(i, image) {
data.append("images[]", image);
});
Then send formData as your $.ajax data.

how to get value by .ajax() method in codeigniter and show the value in input field?

sorry for ask this question again , but I still don't slove this problem!!
half years ago , I got some problem about receive value from server , and show the value in input field.
the question is below:
when I click the button "new" , and I can get the max number from ID table.
I write some code for this and try to use AJAX receive and show in input, it's not working,if I open the debug tools in chrome,I will get a error message :"Uncaught ReferenceError: maxnum is not defined "
(when I only use browser to open the page /localhost/index.php/static_data/kungfu_maxquery,I can get correct json and print on screen. )
what else I can do ...... Σ(  ̄□ ̄;)
sorry again , sorry all , I am a construction laborer , don't know too much about program code, I read the book and practice along , please teach me .
View : (views/kungfu.php)
<div class="hero-unit">
<div style="width:250px;float:left;">
<form id="pr_form" action="<?php echo site_url();?>/static_data/kungfu_act" method="post">
ID:<input id="num" name="num" type="text" class="field_set"><br>
NAME:<input id="name" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" name="kungfu" type="text" class="field_set"><br>
</div>
<div style="clear:both;height:50px;padding-top:10px">
<input id="go" name="go" class="btn" type="submit" value="submit">
<input id="query" name="query" class="btn" type="button" value="query">
<input id="newone" name="newone" class="btn" type="button" value="new">
</div>
</form>
</div>
Controller(controllers/static_data.php):
class Static_data extends CI_Controller {
public function kungfu_maxquery()
{
$this->load->model("pr_model");
$data = $this->pr_model->pr_maxquery();
echo json_encode($data);
}
}
Model(models/pr_model.php):
class Pr_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('html');
$this->load->database();
}
function pr_maxquery()
{
$this->db->select_max("num");
$maxquery=$this->db->get("kungfu_table");
return $maxquery;
}
JS(js/try.js):
$("#newone").click(function () {
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
cache: "false",
data: {'num':maxnum},
datatype: "json",
}).done(function () {
$("#num").val(maxnum);
});
});
In the data of the ajax call you are setting the data, not getting!!!
You should use something like this:
$("#newone").click(function () {
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
cache: "false",
datatype: "json",
}).done(function (result) {
$("#num").val(result);
});
});
The function in the done recibe the result of the callback.
you try like this
$("#newone").click(function () {
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
cache: "false",
datatype: "json",
}).done(function (resp) {
var json = $.parseJSON(resp);
$("#num").val(json);
});
});

Categories