I have a div element where a file is being loaded every 10500 miliseconds;
index.php
...
<div class="loadHere"></div>
...
code that loads every few seconds.
setInterval(
function ()
{
$('.loadHere').unload().load('filetoload.php').fadeIn('slow');
}, 10500);
filetoload.php
test
<input type="hidden" value="1234" class="hiddenelement"/>
and this is what i'm trying to do but isn't working:
$(document).on('click','.testbtn',function(event)
{
event.preventDefault();
var xyz = $('.hiddenelement').val();
alert(xyz);
});
Your strategy seems to work.
setInterval(
function () {
$('.loadHere').unload().load('toload.php').fadeIn('slow');
}, 10500);
$(document).on('click','.testbtn',function(event)
{
event.preventDefault();
var xyz = $('.hiddenelement').val();
alert(xyz);
});
Here is the working plunker : http://plnkr.co/edit/tiLv3WMDCjoW3Ggb9bTH?p=preview.
Use Callback function:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
From Jquery Docs
Related
For some reason my variable keeps resetting to 2 despite me wanting to increment the variable when a function is called. It's really annoying me and I've refactored the code several times to no avail! It should be simple...
Here is my code:
( function( $ ) {
$( document ).ready( function () {
var count = 2;
var total = <?php echo $loop->max_num_pages; ?>;
if ( count <= total ) {
$( window ).scroll( function() {
if ( $( window ).scrollTop() == $( document ).height() - $( window ).height() ) {
$.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + count + '&loop_file=forums',
success: function( html ){
$( "#content" ).append( html );
}
});
count++;
}
});
} else {
return;
}
});
})( jQuery );
EDIT: Thanks for your responses so far! Updated code below:
<script type="text/javascript">
pageCount = 2;
total = <?php echo $loop->max_num_pages; ?>;
jQuery( window ).scroll( function() {
if ( jQuery( window ).scrollTop() == jQuery( document ).height() - jQuery( window ).height() ){
console.log( 'Old value: ' + pageCount );
if ( pageCount > total ){
return false;
} else {
loadArticle( pageCount );
}
pageCount++;
console.log( 'New value: ' + pageCount );
}
});
function loadArticle( pageNumber ) {
jQuery.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=forums',
success: function( html ){
jQuery( "#content" ).append( html );
}
});
return false;
}
</script>
New value is always 3 and old value is always 2 (output in console) so it's still being reset...
SOLVED: The html callback in the ajax method was causing the issue. Moving the increment into there worked! New code:
( function( $ ) {
pageCount = 2;
total = <?php echo $loop->max_num_pages; ?>;
$( window ).scroll( function() {
if ( $( window ).scrollTop() == $( document ).height() - $( window ).height() ){
if ( pageCount > total ){
return false;
} else {
$.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + pageCount + '&loop_file=forums',
success: function( html ){
$( "#content" ).append( html );
pageCount++;
}
});
}
}
});
})( jQuery );
two things first:
var can be shortened as such:
var var1 = 'string',
var2 = 'int';
Don't mix php inside JS - it's messy. Create a hidden span and assign data tags to it and call like that
secondarily, that's because the value gets reset whenever you call the function. Place outside, or pass a parameter called count so you can make it more generic and use it throughout your project.
Define count variable outside the function.
e.g.
var count = 2;
( function( $ ) {
$( document ).ready( function () {
var total = <?php echo $loop->max_num_pages; ?>;
if ( count <= total ) {
$( window ).scroll( function() {
if ( $( window ).scrollTop() == $( document ).height() - $( window ).height() ) {
$.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + count + '&loop_file=forums',
success: function( html ){
$( "#content" ).append( html );
}
});
count++;
}
});
} else {
return;
}
});
})( jQuery );
Your problem here is that the var count is local to your method. This means that it is only alive in that method call. Next time you call your function again, it will create a different count with the value 2 since that is the value you specify on your declaration. Move the variable declaration outside the method and everything should be fine.
This is my code at www.domain-a.de/external.search.js. I call it from www.domain-b.de/test.php:
(function ($) {
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
var frm = $('#embedded_search form');
// click on submit button
frm.submit(function (ev) {
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
});
})(jQuery);
After running this code I don't get any message in console. What is wrong with that code?
frm.submit(function (ev) {
ev.preventDefault();
.....rest of code.
Your code is not calling the submit handler on the item, it is simply binding it. You should do the frm.submit(function binding outside of your $.getJSON callback; then inside the callback add
frm.submit()
Which triggers the event.
Also, when the submit happens, your actions will take place but then the form will submit to the back end as normal, causing a page reload.
After the line
frm.submit(function (ev) {
Add
ev.preventDefault();
So your overall code should be
(function ($) {
var frm = $('#embedded_search form');
var myUrl = 'http://www.domain-a.de/get-form-values?jsoncallback=?'
frm.submit(function (ev) {
ev.preventDefault();
$.getJSON( myUrl )
.done(function( json ) {
console.log( "JSON Data: " + json );
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
});
});
// make the ajax request
$.getJSON('http://www.domain-a.de/external-search.js?jsoncallback=?', function(data) {
// append the form to the container
$('#embedded_search').append(data);
$('#embedded_search form').attr('action','');
// click on submit button
frm.submit();
});
})(jQuery);
I created a JavaScript function that uses AJAX to call a CodeIgniter controller function that calls the model and retrieves data from the database and is returned as json.
I have successfully created it and have the data rendered using jQuery Template plugin, but I encounter errors when I move the View which renders the data from the index() function into a different function.
ajax goes into error and gives the status of 200.
below is the code:
<?php
class Scheduler extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Scheduler_model');
}
public function index() {
$this->load->view('templates/header');
$this->load->view('Rooms_view'); //data appears/gets rendered here
$this->load->view('templates/footer');
}
public function rooms() {
$this->load->view('templates/header');
$this->load->view('Rooms_view'); //error is encountered here
$this->load->view('templates/footer');
}
public function read($table) {
echo json_encode( $this->Scheduler_model->getAll($table) );
}
JavaScript/jQuery:
var readUrl = 'scheduler/read',
createUrl = 'scheduler/create',
updateUrl = 'scheduler/edit',
delUrl = 'scheduler/delete',
delHref,
delId,
updateHref,
updateId;
$(document).ready(function() {
var pathname = window.location.pathname;
if (pathname == '/MobileSchedule/scheduler/rooms'){ read('rooms'); }
//if i call read("rooms") here, it appears on index(), but errors on rooms()
}); //end Document ready
function read(table) {
$( '#ajaxLoader' ).fadeIn( 'slow' );
$.ajax({
url: readUrl + '/' + table,
dataType: 'json',
success: function( response ) {
for( var i in response ) {
response[ i ].updateLink = updateUrl + '/' + response[ i ].id;
response[ i ].deleteLink = delUrl + '/' + response[ i ].id;
}
//clear old rows
$( '.roomsList' ).html( '' );
//append new rows
$( '#roomsTemplate' ).render( response ).appendTo( '.roomsList' );
$( '#ajaxLoader' ).fadeOut( 'slow' );
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
console.log(thrownError);
}
});
}
Im doing a AJAX call and once I get the response, I want to replace a submit button with a label...But this is not working. I get the alert msg ie; the response from the Ajax call but the replacewith command fails.
Can you please tell me what is the mistake Im doing..
Replacewith command
$( this ).closest( 'tr' ).find( 'input:label' ).replaceWith("<label for=\'success\'>SUCCESS</label>");
Code:
$("#table_appl,#table_enfr,#table_det01,#table_det02,#table_det03,#table_det04,#table_det05,#table_datais").on( "click", "input:submit", function( event ) {
//alert('Hi')
//event.preventDefault();
var fieldvalue = $(this).closest('tr').find('input:text').val();
var fieldname = $(this).closest('tr').find('input:text').attr('name');
alert('fieldname = ' + fieldname)
alert('fieldvalue = ' + fieldvalue)
$.ajax({
type:"GET",
url:"/validate/",
data:{'fieldvalue':fieldvalue,'fieldname':fieldname},
success:function(data){
if (data == 'Y'){
var item = $(this).closest('tr').find('input:label')
alert("Gonna be replaced" + item);
$( this ).closest( 'tr' ).find( 'input:label' );
$( this ).closest( 'tr' ).find( 'input:label' ).replaceWith("<label for=\'success\'>SUCCESS</label>");
}
alert("Response = "+ data);
}
});
return false;
})
Here's a fiddle.
And here's the code:
<form role="form" method="POST" action="/validate/" id="input_form">
<input id="myInput">
<button type="submit" id="submitButton">Click me!</button>
</form>
with the script:
$("#submitButton").click(function () {
event.preventDefault();
$.get("/validate/", function (d){
if (d == "Y"){
$("#submitButton").replaceWith("<label>SUCCESS</label>");
}
})
})
Is this about what you want? I guess you'll have to adapt the .replaceWith() part to find the correct element...
I used the example from jQuery mobile site Autocomplete source code
It's working fine, but when I tried to give alert in the script inside the listviewbeforefilter event, it's showing the alert 3 times, so when 3 characters are entered, it will prompt around 7-9 times.
Why is it showing so many alerts? I thinks it should prompt only once when the character is inserted.
Here is the code retrun in script for autocomplete:
$( document ).on( "pageinit", "#myPage", function() {
alert("abc");
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
alert("789");
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
alert("123");
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
Here is the code return in the body tag:
<div data-role="content">
<h3>Cities worldwide</h3>
<p>After you enter <strong>at least three characters</strong> the autocomplete `function will show all possible matches.</p>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" `data-filter-placeholder="Find a city..." data-filter-theme="a">
</ul>
</div>