How to use ajax to load default values into form - javascript

<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 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>
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
How would I use the default values array and load the default values when I click insert default data using ajax? I created a click fucntion for insertdefault but am stuck there.

Here are two ways of doing that using the response of the ajax in json or set default values with the link.
$(document).ready(function(){
$('#InsertDefault').click(function(){
$('#name').val('Jane');
$('#postal').val('L5B4G6');
$('#phone').val('9055751212');
$('#address').val('135 Fennel Street');
});
});
Or:
$(document).ready(function(){
var jsonObjFromAjax = {
"name":"Jane",
"postal":"L5B4G6",
"phone":"9055751212",
"address":"135 Fennel Street"
};
$('#name').val(jsonObjFromAjax.name);
$('#postal').val(jsonObjFromAjax.postal);
$('#phone').val(jsonObjFromAjax.phone);
$('#address').val(jsonObjFromAjax.address);
});
Hope that helps!

The script prints the form and the data when requested, you would need to print only the data when requested, with an if, or a separate file.
And for the AJAX part, if you have no problem using jQuery:
$.getJSON("your-file.php?act=default", function (data) {
$.each(data, function (key, val) {
$("#"+key).val(val);
});
});

First generally you load default values if they exist with PHP
<input type = "text" value="<?php if (isset($var)){ echo $var ; } else { echo ''; }">
If you want to load them with JS(jquery)
$("input").each(function(i,v){
var name = $(this).attr('name');
for(i=0; i < result.length; i++) {
if ( result[i]['name'] == name ){
$(this).val(name);
break;
}
}
});
Untested of the top of my head

Related

Return mysql fetch data and insert into form field value

i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});

$.post variables not passing to php getting undefined index error

This code almost works, it inserts into the db and it is giving feedback on the page to say it has updated. However I am getting undefined index between lines 5-8 in the insert_message.php and my database is filling with blank entries (except the date).
Apologies for being new to jquery and AJAX. Need some help.
form
<form enctype='multipart/form-data' action='insert_message.php' method='POST' id='contact_form'>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='email'>Email:</label>
<input class='form-control' type='email' id='email' name='email' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='subject'>Subject:</label>
<input class='form-control' type='text' id='subject' name='subject' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="form-group">
<label for='message'>Message:</label>
<textarea class="form-control" placeholder="Message" id='message' required="required"></textarea>
</div>
<input type="hidden" name="reciever" id='receiver' value="Admin">
<input class='btn btn-primary' id='submit' type='submit' value='submit' >
</form>
<span id="result"></span>
jquery
<script>
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
var message1 = $('message').val();
var sender1 = $('sender').val();
var receiver1 = $('receiver').val();
var subject1 = $('subject').val();
$.post("insert_message.php", {message:message1, sender:sender1, receiver:receiver1, subject:subject1}, function(info) { $("#result").html(info);
});
clearInput();
});
$("#contact_form").submit( function() {
return false;
});
function clearInput() {
$("#contact_form :input").each( function() {
$(this).val('');
});
}
});
</script>
insert_message.php
<?php
include("connections/conn.php");
$getsubject = mysqli_escape_string($conn,$_POST["subject1"]);
$getmessage = mysqli_escape_string($conn,$_POST["message1"]);
$getsender = mysqli_escape_string($conn,$_POST["sender1"]);
$getreceiver = mysqli_escape_string($conn,$_POST["receiver1"]);
$date = date("Y-m-d");
$insertmessage = "INSERT INTO messages (id,subject,message,date,sender,receiver) VALUES (NULL,'$getsubject','$getmessage','$date','$getsender','$getreceiver')";
$insert = mysqli_query($conn, $insertmessage) ;
if($insert){
echo "Message Sent";
}else{
echo "Message did not send";
}
UPDATE
attempted alternative way but I still get the undefined index in the inser_message.php
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
$.ajax({
url: "insert_message.php",
type: "POST",
data: $("#contact_form").serialize(),
success: function(result){
$("#result").html(result);
}
});
});
});
You have several problems in both JS and PHP.
Adjust typo in input hidden where actually name="reciever" instead of name="receiver";
In your $("#submit").click() function you're trying to selecting elements with an invalid selector (e.g. $('message').val() instead of $("#message").val());
Adjust $_POST keys by removing 1 at end. If you have any doubt, print the whole array print_r($_POST);
This is not an error but a suggestion. Since you require conn.php to do your job, I would use require instead of include.
Remove the $conn and the 1's from your 'get' block and, for example:
$getsubject = mysqli_escape_string($_POST["subject"]);
$getmessage = mysqli_escape_string($_POST["message"]);
$getsender = mysqli_escape_string($_POST["sender"]);
$getreceiver = mysqli_escape_string($_POST["receiver"]);

Using php and javascript to put random number in txt file

I have a text input field with a button that generates a random number between 1 and 20 and displays within the text field. The problem I am having, is taking that random number that it generates and saving it into a .txt file. The file chat.txt is stored in the same directory as the rest of these files. Not sure I am going about this the right way. The following is the code. Any ideas would be helpful.
chat.php:
<div id="pageWrap">
<form action="roll.php" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<button type="button" name="button" onclick="myFunction()">Roll</button>
<script>
function myFunction()
{
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
}
</script>
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
roll.php:
<?php
if(isset($_POST['button']))
{
$roll = $_POST['roll'];
$file = fopen("chat.txt");
fwrite($file,$roll);
fclose($file);
print_r(error_get_last());
}
?>
If you are interested in your way of generating random number on client end with javascript:
on html:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="pageWrap">
<form action="page.php" id="rollBox" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<button type="submit" name="submit" >Roll</button>
<script>
$(document).ready(function () {
$('#rollBox').submit(function(e) {
var x=document.getElementById("demo");
x.value=Math.floor((Math.random()*20)+1);
e.preventDefault();
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {}
});
return false;
});
});
function myFunction()
{
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
document.getElementById("rollBox").submit();
}
</script>
</form>
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
on php change this
<?php
if(isset($_POST['submit']))//on submit
{
//echo 'here';
$roll = $_POST['roll'];
$file = fopen("chat.txt","w");//no mode selected
fwrite($file,$roll);
fclose($file);
print_r(error_get_last());
}
?>
This works and generates the chat.txt
The random number is only generated on the client side: you're not sending it to the server yet. You're starting a form (name=rollbox), which you not sending back to the server (also you seem to be missing a </form>. Either submit the form, or use AJAX to send the information to the back-end.
Why don't you just generate the random number in PHP, and then put it in the file with file_put_contents()like this?
<?php
$roll = rand(1,20);
file_put_contents("chat.txt",$roll);
?>
You have some issues with the HTML of your top FORM.
Try replace it with the following code:
<form action="roll.php" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<input type="submit" name="button" onclick="myFunction();" value="Roll">
</form>

mysql_num_rows returned with ajax

i need to pass two dates to a mysql query through ajax.
i have two date inputs.
this is the index.php that has the input
<div id="input">
<td><input type="date" name="date_start"></td>
<td><input type="date" name="date_end"></td>
<input type="button" class="button" value="Get Value">
</div>
<div id="count_display">
</div>
this is the getresult.php file that has the working query
$date_start=$_GET['date_start'];
$date_end=$_GET['date_end'];
$select="select * from tblreport where (date(date_added) between '$date_start' AND '$date_end');";
$res = mysql_query($select);
$rec_count = mysql_num_rows($res);
echo "There are <font color='red' size='3'>".$rec_count."</font> matching records found.";
i want to display the resulting echo from the getresult.php inside the <div id="count_display"> in the index.php file through an ajax method which will display the result in real time without refreshing/reloading the page.
the result will be very similar to this example on this page: http://www.w3schools.com/php/php_ajax_database.asp but all i need is the count of rows returned by the query.
You can do it easily using jquery. Here is your code
<script src="js/jquery-1.6.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".button").click(function()
{
var date_start = $("#date_start").val();
if($("#date_start").val()=='') date_start="";
var date_end = $("#date_end").val();
if($("#date_end").val()=='') date_end="";
var dataString = 'date_start='+ date_start + '&date_end=' + date_end;
$.ajax({
type: "POST",
url: "getresult.php",
data: dataString,
success: function(msg){
$('#count_display').html(msg);
}
}); //END $.ajax
});
});
</script>
<div id="input">
<td><input type="date" name="date_start" id="date_start"></td>
<td><input type="date" name="date_end" id="date_end"></td>
<input type="button" class="button" value="Get Value">
</div>
<div id="count_display">
</div>
Try this:
<script language='javascript'>
$(document).ready(function() {
$.get('getresult.php')
.success(function(result) {
var data = $.parseJSON(result);
var div = document.getElementById("count_display");
div.innerHTML = data.message;
});
});
</script>
Note, you need to include the current jquery api from jquery.com.
In PHP:
$message = "There are <font color='red' size='3'>".$rec_count."</font> matching records found.";
echo json_encode( array( "message"=>$message ) );

GET or import $var as input value to Form after the page is loaded - onClick Button?

I have a FORM with 2 input fields $first_name and $last_name.
<?
$first_name = get_post_meta($post->ID, 'fname', true);
$last_name = get_post_meta($post->ID, 'lname', true);
$fname_tmp = 'Foo' ; // First Name TEMP
$lname_tmp = 'Bar' ; // Last Name TEMP
?>
<input type="text" value="<? echo $first_name;?>" name="first_name" />
<input type="text" value="<? echo $last_name;?>" name="last_name" />
I want to add a onClick "GET/IMPORT" Button/function in this form. So if a user press this button then inputs field first_name should show Foo and last_name should show Bar
How can I do this? Using PHP?
Many thanks in advance.
I try it. it work. Here is your code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".buttonclass").click(function()
{
var fname_tmp = $("#fname_tmp").val();
if($("#fname_tmp").val()=='') fname_tmp="";
var last_name = $("#lname_tmp").val();
if($("#lname_tmp").val()=='') last_name="";
document.getElementById('first_name').value=fname_tmp;
document.getElementById('last_name').value=last_name;
});
});
</script>
<?php
//$first_name = get_post_meta($post->ID, 'fname', true);
//$last_name = get_post_meta($post->ID, 'lname', true);
$fname_tmp = 'Foo' ; // First Name TEMP
$lname_tmp = 'Bar' ; // Last Name TEMP
?>
<input type="hidden" name="fname_tmp" id="fname_tmp" value="Foo"/>
<input type="hidden" name="lname_tmp" id="lname_tmp" value="Bar"/>
<input type="text" value="<?php echo $first_name;?>" name="first_name" id="first_name"/>
<input type="text" value="<?php echo $last_name;?>" name="last_name" id="last_name"/>
<input type="button" name="mybutton" id="mybutton" value="Click Me" class="buttonclass" />
Have a .php file which will respond to the onclick event triggered in the form.
<?php
$result['fname'] = 'FOO';
$result['lname'] = 'Bar';
echo json_encode($result);
?>
Write a jQuery function to trigger the event and receive response from php
You can add this javascript code anywhere in your page, but between your is recommended.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.button').click(function() {
$.get('/path-to-php-file', function(data) {
result = $.parseJSON(data);
$("input[name='first_name']").val(result.fname);
$("input[name='last_name']").val(result.lname);
});
});
});
</script>
Create a button in your form
<input class="button" type="button" value="Get/Import" />

Categories

Resources