I'm trying to populate form fields using an AJAX call to a php script which returns JSON data. I've tried two methods but neither work and I'm pretty sure I'm missing something entirely... I've never used AJAX before and I'm finding it confusing.
$("#loadDefault").click(function()
{
$.getJSON('formdata.php', {act : 'default'},
function(data) {
$.each(data, function(key, value) {
$('[name='+key+']', frm).val(value);
})
});
/* function populate(frm, data) {
$.each(data, function(key, value) {
$('[name='+key+']', frm).val(value);
});
}
populate('#myForm', $.parseJSON(data)); */
return false;
});
Here is the HTML form for reference: __________________________________________________
<form id="myForm">
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>
<a id="loadDefault" href="">Load Default Data</a>
<br>
Note: I'm not looking for someone to write the solution for me, I'm just hoping for some guidance or some idea as to what I'm missing or doing incorrectly. Thanks!
Your frm is not defined.
Also frm doesn't need to be in $('[name='+key+']', frm).val(value); cause you only need to updated the field values.
I know you didn't want me to write the solution, but it's just your approach is correct. It's just small details you've missed.
Basically, if your response is like {'name': 'foo', 'postal': 'bar'}, the js should work.
Maybe you could take a look at this view engine: https://jocapc.github.io/jquery-view-engine/ It enables you to load JSON object from the AJAX response directly into the form if properties of the object match elements of the form. You code would look like:
$("#loadDefault").click(function()
{
$.getJSON('formdata.php', {act : 'default', dataType: 'json'},
function(data) {
$('#myForm').view(data);
});
return false;
});
Related
Good day..
i have modal and inside the modal i have div class
<div id="user-details-content" class="modal-body">
...
</div>
i supply the content inside that modal using ajax.
this is the supplied content:
<div id="hidden" class="hidden">
<input type="hidden" name="id" class="id" id="id" value="1">
<input type="hidden" value="email#email.com" class="email">
</div>
Now i try to get that input type="hidden" using this ajax
var id = $(this).parents('#user-details-content').find('.id').val();
but it returns undefined in my console.log
any suggestions ? on how to get that input type="hidden" and the value ?
EDIT - This is my ajax function
function inquiryId(){
var id = $(this).parents('#user-details-content').find('.id').val();
console.log(id);
$.ajax({
url: 'php_file.php',
type: 'POST',
data: { id: id,
},
dataType: 'json',
success: function(result){
console.log(result);
}
});
}
the problem may occurs because you loaded the html after the DOM loaded.
i guess you have kind of event listener right ?
A workaround could be doing something like :
$(document).on('some_event', '#your_css_selector', function(e){
// do your stuff here
});
Just want to get the input type=hidden value?
JQuery can get the value no matter it's hidden or show.
$('#id').val();
$('.email').val();
this is ok.
From the line of code:
var id = $(this).parents('#user-details-content').find('.id').val();
If you know the exact id and the class attributes of the input[type="hidden"], may I suggest using $("#id").val() and $(".email").val(). Below is a snippet to demonstrate my suggestion, hope it helps.
$(function(){
$("button").click(function(event) {
buttonSubmit_OnClick();
});
});
function buttonSubmit_OnClick() {
var message;
message = "Hello " + $("#id").val() + "! ";
message += $(".email").val();
$("p").html($("p").html() + "<br>" + message);
/* $.ajax() code-block goes here */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden" class="hidden">
<input type="hidden" name="id" class="id" id="id" value="1">
<input type="hidden" value="email#email.com" class="email">
<button>Click me!</button><!-- this is for demo! -->
</div>
<p></p><!-- this is for demo! -->
As a side note:
For better client-side code optimization:
$(this) is powerful, but also a wild-card. jQuery is always updating the this, so, this may not always be what you expect it to be. Best be used only when you really have to, when you do, store its reference in a variable. Remember, with great power, comes great responsibility.
ID-Based Selectors are much faster because they handled by using document.getElementById() which is native to the browser instead of going through jQuery's sizzle selection engine.
Being specific if possible. Avoid universal selectors such as .children() or .parents().
Here is a more eloquent read on optimizing jQuery selectors.
Ok, so I have the following form in a jQuery overlay:
<div class="profile_about_edit_container" id="profile_about_edit_container">
<form id="profile_edit_form" name="profile_edit_form" method="post" action="validation.php">
<label>First Name:</label>
<input type="text" name="firstname" maxlength="50" size="30">
<label>Last Name:</label>
<input type="text" name="lastname" maxlength="50" size="30">
<button type="submit" class="save">Save</button>
<button class="close">Cancel</button>
</form>
</div>
This is displayed using an <a> with class="profile_popups_form" and the following Javascript:
$(document).ready(function() {
$(".profile_popups_form").overlay({
});
});
This shows correctly, and validation.php then echo's an array of error messages like so:
if (count($errors) > 0) {
echo json_encode($errors);
}
But now I'm trying to use jQuery client & server validation on this form.
I tried this:
$(document).ready(function(){
var form = $("#profile_edit_form");
$("#profile_edit_form").submit(function(e) {
e.preventDefault();
var input = $("#profile_edit_form").validator();
$.getJSON(form.attr("action") + "?" + form.serialize(), function(json) {
if (json !== '') {
input.data("validator").invalidate(json);
}
else
$('#profile_edit_form').unbind('submit').submit();
});
});
With the objective of submitting the form and displaying this array of error messages in the normal way jQuery Tools Validation does. But I'm having no luck.
Am I approaching this right? If so, what am I doing wrong? I'm not sure if it's the Javascript causing the issue, or if I'm approaching this right logically. I can find literally no resources explaining how to use JQuery Tools Validation with PHP successfully.
Currently the array is just displayed on the screen as if you echo'd text.
I used the following resource to get the code for returning the array:
http://www.abdullahyahya.com/2012/06/20/javascript-client-side-form-validation-using-server-side-form-validation/
Try doing an ajax request to a php file and get back the response from server. The client side can be done with various ways; from HTML5 tags to plain regex
data = $(this).serializeArray();
//we serialized the data of the form and then we do the ajax request
$.ajax({
url: 'validate.php',
type: 'post',
data: data,
dataType : 'json',
success: function (dat) {
if(dat.error==0){
//dat.error is my returned error from the php file
}else{
//handle the errors
}
}
},
error: function(){
//that's if something is wrong with sent data
alert('failure');
}
});
I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts....
It would be great help if some one helps me out with this
index.html
<script type="text/javascript">
$(document).ready(function(){
$("#submit_btn").click(function() {
$.ajax({
url: 'count.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data');
}
})
});
</script>
</head>
<form name="contact" id="form" method="post" action="">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
In count.php i want to implement
<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);
$output=$FNO+$SNO;
echo $output;
?>
(i want to display output in count.php page not in the first page index.html)
Thanks for your help in advance.
You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:
$('#form').submit(function() {
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
alert(data); //check to show that the calculation was successful
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.
I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:
$("#submit_btn").click(function() {
$("#form").submit();
});
I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.
Index.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
<label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
<!-- The following div will use to display data from server -->
<div id="result"></div>
</body>
<script>
/* attach a submit handler to the form */
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
//Get the first value
value1 = $form.find( 'input[name="SNO"]' ).val(),
//get second value
value2 = $form.find( 'input[name="FNO"]' ).val(),
//get the url. action="count.php"
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { SNO: value1, FNO: value2 } );
/* Put the results in a div */
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
});
</script>
</html>
count.php
<?php
$FNO = $_POST['FNO'];
$SNO= $_POST['SNO'];
$output = $FNO + $SNO;
echo $output;
?>
There are a few things wrong with your code; from details to actual errors.
If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.
Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").on("submit", function () {
$.post("/count.php", $(this).serialize(), function (data) {
alert(data);
}, "text");
return false;
});
});
</script>
As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.
<form method="post" action="/count.php" id="form">
<label for="number1">Enter First no:</label>
<input type="number" name="number1" id="number1">
<label for="number2">Enter Second no:</label>
<input type="number" name="number2" id="number2">
<input type="submit" value="Calculate">
</form>
The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.
Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.
<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
echo 'Error';
} else {
echo ($number1 + $number2);
}
Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).
You can do like below to pass form data in ajax call.
var formData = $('#client-form').serialize();
$.ajax({
url: 'www.xyz.com/index.php?' + formData,
type: 'POST',
data:{
},
success: function(data){},
error: function(data){},
})
I'm trying to build a nice contact form, from where a user can send an e-mail. I have 3 input fields (1. name, 2. e-mail address, 3. telephone number).
<p>
<label for="name"><?php echo $label_name; ?></label>
<input type="text" name="name" id="name" size="30" />
</p>
<p>
<label for="email"><?php echo $label_email; ?></label>
<input type="text" name="email" id="email" size="30" />
</p>
<p>
<label for="tel"><?php echo $label_tel; ?></label>
<input type="text" name="tel" id="tel" size="30" />
</p>
The styling of the fields is made with the following JQUERY script:
$(document).ready(function() {
$('input[type="text"]').addClass("idle");
$('input[type="text"]').focus(function() {
$(this).removeClass("idle").addClass("focus");
this.select();
});
$('input[type="text"]').blur(function() {
$(this).removeClass("focus").addClass("idle");
});
});
Basically what I want is to style the fields with RED border, if the server would return false (using AJAX and PHP). For this, I searched the net and tried to implement a few scripts, but none worked. Here's what I tried:
$(document).ready(function() {
$('input[type="text"]').blur(function() {
$.ajax({url:"php/verify_field.php", success:function(result){
$(this).removeClass("idle").addClass(result);
}});
});
});
Thank you all for answering!
The reply of Omid Amraei seems to suit my project so far. But could we add some spice to all this script: I would like to transmit 2 parameters with the Jquery-Ajax script to the server-side PHP file:
the ID of the text input
the value of the text input.
All this with POST method!
This way I could parse the information in the PHP file using $_POST method and check first the ID, then run the verification criteria on the value of the input.
Many thanks for all!
Happy Saturday :)
Because using this in Ajax callback does not point to your input, so try this :
$(document).ready(function() {
$('input[type="text"]').blur(function() {
var $input = $(this);
$.ajax({url:"php/verify_field.php", success:function(result){
$input.removeClass("idle").addClass(result);
}});
});
});
this in this case isn't the textbox it's the ajax jquery object
Change the context to this.
$('input[type="text"]').blur(function() {
$.ajax({
url:"php/verify_field.php",
context: this
success:function(result){
$(this).removeClass("idle").addClass(result);
}});
});
docs:
contextObject
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).
I have a form that is called via the fancybox plugin login example.
Here is the code I have:
Form:
<form method="post" action="" id="events_form">
<p class="clearfix"><label for="Name">Name:</label> <input type="text" name="Name" id="Name" /></p>
<p class="clearfix"><label for="Company">Company:</label> <input type="text" name="Company" id="Company" /></p>
<p class="clearfix"><label for="Email">Email:</label> <input type="text" name="Email" id="Email" /></p>
<p class="clearfix"><label for="Tel">Tel:</label> <input type="text" name="Tel" id="Tel"/></p>
<p class="clearfix"><input type="submit" value="Submit details" /></p>
</form>
JavaScript / jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#event_trigger").fancybox({
'padding' : 0,
'scrolling' : 'no',
'titleShow' : false,
});
$("#events_form").bind("submit", function() {
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "/events/index.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
});
</script>
The PHP file returns and empty array. However the Firebug post tab displays the form data.
Also, I noticed that if I do
print_r($_SERVER['REQUEST_METHOD'])
This returns GET, even though I have specified POST.
$(this).serializeArray()
with the name of the form CSS id (#my-form-ID, in this example) like this:
$("#my-form-ID").serializeArray()
Hope that solves it. It worked for me. ;-D
$.ajax expects the parameter data to be an object or a string.
http://api.jquery.com/jQuery.ajax/ scroll down to data.
If you wrap your data in an object e.g. data: {array:$(this).serializeArray()} it may work. I'm not 100% sure on that though.
You are doing an AJAX request on a form submit.
Unless the AJAX request is synchronous (which I wouldn't recommend, anyway) there is a danger that your form will be submitted before there is any chance for the AJAX request will return.
In the line:
$(this).serializeArray()
$(this) is referring to the the form element you have selected in the bind method. I'm assuming this is intended