Update, I changed jQuery to this and it still doesn't work:
$("#click").click(function(){
$.post("accountcreation.php",function(response){ userCreation:"userCreation"
$("#justtesting").html(response);
})
})
Nothing is happening. I had the HTML and PHP working, but then I wanted to add live updating and began this jQuery code. What's wrong with it?
Thanks.
jQuery
$("#click").click(function(){
$.post("accountcreation.php", { userCreation:"userCreation"
})
$.get("accountcreation.php", function(data,status){
$("#justtesting").html(data);
})
})
HTML
Username: <input required type="text" name="userCreation"
onchange="userValidate();"
onkeypress="this.onchange();"
onpaste="this.onchange();"
oninput="this.onchange();">
<span id="userRegexJavascriptResponse"></span>
<br>
<input type="button" value="Submit" id="click">
<div id="justtesting"></div>
PHP (Part)
class accountcreation {
private $options;
function __construct($con, $ipCreation) {
$this->passwordCreation = $_POST['passwordCreation'];
$this->userCreation = $_POST['userCreation'];
$this->ipCreation = $ipCreation;
$this->emailCreation = $_POST['emailCreation'];
$this->con = $con;
}
Use this code instead. Your PHP script is expecting data via post, and you can get a response in that same .post() call.
$("#click").click(function(){
$.post("accountcreation.php", { userCreation:"userCreation"}, function(data){
$("#justtesting").html(data);
});
});
NOTE: I would strongly advise against inline javascript; it's so difficult to maintain and is just not good practice. Event listeners should be attached as above ... that's the way to go.
Your HTML should be:
Username: <input required type="text" name="userCreation">
<span id="userRegexJavascriptResponse"></span><br>
<input type="button" value="Submit" id="click">
<div id="justtesting"></div>
And, you do need to include jQuery core right before the JavaScript code:
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
If you open your dev tools and run the code snippet below, you should see a post call being made with the data you supply. This means that it should be able to work on your server or else you should be able to see any errors in the console of the dev tools.
$("#click").click(function(){
$.post("accountcreation.php", { userCreation:"userCreation"}, function(data){
$("#justtesting").html(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Username: <input required type="text" name="userCreation">
<span id="userRegexJavascriptResponse"></span><br>
<input type="button" value="Submit" id="click">
<div id="justtesting"></div>
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I tried to add a form from a php file to another php file using jQuery, and I added an event to my added input(submit) button, but it's nt work,
I have seen some answers that propose using the method $elm.on("click",function() instead of of $elm.click(function(), but it still not work.
So here is my code :
<div id="update" class="third">
<div class="updatingzone">
You will have to rwrite all the data again
<form method="post" class="updating">
<input type="text" name="id" class="id" style="width:40px;" />
<input type="submit" id="button" value="Insert" />
</form>
<input type="submit" id="button" class="cancel" value="Cancel" />
</div>
<div class="insertion"></div>
</div>
when I press the Button Insert this php file is added :
<?php require_once "connexion.php";
$gdb = new GestionBD();
$id = $_POST["id"];
$req = "select * from utilisateurs WHERE id='$id'";
$results = $gdb->selectFromBD($req);
foreach ($results as $result):
?>
<form class="insertMode" method="post">
<input type="text" value="<?php echo $result->nom;?>" class="nom" name="nom" /><br />
<input type="text" value="<?php echo $result->email;?>" class="email" name="email" /><br />
<input type="text" value="<?php echo $result->sexe;?>" class="sexe" name="sexe" /><br />
<input type="text" value="<?php echo $result->age;?>" class="age" name="age" /><br />
<input class="test" id="button" type="submit" value="Add" />
</form>
<?php endforeach;?>
When I press the button with the class test I don't get an alert with "no" message, as you can see in the script :
$(".updating").submit(function () {
var id = $(".id").val()
$(".insertion").show()
$.post("getId.php",{id:id},function (data) {
$(".insertion").html(data)
});
return false;
});
$(".test").click(function () {
alert("no");
});
And i am sorry if this is long.. Thank you people
Since the element is being generated dynamically, you need to use event delegation.
$(document).on("click",".test", function () {
console.log("no");
});
Reference Document: https://learn.jquery.com/events/event-delegation/
Hope this will help you.
use this construction for dynamicaly created objects: $(document).on("click", "elementSelector", function(){ /* function body*/})
Create delegated event binding using on like this
$(document).on("click",".test",function(){ ..... });
Note : Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
The jQuery method you're using assumes that the element is already within the DOM (already exists on the page) when your Javascript runs. Because you're adding HTML to the page after your script has run, your use of $(".test") will not catch any HTML added later.
You have two options:
1. Query your HTML only once the new HTML has been inserted
Include your $() query in the same callback where you're inserting your HTML, like this:
$.post("getId.php", {id:id}, function(data) {
$(".insertion").html(data);
// this will work now
$(".test").on("click", function() { ... });
});
Or, maybe better, scope your jQuery query to only look within the newly inserted HTML:
$.post("getId.php", {id:id}, function(data) {
var $insertion = $(".insertion");
$insertion.html(data);
// only find .test within the new HTML
$insertion.find(".test").on("click", function() { ... });
});
2. Change your jQuery syntax to bind an event listener to the body
As #diavolic points out, jQuery provides a second syntax for .on, where you bind your listener to an element but provide a selector as a second argument. The callback will only fire if the event is triggered on elements matching this selector. By binding the listener to the body tag (which is always present in the DOM) and providing .test as the selector, the .test element doesn't need to exist in the DOM when the javascript runs.
$(document.body).on("click", ".test", function() {
// do something
});
$.post("getId.php", {id:id}, function(data) {
$(".insertion").html(data);
});
Either option should work. The first option is a better option if you want to listen for clicks only within a specific element. The second is more reliable if you aren't sure when or where the new HTML will be inserted.
More information about event delegation can be found here: http://api.jquery.com/on/#direct-and-delegated-events
//for <input type="button" class="test" value="test">
jQuery(document).ready(function() {
jQuery('.test').on( 'click', function () {
alert('no');
});
});
Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.
I am making a chat script and an hoping to code it so that when a user submits a message, the script will run chat_new.php and then refresh #cbox. I use the code below to try and accomplish this, but unfortunately it won't reload. Just to rule it out, I tested without any jQuery and chat_new.php executes without problems, so it definitely is my ajax script. In addition, getUpdates() works just fine on it's own. I only have a problem when posting new messages through ajax.
<div id="cbox" align="left">
<script>
$(document).ready(function() {
setInterval(function() {
getUpdates()
}, 2000);
});
function getUpdates() {
$("#cbox").load("/lib/chat_post.php");
}
$("#submitmsg").click(function() {
$.ajax({
type: 'POST',
url: '/lib/chat_new.php',
data: {
submitmsg: 'submitmsg',
usermsg: 'usermsg'
},
success: function() {
getUpdates()
}
});
});
</script>
</div>
<form name="message" method='post' id="cbox_input">
<input name="usermsg" id='usermsg' type="text" size="63" maxlength="255" />
<input name="submitmsg" id='submitmsg' type="submit" />
</form>
Several issues:
Your click handler exists before the element it references and is not inside document.ready. Therefore it can't find the element and never gets bound to it
Once that is fixed you need to prevent the default form submit process. Otherwise page will reload on submit
// put this inside ready()
$("#submitmsg").click(function (event) {
event.preventDefault();
//other code
})
This might be a simple as moving }); from the third line of your script, to just before </script> so that your function and your ajax call are inside $(document).ready(... and therefore only get processed once the DOM has loaded, and all HTML elements are on the page.
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>