Automatic Form Completed With PHP Ajax - php

I have two textboxes namely no_id and customer_name. when the user enters no_id, customer_name is filled in automatically.
Form
<form>
<input type="text" name="no_id" onkeyup="autofill()" id="no_id">
<input type="text" name="customer_name" id="customer_name" readonly>
<!--textbox customer_name is readonly-->
</form>
Javascript
<script type="text/javascript">
function autofill(){
var no_id = $("#no_id").val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
}).success(function (data) {
var json = data,
obj = JSON.parse(json);
$('#customer_name').val(obj.customer_name);
});
}
</script>
ajax.php
include 'conn.php';
$npwp = $_GET['no_id'];
$query = mysqli_query($conn, "select * from ms where no_id='$no_id'");
$ms = mysqli_fetch_array($query);
$data = array(
'customer_name' => $ms['customer_name']);
echo json_encode($data);
The scripts above works for me.
Now I want to modify it.
When the no_id entered is NOT stored in the database, the customer_name box attribute becomes readonly=false, so the user can fill in customer_name box.

you can use jquery onChange method on no_id input to send no_id value and search it's stored in the database or not and return true or false (0 or 1)like this code:
$('#no_id')onchange(function(){
var no_id = $(this).val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
}).success(function (data) {
if(data == true){
$('#customer_name').attr('readonly');
}else if(data == false){
$('#customer_name').removeAttr('readonly');
}
});
});
I prefer to create another function for no_id onChange method

Here I am counting rows in mysql and if rows == 0, then removing readonly attribute
Javascript
<script type="text/javascript">
function autofill(){
var no_id = $("#no_id").val();
$.ajax({
url: 'ajax.php',
data:"no_id="+no_id ,
success : function (data) {
var json = data;
obj = JSON.parse(json);
if(obj.success=='true') {
$('#customer_name').val(obj.customer_name).attr("readonly", true);
} else {
$('#customer_name').val("").attr("readonly", false);
}
}
})
}
</script>
AJAX.php
include 'conn.php';
$npwp = $_GET['no_id'];
$query = mysqli_query($conn, "select * from ms where no_id='$npwp'");
if(mysqli_num_rows($query) >= 1 ) {
$ms = mysqli_fetch_array($query);
$data = array('customer_name' => $ms['customer_name'], 'success'=>'true');
echo json_encode($data);
} else {
$data = array('success'=>'false');
echo json_encode($data);
}

Related

Post more than one parameter to ajax

PHP code :
<?php include_once 'includes/dbconnect.php';
$name = $_POST['name'];
$year = $_POST['year'];
$term= $_POST['term'];
$semester= $_POST['semester'];
$class= $_POST['class'];
$query = "SELECT * FROM hostelfee WHERE RegNo = '$name' AND PayYear='$year' AND PayTerm='$term' AND PaySemester='$semester' AND PayClass='$class' ";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
echo json_encode($row);
}
?>
<script type="text/javascript">
function ch() {
$(document).on('change',function() {
name = $('#name option:selected').val();
year = $('#year').val();
term = $('#term').val();
semester = $('#semester').val();
class = $('#class').val();
$.ajax({
type : 'POST',
dataType: 'json',
data: {name : name,year : year,term:term,semester:semester,class:class},
url:'getBalance.php',
success:function (result) {
$('#Year').val(result['PayYear']);
$('#student-balance').val(result['Balance']);
}
});
});
}
</script>
I have a payment page where I first have to select student No, Year and term, then the balance of that period will be selected.
The challenge is that I can only send one parameter from PHP to ajax. How to use more than one parameter?
you can use serialize.
<script type="text/javascript">
function ch() {
$(document).on('change',function() {
//use serialize to get multiple value of form. Add your form id - #form. you can also use form name, class
form_data = $('#form').serialize();
$.ajax({
type : 'POST',
dataType: 'json',
data: {action : 'hostelfee',formdata : form_data},
url:'getBalance.php',
success:function (result) {
$('#category').val(result['PayYear']);
$('#student-contact').val(result['Balance']);
}
});
});
}
</script>
In getBalance.php file use parse_str to get the serialize data in array.
if($_POST['action'] == 'hostelfee'){
parse_str($_POST['formdata'], $form_data);
//here will get all the parameter like name, year,term,semester and class etc in array.
print_r($form_data);
//add your code here
}

ajax dropdown box when a variable exists

I am trying to make an ajax call for the an dropdown box(dynamic)
when the variable $place is available it will make an ajax call and populate
the dropdown box.
I am trying to pass the variable $place to listplace.php and encode it in json data and get the datalist values but not sure the encoded json file is correct
I just given a try and not sure below code works, please help.
Dropdown box
<select>
<option selected disabled>Please select</option>
</select>
Ajax call
<?php if(isset($_GET['place']) && $_GET['place'] !='') {?>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $place ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
}
});
</script>
<?php } ?>
listplace.php
<?php
$sql = #mysql_query("select placename from employee where placename= '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
Change your AJAX call to the following.
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
And your PHP to
<?php
$place = $_POST['place'];
$sql = #mysqli_query($conn,"select placename from employee where placename= '$place'");
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r['placename'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
var request;
// Abort request is previous doesnt end
if (request) {
request.abort();
}
// Make request
request = $.ajax({
type: "POST",
url: 'listplace.php',
dataType: 'json',
// One option is passed php into script
data: {
department: '<?= $place ?>'
}
// but I prefer this solution
// html markup:
// <div style='display:none;' data-place>YOUR_PLACE</div>
// or hidden input, in final it doesnt matter...
data: {
department: $('[data-place]').text()
}
});
request.done(function(response, textStatus, jqXHR){
// check response status
// HTML Markup:
// <select id='select'></select>
var select = $('#select');
select.empty();
// add default option first one disabled, selected, etc.
// data are rows in your situatios
// append data to select with lodash for example
// _.map(response.rows, function(row){...}
// jQuery each
// $.each(response.rows, function(index,row){...}
})
request.fail(function(){
// do something
})
request.always(function(){
// do something
})
in your .php is missing line
$place = $_POST['department'];

Pass data from ajax to php [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Ajax:
function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
type: "POST",
url: "http://localhost/test/testForm.php",
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}
PHP:
<?php
require_once("Connections/cid.php");
$userId= $_POST['userId'];
$productCode= $_POST['productCode'];
$countryCode= $_POST['countryCode'];
$sql_check = "SELECT * FROM utc WHERE userId = '$userId' AND productCode = '$productCode' AND countryCode = '$countryCode'";
$list = mysqli_query( $conn, $sql_check);
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
else
echo "NOK";
?>
I am very sure that the data i had pass in to the php file are correct. However i cant seem to get my data to the php file and it keep return false value back to me. Anything i can do to make it works?
**Note: Somehow even if i change both result to return true in ajax, it will still return false.
and i tried to change the link to another file with only echo "OK"; but it also doesn't work. So i think it is not the file problem. It just never run the ajax no matter what. Do i need to do any link for ajax to run? **
function check_user_country_prod(userId , countryCode , testType )
{ //using alert to check that all data are correct
$.ajax({
url: "test/testForm.php"
type: "POST",
url: "http://localhost/test/testForm.php", // This needs to be "test/testForm.php"
data: { userId: userId ,
countryCode : countryCode ,
productCode: testType
},
success:function(res) {
if(res == "OK")
return true;
else
return false;
}
});
}
Adjust this code according your input type. I hope this will help you:
$(document).ready(function() {
$("#submit_btn").click(function() {
//get input field values
var user_name = $('input[name=name]').val();
var user_email = $('input[name=email]').val();
var user_phone = $('input[name=phone]').val();
var user_message = $('textarea[name=message]').val();
//simple validation at client's end
//we simply change border color to red if empty field using .css()
var proceed = true;
if(user_name==""){
$('input[name=name]').css('border-color','red');
proceed = false;
}
if(user_email==""){
$('input[name=email]').css('border-color','red');
proceed = false;
}
if(user_phone=="") {
$('input[name=phone]').css('border-color','red');
proceed = false;
}
if(user_message=="") {
$('textarea[name=message]').css('border-color','red');
proceed = false;
}
//everything looks good! proceed...
if(proceed)
{
//data to be sent to server
post_data = {'userName':user_name, 'userEmail':user_email, 'userPhone':user_phone, 'userMessage':user_message};
//Ajax post data to server
$.post('contact_me.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$('#contact_form input').val('');
$('#contact_form textarea').val('');
}
$("#result").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input, #contact_form textarea").keyup(function() {
$("#contact_form input, #contact_form textarea").css('border-color','');
$("#result").slideUp();
}); });
Try this also both are running on my localhost:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function (d) {
alert(d);
}
});
});
});
</script>
<form method="post" id="myform">
<input type="text" name="time" /><br>
<input type="text" name="date" /><br>
<input name="submit" type="submit" value="Submit">
</form>
make new file of post.php and pest this code. This code will alert your input field value:
<?php print_R($_POST); ?>
"my current folder is localhost/abc/bsd.php while the one that i am going is localhost/test/testForm.php".
From the above comment, you have to change the ajax url to
url: "/test/testForm.php",
Apart from this , your php code shows
$num = mysqli_fetch_assoc($list);
if($num >0)
echo "OK";
This is incorrect as mysqli_fetch_assoc returns an associative array of strings. So, the comparison $num >0 is illogical.

PHP Ajax post result not working

I am trying to get a form to work, but when I call ti with ajax, it will not work.
// ----------------------------EDIT----------------------------
I actually found exactly what I was looking for while browsing around.
jQuery Ajax POST example with PHP
I just have one question, would this be the best way to get the data, or could I call it from an array somehow?
post.php
$errors = array(); //Store errors
$form_data = array();
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$_POST['name'])); //Get data
if (!empty($errors)) {
$form_data['success'] = false;
$form_data['errors'] = $errors;
} else {
$form_data['success'] = true;
$form_data['country'] = $query['country'];//Have a bunch of these to get the data.
$form_data['city'] = $query['city'];//Or is there an easier way with an array?
$form_data['zip'] = $query['zip'];
// Etc, etc
}
echo json_encode($form_data);
Then in index.php just call it via:
$('.success').fadeIn(100).append(data.whatever-i-have-in-post);
// ----------------------------v-ORIGINAL-v----------------------------
This is I have so far. At the bottom you can see I have an if statement to check if I could get the results from post, but it always results in "unable to get country" (I'm checking with google.com). I don't know if I am doing it correct or not. Any ideas?
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString
});
}
return false;
});
});
</script>
<form id="form" method="post" name="form" style="text-align: center;">
<input id="name" name="name" type="text">
<input class="submit" type="submit" value="Submit">
<span class="error" style="display:none">Input Empty</span>
<?php
include_once('post.php');
if($query && $query['status'] == 'success') {
$query['country'];
} else {
echo 'Unable to get country';
}
?>
</form>
Post.php
$ip = $_POST['name'];
//$ip = isset($_POST['name']); // I dont know if this makes a difference
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
Try with this after changing the dataString = {name: name}
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(response) {
// Grab response from post.php
}
});
}
return false;
});
The best way i like to grab the JSON data from ajax request. You can do it by slightly changes in your script.
PHP File
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
echo json_encode(array('status'=>true, 'result'=>$query)); // convert in JSON Data
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
dataType: 'json', // Define DataType
success: function(response) {
if( response.status === true ) {
// Grab Country
// response.data.country
// And disply anywhere with JQuery
}
}
});
}
return false;
});

how to return an array in AJAX call in php

I have a form that has a select option , So I am trying to update the form/table with some content from database when I select a type in the select option ,
SO for that I did an ajax call something like this.
$("#selectPlantilla").on("change",function(){
var descripcion = $(this).val();
//alert(descripcion);
var url="http://index.php";
var posting = $.post(url, {
im_descripcion: descripcion,
}).done(function (data) {
alert(data);
});
});
And then I validated the call in php on the same inde.php page like this
if(isset($_POST['im_descripcion']))
{
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
$result = mysql_fetch_array($result);
print_r($result);
}
The problem I am facing is in the alert window it return the whole page instead of just the $result that I have printed , So can any one help me out how I can channelize it properly , I have use the values from the array $result to update in the form using JQuery .
Thanks in Advance
For returning PHP array data in Ajax, JSON will make your life the simplest.
$result = mysql_fetch_array($result);
echo(json_encode($result));
This will return the array in a format that is easily usable by JavaScript. Try this to see its content:
alert(JSON.stringify(data));
With JSON, you should be able to fetch data or iterate through it in JavaScript
Try this
In Javascript
<script type="text/javascript">
var $ =jQuery.noConflict();
$(document).ready(function(){
$('.dropdown_class').on('change', function() {
var m_val = this.value;
var datastring = "im_descripcion="+m_val;
$.ajax({
type: "POST",
url: "lunchbox_planner.php",
data: datastring,
cache: false,
success: function(result) {
var v = $.parseJSON(result);
var l = v.length;
for(var i=0;i<l;i++){
var sh_d = "<div class='coco3'>"+v[i]+"</div>";
$('.mon_tea').append(sh_d);
}
}
});
});
});
</script>
<div class="mon_tea">
In PHP
<?php
if(isset($_POST['im_descripcion'])) {
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
while($row_sh = mysql_fetch_array($result)){
$all_incr[] = $row_sh['col_name'];
}
echo json_encode($all_incr);
}
?>

Categories