Main page div is updated with an Ajax request. The updated html contains a form with input fields, a button, and another Ajax script to submit that form. While it is possible to initiate the second script by pressing the button in the injected form, the script does not seem to find form inputs by id.
I read about the .on() method of JQuery, but it only seems to provide access to dynamically updated functions, not elements.
How do I get the input element by ID, after this element got injected into the code with an Ajax request?
Main page:
<div id="output"></div>
<span id="call_account">Account</span>
$("#call_account").click(function(){
$.get('/accounts/login/', {}, function(data){
$('#output').html(data);
});
});
Injected into #output html:
<input id="id_username" name="username" type="text">
<input id="id_password" name="password" type="password">
<span id="account_submit">Submit</span>
$("#account_submit").on("click", function() {
var id_username = $('#id_username').val();
var id_password = $('#id_password').val();
$.ajax({
type:"POST",
url:"/accounts/login/",
data: {
'username': id_username,
'password': id_password,
},
success: function(data){
$('#output').html(data);
}
});
});
});
id_username and id_password are undefined when I try to submit the form.
edit:
Thanks to answers from the guys below I was able to get it to work. I also made a jsfiddle simulation of the problem in the process: https://jsfiddle.net/hn1Lrkzs/
Hope it helps someone in the future, I had trouble finding a direct answer, and lacked understanding to get the thing from help files.
Enclose your js inside document.body
<script>
$(document.body).on("click", "#account_submit", function() {
var id_username = $('#id_username').val();
var id_password = $('#id_password').val();
$.ajax({
type:"POST",
url:"/accounts/login/",
data: {
'username': id_username,
'password': id_password,
},
success: function(data){
$('#output').html(data);
}
});
});
</script>
Try to delegate the event to the document:
$(document).on("click", "#account_submit", function() {
var id_username = $('#id_username').val();
var id_password = $('#id_password').val();
$.ajax({
type: "POST",
url: "/accounts/login/",
data: {
'username': id_username,
'password': id_password,
},
success: function (data) {
$('#output').html(data);
}
});
});
Example:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).on("click", "#account_submit", function() {
console.log('delegated event: works');
});
$("#account_submit").on("click", function() {
console.log('direct event: works');
});
</script>
<input id="id_username" name="username" type="text">
<input id="id_password" name="password" type="password">
<span id="account_submit">Submit</span>
Related
Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).
I read a lot of similar questions, and I tried all solutions but nothing seems to work. I want to send an AJAX request by clicking a button and send what the user typed in a textarea and display it in a div(chatbox). When I click the button, nothing happens. It never calls the function that has the AJAX code. Do you have any ideas what is going on?
P.S. I included the JavaScript files but nothing's changed.
<form action="ajax()">
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
//AJAX function
function ajax() {
alert("insert");
var txtArea = $("#txtArea").val();
$.ajax({
type: "POST",
url: "InsertMessage.php",
data: {
txtArea: txtArea
}
success: function(data) {
alert(data);
$("#chatbox").load("DisplayMessages.php")
$("#txtArea").val(""); //Insert chat log into the #chatbox div
}
error: function() {
alert('there was an error, write your error handling code here.');
}
});
}
$(document).ready(startAjax);
//setInterval(function(){
// $("#chatbox").load("DisplayMessages.php");
//}//,1400);
</script>
Your question is not so clear, But for sending data in post method when submiting a form and then show result in a div, try something like this:
html:
<form>
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit">
</form>
<div id="resultDiv">
</div>
js:
$( "form" ).submit(function( event ) {
var txtArea = $("#txtArea").val();
$.ajax({
type:"POST",
url:"InsertMessage.php",
data:{txtArea:txtArea}
success: function(data){
alert(data);
$("#resultDiv").html(data);
}
error: function(){
alert('there was an error, write your error handling code here.');
}
});
});
The action attribute has to contain a URL, not Javascript. You can use:
<form action="javascript:ajax()">
or:
<form onsubmit="ajax(); return false;">
or you can bind the event in jQUery:
$(document).ready(function() {
$("form").submit(function() {
ajax();
return false;
});
});
what's up guys? look... I have a comment system for my web page... and I've been dealing with this little problem for a entire week. I really need some help here x_x ... the thing is that when a user leave a comment on my page, this comment is showed automatically thanks to ajax, that's ok...
each comment can be voted. and here's my problem... these divs that contain the forms for voting are build dynamically and the thing is that when I do click on the button for sending the form in any comment... the resulting data appears in all the comments! instead of appear in the specific one where the submit button was clicked, so I don't know what to do at this point, I hope you can give me a hand. this is my code
the form:
<label > Vote </label>
<form action="vote.php" method="POST" class="form-vote" id="form-vote">
<button class="icon-thumbs-up" id="icon-thumbs-up"></button>
<input hidden="hidden" type="text" name="num-comment" id="num-comment" value="'.$d['id'].'" >
<input hidden="hidden" type="text" name="point" id="point" value="'.$d['point'].'" >
<p id="actual-points" class="actual-points"> '.$d['point'].'</p>
<div id="result" class="result"> </div>
</form>
the script:
<script type="text/javascript">
$(document).ready function() {
$('.form-vote')on('submit', function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('.actual-points').hide();
$('.result').html(data).fadeIn('slow');
}
})
return false;
});
})
</script>
Have you tried saving the 'this' object of the original event and using it inside the success function like this:
$('.form-vote')on('submit', function(e) {
e.preventDefault();
var $form = $(this); // Save here
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// use here
$form.find('.actual-points').hide();
$form.find('.result').html(data).fadeIn('slow');
}
})
return false;
});
change this:
$('.result').html(data).fadeIn('slow');
to this:
$(this).find('.result').html(data).fadeIn('slow');
I want to clear all inputs value whenever result succeed.
I have tried unbind from Jquery but doesn't get any result
so any suggestion would be great
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="Result"></div>
<form id="Form" action="File.php" autocomplete="off">
<input type="text" name="Name" />
<br/>
<input type="text" name="Pass" />
<br/>
<input type="button" id="Submit" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#Submit").click(function()
{
$("#Form").submit(function(e)
{
$.ajax(
{
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function(data, textStatus, jqXHR)
{
$("#Result").html(data);
}
});
e.preventDefault();
});
$("#Form").submit();
});
});
</script>
</body>
</html>
please feel free to ask for more details
You can clear all inputs using
$("input[type='text']").val('');
You are binding an event handler inside another event handler. Each time the button is clicked, a new handler is attached to the form. So, after n number of clicks, you'll be sending n number of ajax requests, as you can see here
Ideally, your code should be
$(document).ready(function () {
$("#Submit").click(function () {
$("#Form").submit();
});
$("#Form").submit(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function (data, textStatus, jqXHR) {
$("input[type='text']").val(''); // reset the input values
$("#Result").html(data);
}
});
});
});
Demo.
Side note: You can simply use a submit button instead of triggering the form submission manually like this
Here you go:
$(document).find('input').each(function(){
$(this).val('');
});
More info on: http://api.jquery.com/val/
I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example