Getting jquery to work with dynamic content - php

I am currently using a very similar AJAX post request across many parts of my page:
$(document).ready(function() {
$("#name").change(function(e){
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
The above code works perfectly.
I am having a problem getting any functionality with dynamically loaded content. So for example a form grabbed by an AJAX call and put into my page this above does not work.
If we can pretend that I was running the same AJAX call as above but on dynamically loaded content from a PHP script using AJAX. what would my call look like. #table is a static element that is always present on the page.
I have tried this but it is not working:
$(document).ready(function() {
$("#table").on("click", "#btn1", function(e){
e.preventDefault();
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
Currently I am getting nothing show up on console and it just does not work.
Is what I am doing here correct?
The html would look like this: echoed from php:
<table id='table'>//this is the static element form is echoed
<form method='post'>
<input id='name' name = 'name'>
<button id='btn1' type='submit'>Add me</button>
</form>
</table>
I have changed my code slightly click on button rather than on change.

Try updating the code with following
$(document).ready(function() {
$("#table #btn1").on("click", function(e){
e.preventDefault();
var vname = $("#name").val();
$.post("addit.php", {name:vname}, function(response, status) {
$("#table").html(response);
});
});
});
It is not possible to set a function on a dynamically added element, when the element is not there in document
And instead of <table> use <div> if possible

I think your problem is that you miss
$( document ).ajaxComplete(function() { "script here will run and be available after ajax load" });

Related

jquery post Showing loading message till success

I have following script which fetch data from server based on form parameters.
jQuery('#request_search').submit(function(e){
e.preventDefault();
var s_date=jQuery('#actualfrom').val();
var e_date=jQuery('#actualto').val();
var type=jQuery("#type").val();
var loc=jQuery("#loc").val();
jQuery.post("scripts/get_gamma_activity_type.php", {"loc":loc,"start_date":s_date, "end_date":e_date, "type":type}, function(data) {
jQuery('#report').html(data);});
});
});
This part is working and some times, based on search criteria , it takes a couple of seconds to get results. in the mean time I would like to show some GIF saying data loading. I have the GIF ready. How to implement it in the above script?
please try this.
jQuery('#request_search').submit(function(e){
$("#report").html("<div><img src='loading.gif' alt='Loading.. \n Please wait' title='Loading.. \n Please wait'` /></div>");
e.preventDefault();
var s_date=jQuery('#actualfrom').val();
var e_date=jQuery('#actualto').val();
var type=jQuery("#type").val();
var loc=jQuery("#loc").val();
jQuery.post("scripts/get_gamma_activity_type.php", {"loc":loc,"start_date":s_date, "end_date":e_date, "type":type}, function(data) {
jQuery('#report').html(data);});
});
});
Add Image with path in your html file with id attribute and then show/hide div
based on request and success.
Try below code:
Add html div in your html file :
<div id='loadingmessage' style='display:none'>
<img src='loadinggraphic.gif'/>
</div>
Try below code of jQuery:
jQuery('#request_search').submit(function(e){
$('#loadingmessage').show(); // show the loading message.
e.preventDefault();
var s_date=jQuery('#actualfrom').val();
var e_date=jQuery('#actualto').val();
var type=jQuery("#type").val();
var loc=jQuery("#loc").val();
jQuery.post("scripts/get_gamma_activity_type.php", {"loc":loc,"start_date":s_date, "end_date":e_date, "type":type}, function(data) {
jQuery('#report').html(data);});
$('#loadingmessage').hide(); // hide the loading message
});
});

ajax inject html into a div but keep the html elements including their ids

I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};

jquery form submit does not work after using a load function

I have an index.html page which, using jquery, calls somepage.php residing within the same site to load the contents of this index.html page.
So this is the intended page load sequence:
index.html -> somepage.php -> submit.php (if submit button is clicked)
The index.html has only the "main-div" and no contents as such. When the somepage.php is called, the "main-div" contents are loaded by running the php script. The main-div contains a sub div with a small form with a submit button. Using jQuery,I see if the submit button is clicked, and when clicked, the submit.php script is called.
This is the barebone code:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$('document').ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get(
'http://www.someurl.com/submit.php',
{ item: jsURL },
function(data){
if(data=="success")
{
$('#submit-status').html(data);
}
else
{
$('#submit-status').html(data);
}
}
);
}
});
</script>
</head>
<body>
<div id="main-div"> </div>
</body>
</html>
Now the issue:
The index.html page loads with everything displayed correctly (the small form with the submit button, all other main-div contents, everything is displayed). However, the submit button does not call the submit.php script, meaning I believe that the jQuery code corresponding to the click event is not being registered.
I am fairly new to jQuery. Does this have something to do with how I have "ordered" the code in the jQuery .ready()? Something to do with the DOM not being ready before the function is called, or maybe an issue with the .load() in jQuery?
Try this :
<script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php",function(){
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').attr('value');
submit(jsURL);
});
});
});
function submit(jsURL){
$.ajax({
url:'http://www.someurl.com/submit.php',
type :'GET',
success: function(data){
$('#submit-status').html(data);
}
});
}
</script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get('http://www.someurl.com/submit.php', {item: jsURL}, function(data){
$('#submit-status').html(data);
});
}
});
Do not quote the document
load() is a shortcut for $.ajax, and it's async, so #item-submit does'nt exist when you attach the event handler, you need a delegated event handler for that.
If it's really a submit button inside a form, make you sure you prevent the default action so the form does'nt get submitted.
The load function works asynchronously. With your code #item-submit is not yet there when you try to bind the event handler.
Bind the event handler on succes:
$("#main-div").load("http://www.someurl.com/somepage.php", function () {
$('#item-submit').click(function () {
jsURL = $('#input').val();
submit(jsURL);
});
});
load loads the data asynchronously, which means time by the time you are assigning a click handler on submit button the button itself might not be yet on the page. To overcome this you have two options:
Specify a success handler for load.
$("#main-div").load("http://www.someurl.com/somepage.php", function(){
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
});
Use on to indicate that the click handler should be assigned to elements that are or will be on the page.
$('#item-submit').on('click', function(){
jsURL = $('#input').val();
submit(jsURL);
});
As all pointed out, the load function works asynchronously so, your click handler is not working for the 'future' div.
You can bind handler to a future element like this:
$(document).on('click', '#item-submit', function(event){
jsURL = $('#input').val();
submit(jsURL);
});
This way you can bind your handler in the jQuery document ready function.

jQuery .Post after javascript:submit_contact()

I'm trying to submit a little contact form.
Here is my jquery to POST:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
});
</script>
Here is my html that handles the form:
<form method="post" >
<textarea id="contact_me_text" name="contact_text">Ask me anything!</textarea>
<div>
<input type="text" name="contact_email" value="Email"/><br/><br/>
<a id="contact_submit" href="javascript:submit_contact()">Submit</a>
</div>
</form>
Everything seems to look ok but the form is not submitting. I've run the .php file through a regular submit and it works fine.
Any thoughts?
You need to declare your function outside of $(document).ready() and then call it using anything.
Why can't I ?
As Local Variables cannot be accessed from outside, similarly local functions cannot also be accessed.
Try this:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
$('#contact_submit').on('click', function(){
submit_contact();
return false;
});
});
</script>
and then remove the JS inside HREF attribute.
You need to declare the function outside ready function of jQuery. Moreover you can use serializeArray to determine data to send. By using this you will not need to mention every control name. On server side you can receive the input with same names you have mentioned in your form.
function submit_contact()
{
var params = $("#formId").serializeArray();
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", params, function(data){
console.log( data );
});
}

is the browser or server ignoring the code?

i made this form:
<form id="form" name="msgform" method="" action="">
<input type="text" size="40" id="msg" name="message"/>
<input type="submit" id="button" name="clicker" value="click" />
</form>
and this jquery script:
$(document).ready(function(){
$("#button").click(function(){
$("#form).submit(function(){
var submision= $("#form).val();
$.post("txt/process.php", submision, function(data){
alert(data);
});
});
});
});
and this is the process.php file:
<?php
echo $_POST['message'] . "";
?>
now when i click the button the form is submited, but it sends it using the GET method because i can see it in the adress bar, but it never gets sent to the php file, and i checked to see if the names are correct and if i specify the POST method it still doesnt go to the php file.
is the server or browser ignoring the code? or am i doing the whole thing wrong?
thanks
Please find the following code, it works and please go through with the documentation, it will tell you that what the mistake was being done.
$(document).ready(function(){
$("#button").click(function(){
$("#form").submit(function(){
/* var submision= $("#form).val();
THIS DOESN'T WORK TO GET ALL OF THE ELEMENTS IN
FORMAT TO PASS TO $.post EVENT,
We can do this as I did in following example
*/
$.post("txt/process.php", { msg: $("#msg").val() }, function(data){
alert(data);
});
/* Also you didn't put return false statement just at the end
of submit event which stops propagating this event further.
so it doesn't get submitted as usually it can be without ajax,
So this stops sending the form elements in url. This was because
by default if you define nothing in method property for form
then it consider it as GET method.
*/
return false;
});
});
});
Let me know please you are facing any issue.
You don't need to register the submit event for the form inside the click handler of the button. As it is a submit button it will automatically try to submit the form for which you register the corresponding handler:
$(function() {
$('#form').submit(function() {
// Get all the values from the inputs
var formValues = $(this).serialize();
$.post('txt/process.php', formValues, function(data) {
alert(data);
});
// Cancel the default submit
return false;
});
});
$("#form).submit(function(){
see if this selector is missing a "
$("#form").submit(function(){

Categories