Update text field border using Jquery and Ajax - php

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).

Related

How to make jquery serialize ignores an input field in a div that toggles between hide and show

I have a form where one of the controls(inside a div) has a display of none. When a user checks a particular radio button the hidden div will display which contains an input element allowing him to enter some input.
When I tested it with PHP (using isset() function), I realized that the input variable is set, even if it's parent(div with id of details) is not shown.
What I want however is that serialize should only send the variable to the server when the div containing the input field is displayed. If I however gives display of none to the input element directly, it works as I want. But I want it to be on the div because some controls like labels and many other possible input fields need to also be hidden. One quick solution will be to give all the controls or elements in the div a class and toggles their display using the radio buttons, but I rather prefer the class to be on the div wrapping them all.
HTML:
<form id="form">
<div class="form-group">
<label for="firstname">First Name</label>
<input type="firstname" class="form-control" name="firstname" autofocus placeholder="First Name">
</div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="surname" class="form-control" name="surname" placeholder="Surname">
</div>
<label>1. Do you program?: </label>
<label class="radio-inline">
<input type="radio" name="one" value="Yes"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="one" value="No" checked> No
</label>
<div class="form-group" id="details" style="display:none;">
<label class="control-label">State your Languages</label>
<input type="text" name="language" class="form-control" autofocus>
</div>
<div class="form-group">
<button id="submit" class="btn btn-primary">Submit</button>
</div>
</form>
JavaScript
$(function(){
$('#form input[name=one]').change(function(event) {
$('#details').toggle();
});
$('#submit').on('click', function(event) {
event.preventDefault();
var form = $('#form');
$.ajax({
url: 'process.php',
type: 'POST',
dataType: 'html',
data: form.serialize()
})
.done(function(html) {
console.log(html);
})
.fail(function() {
console.log("error");
})
});
});
PHP
if(isset($_POST['language'])) {
echo 'Language is set';
} else {
echo 'Not set';
}
The PHP reports 'Language is set' even if the div containing the input with name of language is given display of none;
disabled input elements are ignored by $.serialize()
<input type="hidden" name="not_gonna_submit" disabled="disabled" value="invisible" />
To Temporarily enable them.
var myform = $('#myform');
// Find disabled inputs, and remove the "disabled" attribute
var disabled = myform.find(':input:disabled').removeAttr('disabled');
// serialize the form
var serialized = myform.serialize();
// re-disabled the set of inputs that you previously enabled
disabled.attr('disabled','disabled');
OR
You could insert input fields with no "name" attribute:
<input type="text" id="in-between" />
Or you could simply remove them once the form is submitted (in jquery):
$("form").submit(function() {
$(this).children('#in-between').remove();
});
Instead going for complex workaround in JavaScript, you could accomplish it in PHP easy way. Check if the radio button Yes is selected and if it is selected, you can do other processing based on that.
if(isset($_POST['one']) && $_POST['one'] === 'Yes') {
if(!empty($_POST['language'])) {
echo $_POST['language'];
} else {
echo "Language is given empty!";
}
} else {
echo 'Language is not selected!';
}
The PHP code above is a simple workaround. You could go for that. If you're only looking to do that in JavaScript itself, I would direct you to the answer given by Bilal. He has some workaround with JavaScript.
EDIT
I've come up with my own simple workaround in JavaScript. Hope it could help you.
<script>
$(function() {
var details = $('#details');
$('#details').remove();
$('#form input[name=one]').click(function() {
if(this.value === 'Yes') {
details.insertBefore($('#form div.form-group:last-of-type'));
details.show();
} else {
$('#details').remove();
}
});
});
</script>
Storing the reference to div of id details in a variable before removing the details div from the DOM.
Based on the value selected in the radio button, the details div will be added to the DOM and displayed or removed from the DOM in case No is selected.
Hope it helps!

Populating form using AJAX call and JSON data

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

how to Get the value of input type hidden in modal using ajax

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.

How to make button to post data with jQuery

Using Google and this site, I've made a simple form to send data with jQuery.
My HTML code:
ADD
<div class="area"></div>
And jQuery:
function AddPoke(id, action){
var response = $('#dle-poke').val()
$.post(dle_root + 'engine/ajax/poke.php', {id: id, text: response, action: action},
function(data){
if (data == 'ok') {DLEalert(dle_p_send_ok, dle_info);}
else {DLEalert(data, dle_info);}
});
$('.area').append("<div id='dlepopup'><textarea name='dle-poke' id='dle-poke'></textarea></div>");
$("#dlepopup").slideDown(700);
};
The problem is that I don't know how to make a send or submit button to post this data! I am very inexperienced with jQuery and I would appreciate any help!
HTML CODE:
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
<a href="javascript:void(0);" onclick="javascript:submit_value();" >Add </a>
Javascript Code:
<script>
function submit_value()
{
alert($('#first_name').val());
alert($('#last_name').val());
}
</script>
When you have enter any text in textfields then click on ADD link to display the alert message here display the text as you have write in textfileds.
Note: Please include the latest jQuery file in head tag.

Cannot access data from jQuery Ajax request, returns empty array

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

Categories