show and Hide loading with Ajax / PHP - php

I try to do something basic but i block.
I want to add a class to a div for loading when i click on "GO" and remove the class when i get the answer.
My code is :
$.ajax({
url: "/send_email",
type: "POST",
data: $('form').serialize(),
beforeSend: function() {
$('div.loading').classList.add('d-block');
},
})
.done(function(response) {
$('div.loading').classList.remove('d-block')
$('div.message').html(response);
});
return false;
};
The HTML is :
<div class="loading">Loading</div>
What im doig wrong ?
Actualy the page reload and in the console i get:
Cannot read properties of undefined (reading 'add')
i try to find my div seperatly and i get it !
I want to show and hide the loader

You're mixing up jQuery code and non-jQuery code. You can use .toggleClass() instead:
$('div.loading').toggleClass('d-block');
classList is part of the element itself, not the jQuery object. Which you can access from jQuery:
$('div.loading').get(0).classList.add('d-block');
But it doesn't make much sense to do so. Since you're already using jQuery, you might as well remain consistent with that.
Actualy the page reload
That sounds like a separate problem entirely, and one that exists outside of the code shown. This may be helpful, but all we can do is guess since the code shown doesn't demonstrate this specific problem.

Related

POST to PHP page on div change

The below is my code. Div id jp_current_track_title changes automatically when other events occur. I am trying to capture whats gets into the div "Track_title and post it onchange to like.php. as of now i cant figure it out. Im getting something back into the result div but its not posting. What am i doing wrong?
$(document).ready(function() {
$('#track_title').change(function() {
var content = $('#track_title').html();
$.ajax({
url: 'like.php',
type: 'POST',
success: function(info){ $("#result").html(info)
},
data: {
content: content,
}
});
});
});
Instead of detecting changes in jp_current_track_title, can you capture the other events that caused the update to jp_current_track_title? If so, can you get the updated title from there?
You aren't going to get 'change' events when the contents of a div change, it doesn't work like that.
See here:
Fire jQuery event on div change
The main answer mentions how you can track DOMNodeInserted / DOMNodeRemoved / DOMSubtreeModified events, however those don't work in IE.
Your best bet is to use setTimeout() and check the innerHTML of the div on regular intervals to see if the value has changed.

Ajax jquery returns blank page

I have this JavaScript code:
$(document).ready(function(){
$('#sel').change(function(){
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+$(this).val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
On status change i need to refresh a div without page reload. But it returns blank page. If i try alert the result on success, i get the response, also i checked with inspect element, its ok. The problem is that it returns blank page.
The file i'm working on, is the same( modules.php?name=TransProject_Management&file=index ) i called in ajax.
the html:
<body>
//...
<div id="ajax_results">
//.....
//somewhere here is the select option <select id="sel">......</select>
//.....
</div>
</body>
Any help, would be very appreciated.
use the following code to return your response html:
echo json_encode(array($your_response));
Then in your javascript, you will need to reference the data as:
success: function(data) {
$("#ajax_results").html(data[0]);
}
since it is now an array.
this in your ajax function refers to the jQuery XHR object, NOT the $('#sel') object. Just assign it to a variable before the ajax function like var sel = $(this) then use it later inside the function. Try this:
$('#sel').change(function(){
var sel = $(this);
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+sel.val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
Hmm, first glance the code looks good. Have you tried using Chrome debug tools? Hit F12 and check the Network tab, this will show you what is being returned. You can also debug without using an alert so you can step through to see what exactly the properties are.
Just thought, you might need to add 'd' to the data returned. Anyway, if you do what I suggested above, put a pause break on the line and run the code you will see what you need.
Based on your comments below the question, it seems that you are using the same script to display your page and to call in the javascript. This script seems to return a complete html page, starting with the <html> tag.
A page can only have one <html> tag and when you try to dump a complete html page inside an element in another page, that will lead to invalid html and unpredictable results.
The solution is to have your ajax script only return the necessary elements / html that needs to be inserted in #ajax_results, nothing more.

jQuery.get() - How do I use the entire result?

I read this question, and I'm pretty sure it's 90% of what I need, but I'm after something more than just this, and my success formulating my query in Google has been less than stellar.
What I'd like to do
I have a form on a site that, when submitted, needs to connect with a database, and then the user needs to be apprised of the result. I'm trying to get the result page to load in a modal jQuery dialog instead of forcing a full page reload. At present, I'm just trying to create a jQuery dialog that replaces the contents of a <div> with the product of a PHP file. I know I will get the PHP file's execution result this way. That's what I'm after, but it currently is not working.
My code currently looks like this:
$(document).ready(function() {
$("#dialog").get('include.php', function(data) {
$("div#dialog").html(data);
});
});
And include.php is simply:
<?
echo "<h1>Loaded</h1>";
?>
When I load the page, the original contents of #dialog are still there. I have a strong suspicion that what I'm failing to grasp isn't major, but I've had bad luck finding the fix. I'm a web dev newbie. How do I wwebsite as on the internet?
You are calling get on a jQuery result. That'a a different method than $.get, the one you should be using:
$(document).ready(function() {
$.get('include.php', function(data) {
$("div#dialog").html(data);
});
});
i have been using Ajax call for the same purpose. So try this :
$(document).ready(function() {
$.ajax('include.php',
success : function(data) {
$("#dialog").html(data);
});
});
If you want to replace the entire contents of the #dialog DOM object with the HTML you load, then you probably want to use .load():
$(document).ready(function() {
$("#dialog").load('include.php', function(data) {
// no need to set the html here as .load() already does that
});
});

Ajax Post PHP Div Refreshing

It is me again. I am getting so frustrated with this code it is not even funny. It's not that I am wanting to post it again. It is just that now I understand the where the problem was in the code and wanted to see if you guys can help me figure the last part out.
Basically I am trying to refresh a div without reloading the entire page. It's killing me. Here is some more information on it:
here is my js file first
$(function() {
$(".button").click(function() {
// validate and process form
// first hide any error messages
var email = $("input#email").val();
//var dataString = '&email=' + email; commented out
var dataString = email;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: {email:dataString},
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function() {
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
$("#email").val('');
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
Now the problem that I am running into with this code is on the Ajax part. After placing the alert(), I have relized that if I use the function() like this:
success: function(data)
Then the alert came out blank. The reason behind it is that my URL is going to my php file, but my div that I am trying to refresh is on my html file. Meaning if I do this:
success: function(data) {
$("#div").html(data)}
I am sending blank data because it's trying to get the div from my php file instead of my html file.
Now if I do this:
$("#div").html()
Then that gives me the div that is in my html file.
By knowing what is going on now, Can you guys please help me???
My dear you should generate some sort of html in your php file that you want to generate in your div. Then you will see that you are having some content in data in the success function. This is an easy approach.
But there is also some other approach that is more efficient but it needs some sort of search. This is the implementation of Client Side Scripting. You can do this with the help of a jquery plugin jquote2. I hope it will work for you.
You're using
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
Both are wrong, jQuery .fadeIn() and .fadeOut() arguments are either [duration,] [callback] or [duration,] [easing,] [callback]. None take HTML as input.
Try changing
$("#div").fadeOut($("#div").html());
to
$("#div").fadeOut();
and moving it outside the $.ajax call to hide the previously showed (if any) results before the post and also change
$("#div").fadeIn($("#div").html());
to
$("#div").html(result).fadeIn();
Also change
success: function()
to
success: function(result)
Hope it helps.
This might be a problem relating to the response from the php script. Jquery doesn't always correctly render the Ajax response as html.
Setting dataType: html in the $.ajax({ ... }) call can help. Also setting header("Content-Type: text/html"); at the top of your php ajax script.

How to change the content of a div without reloading the webpage?

I have a website, that uses PHP to select the content,
<div>
<? include ("navigation.php"); // navigation.php generates the menu ?>
</div>
<div>
<?
$type = $_GET["type"];
switch ($type) {
case "page" :
include "Text.php";
break;
case "news":
include "news_2.php";
break;
default :
include "main.php";
}
?>
</div>
The url is of the format domain.com/index.php?type.
I need to change the block #content without reloading the whole page, how can I do this?
As you've tagged the question with "jquery" I assume you know what that is, and that you're loading it into your page.
All you need to is give your div and ID... content here
And then use a bit of jquery.. in its simplest form just to load your content from 'myurl.php' into 'mydiv' when the page has finished loading:
$(document).ready(function() {
$("#mydiv").load("myurl.php");
});
You'll no doubt want some logic to determine what loads, and under what circumstances. If you need to pass data back to the URL then you'll need to go for jquery ajax ($.ajax). Its all pretty easy, loads of examples on the web, and good docs on the JQuery website.
This would best be done with Ajax. I like using jQuery's ajax function. Something like this:
function load(page){
var datastring='ANY DATA YOU WANT TO SEND';
$.ajax({
type: "POST",
url: 'your/pagehtml/',
data: "bust="+Date()+datastring,
dataType: "html",
cache: false,
success: function(html){
$('#content').html(html)
}
});
return false;
}
You wouldn't need to send the page in the URL this way. Anytime you change the url, you must be loading a different page. Outside of .htaccess rewrite. Which isn't what you need.
Fire this on click or whatever you want.
If you're using jQuery, it's pretty easy. You didn't post what is supposed to trigger the change, so I'll assume you have a list of links in another element with an id of nav.
Read more about the jQuery Ajax request here: http://api.jquery.com/jQuery.ajax/
//run on page load
$(function(){
//bind a click event to the nav links
$("#nav a").bind("click", function(e){
//keep the links from going to another page by preventing their default behavior
e.preventDefault();
//this = link; grab the url
var pageLocation = this.href;
//fire off an ajax request
$.ajax({
url: pageLocation,
//on success, set the html to the responsetext
success: function(data){
$("#content").html(data.responseText);
}
});
});
});
I'd also suggest doing some code cleanup like caching your $("#content") element on the load event (something like window.container = $("#container"), and using window.container later on), but I left it as-is so that everything remains clear.

Categories