You know jQuery.data() can be very useful, but can I use this in a form and to check it directly with PHP? Like $_POST['inputValue'] but $_POST['dataAttribute'] ? Or even to set it with PHP ?
One thing I seem to see a lot of PHP developers forgetting is that PHP is a server language and can't really do much interaction with the client without the assistance of a client side language like Javascript.
You should be able to generate the data-* attributes on the server side with DOMDocument operations, or even by string concatenation if you're that old-fashioned. If you use the DOMDocument approach modifying the values should also be pretty easy while you're in the process of building your DOM tree.
$doc = new DOMDocument ();
$elem = $doc -> createElement ('input');
$doc -> appendChild ($elem);
$elem -> setAttribute ('data-foo', '123');
// etc
As soon as you transform the DOM model to text for sending to the browser, any subsequent modifications become meaningless because they won't be reflected in the browser.
If you need changes made client-side to be known to the server, then you'll need to do some javascript in the client to collect all the data-values, serialise them and post them to the server.
In order to past data values you can create hidden variables in the form with all data attributes you want before the submit event.
Html:
<div id="element" data-myattr="any_data_value"></div>
<form ...>
</form>
jQuery:
<script>
$(function() {
$("form:first").submit(function() {
// any validation
var v = $("#element").data("myattr");
$("form:first").append('<input type="hidden" name="data_myattr" value="' + v +'">');
return true;
});
});
</script>
Rendering data attributes using PHP:
<?php
$myattrvalue= $_POST['data_myattr'];
?>
<div id="element" data-myattr="<?php echo $myattrvalue; ?>"></div>
Hmmph. I've been working at this for 1+ hrs amid other things. Now there are other, very good answers.
Still, fwiw, here's another:
Here is an example where a div is hidden initially, and a data- attribute is used to decide whether the div should be revealed.
AJAX is used to communicate with a back-end PHP file that just spits out "yes" (if the field value is still "no", but otherwise spits nothing).
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
var ax, dd, kk=0;
dd = $('#hid').data('lnreq');
if (dd=="no") $('#lnDIV').hide();
$('#fname').keyup(function() {
if (kk < 4){
dd = $('#hid').data('lnreq');
$.ajax({
type: "POST",
url: "myprocessor.php",
data: "ddVar=" + dd,
success: function(recd) {
//alert(recd);
$('#hid').data('lnreq', recd);
if ($('#hid').data('lnreq') == 'yes') {
$('#lnDIV').show();
}
}
});
kk++; //Do only a few times
}
});
}); //END $(document).ready()
</script>
</head>
<body>
<form id="myForm" action="" method="POST">
First Name: <input id="fname" name="fname" type="text" /><br />
<div id="lnDIV">
Last Name: <input id="lname" name="lname" type="text" />
</div>
<input id="hid" type="hidden" data-lnreq="no" />
</form>
</body>
</html>
PHP SIDE: myprocessor.php
<?php
$rr = $_POST['ddVar'];
if ($rr == "no") echo 'yes';
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.
I would like to compact all data from a huge HTML-form with over a 1000 variables to circumvent the max_input_vars limit in PHP versions before 5.3.9.
How can I read all data in the HTML-form with javascript, serialize it (or create json) to put it all in only one hidden field that contains the whole data then?
On the receiving side I would uncompress it with PHP (for example with json_decode)
Just sent a ajax post?
form.html with javascript
<form action="process.php" method="post" id="form">
<input type="text" name="name">
<input type="text" name="username">
<button type="submit" id="sendForm">Send</button>
</form>
<!-- YOUR JAVASCRIPT -->
<script type="text/javacript">
$('#sendForm').click(function() {
$.ajax({
type: 'POST',
url: $('#form').attr('action'),
data: $('#form').serialize(),
success: function(data) {
// WHATEVER YOU WANT HERE
}
});
return false;
});
</script>
process.php
<?php
$name = $_POST['name'];
// other form fields here
}
Serialize it using JQuery. You can then parse the URL string using PHP.
perhaps serialize and JSON.stringify may work together, though I have not tried it.
I created a script that does the job on all post forms automatically:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
// this disables all form elements and creates only one new element that contains all data serialized
$('form[method="post"]').submit(function() {
var num_form_elements=$(this).find('input, select, textarea').not('[type="submit"]').length;
var num_elements_already_disabled=$(this).find('input:disabled, select:disabled, textarea:disabled').length;
enabled=(num_form_elements-num_elements_already_disabled);
if($('textarea[name="serialized_data"]', this).length > 0) {
alert("Backbutton is not supported yet!");
return false;
}
if($('textarea[name="serialized_data"]', this).length > 0 || enabled<=0) {
alert("Reload of the form is not supported yet!");
return false;
}
var data=$(this).serialize();
$(this).find('input, select, textarea').not('[type="submit"]').attr("disabled", true);
$(this).append(' <input type="hidden" name="num_form_elements" value="'+num_form_elements+'">');
$(this).append(' <input type="hidden" name="num_elements_already_disabled" value="'+num_elements_already_disabled+'">');
$(this).append(' <textarea style="display:true" name="serialized_data">'+(data)+'</textarea>');
// maybe in the textarea I have to .replace(/</g,'<') ?
});
</script>
On the receiving side you cannot use the PHP parse_str() function because the max_input_vars directive affects this function too, so you need something else: I took my_parse_str() from https://gist.github.com/rubo77/6821632
<?php
$params=my_parse_str($_REQUEST['serialized_data']);
echo count($params,1)." serialized variables:<br>";
var_export($params);
?>
Example script on https://gist.github.com/rubo77/6815945
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){},
})
this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
Hi I'm using jQuery and Codeigniter. I'm creating a simple todo list that can add delete entries using ajax.
The problem is whenever I click on my delete anchor, it won't delete the entry. The adding of the entry feature works BTW.
Here's my code:
todo_view.php
<html>
<head>Todo List</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var msg = $('#message').val();
$.post("<?= site_url('todo/add') ?>", {message: msg}, function() {
$('#content').load("<?= site_url('todo/view/ajax') ?>");
$('#message').val('');
});
});
$('a.delete').click(function() {
var id = $('input', this).val();
$.post("<?= site_url('todo/delete') ?>", {todoid: id}, function() {
$('#content').load("<?= site_url('todo/view/ajax') ?>");
});
});
});
</script>
<body>
<div id="form">
<input type="text" name="message" id="message" />
<input type="submit" name="submit" id="submit" value="Add todo" />
</div>
<div id="content">
<?php $this->load->view('message_list'); ?>
</div>
</body>
</html>
message_list.php
<ol>
<?php foreach ($todolist as $todo): ?>
<li>
<?php echo $todo->todo; ?>
<input type="hidden" value="<?=$todo->todoid ?>" />delete</li>
<?php endforeach; ?>
</ol>
Why doesn't it work?
First and foremost - to track GET/POST headers and values you should start using Firebug (an extension for Firefox). Really makes your life easy to terms of debugging ajax calls and responses.
Next (somewhat on the lines of what alimango mentioned)... the most likely cause is that the message list is being loaded AFTER your main page's DOM has already loaded. jQuery won't automatically bind the click event to elements added later. Your click binding routine has to be called AFTER the message list has been added to the DOM. Now this isn't always possible... as your list is being fetched / altered dynamically.
One solution is to use the live() bind event function that has been introduced since jQuery 1.3. This helps binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events. Fore more information, see http://docs.jquery.com/Events/live#typefn
Second solution is to use, LiveQuery - a jQuery plugin which "utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated." You can grab it from http://plugins.jquery.com/project/livequery
Cheers,
miCRoSCoPiC^eaRthLinG