I would like to give a high level explanation of what's my issue because I can't put up complete code which is too complex.
I have a button. when I click on the button, it pulls data from fb parses it and adds it to the page. Now after it is loaded to then page.. I want to run a script on the loaded content. I am running the script after the data is parsed but somehow it shows that element is not loaded by the time script started running. can some one throw some light.
$("somebutton").on("click",function(){
LoadAndParseFbData();
});
function LoadAndParseFbData(){
//loaded the json, parsed it and added to the page.
anotherScript();
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
This is what i am trying on high level. please help thanks :)
$("somebutton").on("click",function()
LoadAndParseFbData();
});
function LoadAndParseFbData(){
FB.api(path, method, params, function(){
//loaded the json, parsed it and added to the page.
anotherScript();
});
}
function anotherScript(){
// this has some script related to data which is loaded dynamically by parsing json.
}
Run anotherScript() from within the ajax success callback:
$J.ajax({
url: url2,
type: "post",
data: { data: "yourdata", },
success: function (data, textStatus, jqXHR) {
anotherScript();
},
error: function(jqXHR, textStatus, errorThrown) {
/*error handling code here*/
}
});
Related
I'm new to AJAX and not so good at PHP. I'm trying to simply send a string saying "Hello" to my PHP page using the JQuery $.AJAX function. So far I have successfully got AJAX to send the information to the page and log it in the console but the data doesn't get stored into the POST variable.
Please keep in mind I'm not being lazy by coming to this forum and asking for help but I have no other choice because I've been searching for about 2 days now on how to fix this problem and haven't found anything that's worked.
Here's my HTML (order.html) - This isn't all my HTML but it's all you will need):
<html>
<body>
<form method="POST">
<button id="order-btn" type="submit" formaction="PHP/sendMail.php">Order</button>
</form>
<!-- JavaScript/JQuery links -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="JS/order.js"></script>
</body>
</html>
Here's my JavaScript (order.js - Once again, I'm only providing necessary code)
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "PHP/sendMail.php",
type: "POST",
data: {data: txt},
dataType: "html",
asyc: true,
success: function(data){
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
Here's my PHP(sendMail.PHP - I'm only providing necessary code)
<?php
if(isset($_POST['data'])) {
$data = $_POST['data'];
echo $data;
} else {
echo "Failed to grab data.";
}
Just to clarify, in my actual code the URL is the full URL of my website page.
Let me know in the comments if you would like to see the site to get a better understanding of how and why I need this feature to work.
UPDATE & SOLUTION:
From the help I received I now understand that AJAX will only update information on the current page (So, for example, if you have an AJAX function on index.html then you can only run AJAX on that page and can't transfer information across pages)
To solve my problem I stopped sending users to the sendMail.php page and instead changed the HTML content of the page I was currently on (order.html) in the $.ajax success method.
Here's the updated JavaScript code:
$("#order-btn").click(function() {
var txt = "Hello!";
$.ajax({
url: "order.html",
type: 'POST',
data: {data: txt},
dataType: 'html',
success: function(data){
if(parseInt(data)!=0) {
$("body").html(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
I'd like to thank everyone that helped :)
$.ajax({ //create an ajax request to load_page.php
type: “POST”,
url: “load-page.php”,
data: {page:url}, //with the page number as a parameter
dataType: “html”, //expect html to be returned
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$(‘#pageContent’).html(msg); //load the returned html into
pageContet
$(‘#loading’).css(‘visibility’,’hidden’);//and hide the rotating
gif
}
});
Like in above example load-page.php is called so data returned is going to dispaly in pageContent which is the id of some div etc and this div is not on load-page.php this div is on the page from where this ajax request is sent.
may be it will make sence
reference link: Reference Link!
It's not like this way as you have called sendMail.php this file and the data returned will be available in the page from where it was called.
Let suppose with button click on page A you called sendMail.php, so the ajax response returned to page A not to sendmAil.php.
First thing, garantees that your API is working. Using a toolchain for API, like postman or insomnia.
If your api is returning what you want, then you go to your javascript code, because I don't see any problem in your code. I even used your code and worked.
Then use session
session_start(); //at the top
$_SESSION['mydata'] = $data; // something like it
but as far as I know it's necessary to refresh the page for session to work. please try it
I have a select box(list box) where it has 3 values drop down like Pending,Approve,NotApproved and when I select any one of them I want to fire a query so that I get data from database
like select * from table where status="Pending" without reloading page.
can any one help me how can I get data from database without page refresh in a php file.
Thanks in Advance
You can use a get or post AJAX request like so:
jQuery.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'xml/html/script/json/jsonp', // I guess html will be do or JSON if you are returning in a JSON format
data: {param1: 'value1'}, // Here you can send any additional parameters like status ( pending etc.)
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
// in the data variable you will receive the data from your PHP file if the request was succesfull
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
Reference: https://api.jquery.com/jQuery.post/
You should use AJAX for this (as is said in comments). You have can use :
XmlHttpRequest,
jQuery : Less code than an ordinary XmlHttpRequest and easier to implement. Perfect for beginner but heavy if you are looking for performance (to my mind),
And some libraries that I don't know.
I am using jQuery ajax to render an HTML page which also contains javascript functions.
my code is:
function ChartBook() {
$.ajax({
url: '/Charts/ChartBook',
dataType: 'html',
id: 1,
traditional: true,
type: 'GET',
success: function (content) {
$(document.body).empty();
$(document.body).html(content);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An unexpected error occured.');
}
});
}
The page Chartbook contains a function "GetChartData()".
It runs fine, but when I call another page in same manner, The Chartbook page is now not in the body, but I can still get alert message from function "GetChartData".
How can scripts be still there, while I have removed the page from html body with $(document.body).empty()?
EDIT:
Another problem is that, if I recall the "Chartbook" page and return to the previous page, The alert message comes twice from the function "GetChartData()". the number of alert message increases each time I load Chartbook page and return to previous page.
The scripts are usually placed on top of the body in a header section. Therefore they will not be removed by $(document.body).empty(); which you could also write as $('body').empty();.
Doesn't matter if you remove all html they are still in DOM check this
I have created a loading screen plugin. The scenario is that i am doing page navigation using ajax loading. So before loading a page using ajax, i would show an loading screen using the code $('body).loadingMask('show') and once the page is loaded completely loaded, i would remove the loading screen using the code $('body').loadingMask('hide).
The problem is that, there is some delay in retrieving the target dom element inside the plugin.
This is the general structure of the code
$('body').loadingMask('show');
$.ajax({
url : 'views/next.html',
async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
$('body').loadingMask('hide');
The problem is that , inside the show function of the loadingMask plugin, There is a delay in retrieving the target dom element(i.e body) . So pratically, the code $('body).loadingMask('show') runs only after the ajax page is finished loading.
In order to make it work , i have added a time delay. Which seems to work fine.
This is the modified code
$('body').loadingMask('show');
setTimeout(function(){
$.ajax({
url : 'views/next.html',
async : false,
success : function(content, textStatus, jqXHR) {
$('body').append(content);
},
error : function(content, textStatus, jqXHR) {
throw "Unable to load template. Please check the path and name of the template"
}
});
},500);
$('body').loadingMask('hide');
Now i can see the loading screen, while the page loads.
If you remove async:false you can call your plugin withing the ajax success, right after the content gets added.
async:false is deprecated and often leads to unforeseen problems
$('body').loadingMask('show');
$.ajax({
url: 'views/next.html',
success: function(content, textStatus, jqXHR) {
$('body').append(content).loadingMask('hide');
},
error: function(content, textStatus, jqXHR) {
/* likely need to remove maske here and add something to content to advise user*/
throw "Unable to load template. Please check the path and name of the template"
}
});
This is my first time using AJAX. I'm trying to load one of my pages when a link is clicked (I know I can just do <a href="something.html"> but I am doing it just for the sake of using AJAX, and ran into an issue where my page loads but the javascript of the page doesn't. Is this a normal AJAX consequence? I'm guessing it has to do with dataType: html? Here's my code:
function getContent(filename) {
$.ajax({
url: filename,
type: "GET",
dataType: "html",
beforeSend: function(){
$('html').html('<img src="../images/loading.gif">');
},
success: function (data, textStatus, xhr) {
if (filename == "second.html") {
setTimeout(function (){
$('html').html(data);
}, 2000);
} else {
$('html').html(data);
}
},
error: function(xhr, textStatus, errorThrown) {
$('html').html(textStatus);
}
});
}
Can you check chrome's network monitor? First off, does anything get a 404? Is the file literally second.html? If so then there shouldn't be path issues. Next what is the "response" that appears for that item? Does that response look ok?
Next, why don't you try moving the JS from head into the body for the second page? JS should always be right before the closing body tag for performance reasons. Also, there may be an issue with JS being in head and it not getting executed for that reason.
You should be able to load anything on your domain without any issues via AJAX, but there are path issues to watch out for.
This is because the ajax page is only returning rendered content, but does not run like a normal page would. You can use PHP on the ajax page for example, the server renders it and then sends it through, because PHP is pre-render, javascript runs after the page is rendered, as far as I know.