I am reading about Ajax Events from the jQuery docs.
My jQuery code with some HTML:
<p style="display:none">Loading...</p>
<div></div>
$(document).ready(function() {
$("p")
.ajaxStart(function(){
$(this).show();
})
.ajaxStop(function(){
$(this).hide();
});
$.ajax({
url : 'http://localhost/xampp/web_development/new_study_2014/my_files/test.php',
data : {id : 123},
type : "GET",
dataType : "html",
success: function(response) {
$("div").hide().html(response).fadeIn(1500);
},
error: function(xhr, status, errorThrown) {
console.log( xhr + status + errorThrown );
},
complete: function() {
console.log( );
}
});
});
The PHP:
<?php
sleep(1);
echo "<p> his name is jack</p>";
?>
I wanted the paragraph that says Loading... to display when the ajax request starts and hides when it is finished. As described in the jQuery docs. Yet it does none of the two and displays "his name is jack" from the php page. What am I doing wrong?
The target of the ajaxStart event is the document, not a particular element, so using $(this) in the handler won't work. Change it to select the specific element.
jQuery:
$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});
HTML:
<p id="loading" style="display: none;">Loading...</p>
Related
Spend a couple of days now on trying to get swipe on a php website with dynamic content. I've been looking at jQuery mobile but there is no example out the how to get swipe to work with dynamic content. Anybody that can point in a direction how to accomplish this? Does not have to be jQuery mobile it could be anything as long as they have an example to work after. This is what I've accomplished with jQuery mobile and it of course doesn't swipe nice with animation but do load the content on swipe.
$(document).on('swipeleft', '.ui-page', function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
getartikel('1');
}
});
getartikel() is a function that runs an ajax request getting the data from mysql and put it in a div.
function getartikel(id) {
$.ajax({
url: "ajax/getartikel.php",
type: "post",
data: {id:id} ,
success: function (data) {
$("#artikel").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
It is a bunch of articles that I want to be able to swipe between. data from the database I just HTML.
Pagecontainer is what I understand I must use but I can't figure out how to get that to work with a ajax call.
done some change to my code but still no slide, now I get Uncaught TypeError: a.split is not a function. It comes up when I add
$.mobile.pageContainer.pagecontainer('change', "#"+sida, {transition: 'slide'});
here is my complete code
<script>
$(document).on("pageshow", function (event) {
getartikellist();
//this get the menue and put into a ul listview with the class artikel
});
$(document).ready(function(){
$(document).on("click", \'[class^=artikel]\', function(event, ui) {
$("#menyn").panel("close");
getartikel($(this).data(\'secid\'));
});
});
</script>
function getartikel(id) {
var sida;
if($.mobile.activePage.attr("id")=="1"){
sida="2";
}else{
sida="1";
}
$.ajax({
url: "ajax/getartikel.php",
type: "post",
data: {id:id} ,
beforeSend: function() {
$.mobile.loading("show");
},
success: function (data) {
$("#innehall"+sida).html(data);
},
complete: function() {
$.mobile.loading("hide");
$.mobile.pageContainer.pagecontainer('change', "#"+sida, {transition: 'slide'});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
Everything works fine until I add the pagecontainer row, It adds the content to the right page and all.
I've tried at least 3 ways and every time I try to get a form to post using ajax, the page always reloads and nothing is submitted.
It doesn't even return a success or error - it seems that the function isn't even being called.
Here's the code, thanks in advance.
HTML:
<form id='sig_up' name='sig_up' style='min-width:170px'>
<textarea id='sig' class='custom-scroll' style='max-height:180px;'></textarea>
<br>
<input class='btn btn-primary btn-sm' type='submit' />
</form>
jQuery/AJAX:
$('#sig_up').on('submit',function(e) {
$.ajax({
url:'update_sig.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
$.smallBox({
title : "Signature Updated",
content : "Your signature has been successfully updated.",
color : "#296191",
//timeout: 8000,
icon : "fa fa-bell swing animated"
});
},
error:function(data){
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
});
Well, to send it I will attach the handler of the the form to the document (although according to the docs it doesn't matter), write the preventDefault first to avoid sending the form before anything (although I tried with it at the end, and the result is exactly the same, have to review this function).
So, the other important thing I did, and I thing is the real answer, is the change of the scope inside of the form. If you used $(this) inside of the AJAX, you're referring to the AJAX jquery handler, instead to the form, I changed it to show how it changes. I also added an error console.log to check what is wrong just in case. I tried the code below and it sends the call in my localhost.
$(document).on('submit', '#sig_up', function(e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url: 'update_sig.php',
data: $form.serialize(),
type: 'POST',
success:function(data){
console.log('ok');
// $.smallBox({
// title : "Signature Updated",
// content : "Your signature has been successfully updated.",
// color : "#296191",
// //timeout: 8000,
// icon : "fa fa-bell swing animated"
// });
},
error:function(data){
console.log(data);
}
});
});
Have you tried it with stopImmediatePropagation() ?
$('#sig_up').on('submit',function(e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
url: 'update_sig.php',
data: $(this).serialize(),
type: 'POST',
success:function(data){
console.log("Success");
},
error:function(data){
console.error("Error");
}
});
});
$('#sig_up').on('submit',function(e) {
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
var that = this;
$.ajax({
url:'update_sig.php',
data:$(that).serialize(),
type:'POST',
success:function(data){
$.smallBox({
title : "Signature Updated",
content : "Your signature has been successfully updated.",
color : "#296191",
//timeout: 8000,
icon : "fa fa-bell swing animated"
});
},
error:function(data){
}
});
});
I'm having a problem when I click my generate cards button multiple times(it generates a new set of cards randomly on every click) and then I click on any of my buttons that sort it will run multiple ajax calls instead of just the latest generated array. It will pass in every array of cards that has been generated not just the most recent one, sort of like it's keeping a queue.
console log will output, "sending color sort", "sending color sort", "sending color sort", etc. *For as many times as i've clicked my generate_cards* button
How can I have it so the sort function only runs once.
<input type="button" value="Generate Cards" id="generate_cards"> </input>
<input type="button" class="sorter" value="Color Sort" id="color_sort"> </input>
<input type="button" class="sorter" value="Shape Sort" id="shape_sort"> </input>
Generate Cards:
$('#generate_cards').click(function() {
$.ajax({
url: ''+set,
async: false,
type: 'POST',
dataType: 'html',
success: function(data) {
var obj = JSON.parse(data);
//sent array to sorting function :
sorting(obj);
var tmpl = $("#formInfo_tmpl").html();
var html = Mustache.to_html(tmpl, obj);
pool_window.html(html);
initilizejs();
},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
card sort function
function sorting(cards) {
$('.sorter').on("click", function() {
var cards_window = $("#sealed_pool");
var sort_type = $(this).attr('id');
//just give me the first word:
sort_type = sort_type.replace(/(\w+).*/,"$1");
console.log('sending'+sort_type);
$.ajax({
url: '',
async: false,
type: 'POST',
data: ({'cards':cards, 'sort_type':sort_type}),
dataType: 'html',
success: function(data) {
var obj = JSON.parse(data);
if(sort_type =='color_sort')
{
var tmpl = $("#color_sort_tmpl").html();
}
if(sort_type =='shape_sort')
{
var tmpl = $("#formInfo_tmpl").html();
}
var html = Mustache.to_html(tmpl, obj);
cards_window.html(html);
initilizejs();
},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
});
}
remove the previous click-listener before you add a new:
$('.sorter')
.off("click")
.on("click", function() {
//code
});
You need to use setInterval within the document ready function, like this:
$(document).ready(function() {setInterval(doAjax, 5000);});
I'm making an ajax request to my PHP script which will echo out a certain # of tables ( different each time), that I want to include on my original page when a user clicks the submit_form button. My question is how can i get Jquery to display this table into the table_layout div?
HTML :
<div id="table_layout"> </div>
JQUERY
$( ".submit_form" ).click(function( e ) {
$.ajax({
type : 'GET',
url: 'draw_tables.php',
dataType : 'html',
data: dataString ,
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert('error'); },
success : function(data) { //appendto.('#table_layout') }
});
return false;
})
PHP (draw_tables.php)
echo '<table>';
echo '<input type="text" name="ID">';
echo '<input type="text" name="CLASS">';
echo '</table>';
For example you could make an ajax request and fill the div with it
$.get("draw_tables.php", function(data) {
$("#table_layout").html(data);
});
This will fill your table_layout id with the data from the ajax request.
$('#table_layout').append(data);
Inside the success callback you should add:
$('#table_layout').append(data);
I am trying to fetch data form a callback page (php) and load it into a html div with jQuery mobile. This should happen if a user clicks on another div.
What I actually got is
$.('#home-button').bind('vclick', function( e ) {
$.get('homeCallback.php',function(data){
$('#displayContent').append(data).trigger('create');
},'html');
});
Where #home-button is the div that should trigger the event and #displayContent the div where the content should be put in.
The request should be able to pass some parameters, too. Like homeCallback.php?param=1 but it could also use the post method.
The callback does not have to be html only, it could also be possible that the callback php script provides JSON data or anything.
I am not a JS crack so I have problems solving this issue. Thanks for your help!
Edit:
So I found a solution on my own:
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajaxLoader = '<img src="images/ajax-loader.gif" alt="loading.." />';
var loadUrl = "homeCallback.php";
$('#home-button1').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option1',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
$('#home-button2').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option2',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
});
And this is what homeCallback.php simply does..
<?php
if( isset($_GET["option1"] ))
echo "option1";
if( isset($_GET["option2"] ))
echo "option2";
So far.
$.('#home-button').bind('click', function() {
$.ajax({
url: "homeCallback.php",
type: "POST",
data: ({param: 1, param2: 2}),
success: function(html){
$("#displayContent").html(html);
}
});
});