AJAX Load Content - javascript

Im completely lost on how to work AJAX. Looked up some tutorials and all seemed pretty confusing. I ran into the problem: [ Script only runs once ].
I would use it to reload pages like so: [ http://www.roblox.com/Poison-Horns-item?id=62152671 ] so I could get the latest item prices, without refreshing the page. if anyone could help/tell/point me in the right direction, it'd help TONS.
Im somewhat a beginner scripter, so be a little patient ;)
Thanks for any help,
Alex

AJAX requests are the same as page requests (GET and POST), except that they are handled asynchronously and without leaving the current page. The response data is the source of the page you wanted to fetch. That source is useless until you parse/use it.
A simple jQuery example:
//for example, we are on example.com
$.ajax({
type : 'get', //the METHOD of the request, like the method of the form
url : 'index.php' //the url to fetch
data : { //additional data which is synonymous to:
query1 : 'foo', // - url queries
query2 : 'bar', // - form inputs
query3 : 'baz',
},
success : function(resposeText){ //response text is the raw source of the fetched resource
$(element).html(responseText); //use response as HTML for element
}
});
//this is similar to requesting:
http://example.com/index.php?query1=foo&query2=bar&query3=baz

agree with joseph. You can use ajax by javascript manner or by jQuery, I personally suggest jQuery because it is simple to implement.
$.ajax({
type: 'GET',
url: "URL you want to call" ,
data: 'Data you want to pass to above URL',
cache: true, //to enable cache in browser
timeout: 3000, // sets timeout to 3 seconds
beforeSend: function() {
//when ur ajax call generate then u can set here loading spinner
},
error: function(){
// will fire when timeout is reached
},
success: function(response){
//in response you can get your response data from above called url.
}
});

Related

Datatable.js + POSTing data PHP

I'm trying to setup my datatable to POST to the contents of it's rows into my PHP script so that I can store it in a database.
I have a working HTML page, which when I click "+ Add Mapping" a BS modal appears and I can add a row to the datatable.
<script>
$(document).ready(function() {
var t = $('#parameters_config').DataTable();
$('#add_new_mapping').on('click', function() {
$('#add_field_mapping').modal('hide');
var wb_field = $("#add_field_mapping #wb_field").val();
var adobe_field = $("#add_field_mapping #adobe_field").val();
t.row.add([
adobe_field,
wb_field,
]).draw();
$('#add_new_field_mapping').trigger("reset");
});
});
</script>
This all works perfectly. I now would like to retrieve all data rows and POST them to my script so that I can process the submitted data and store. So far, I've come up with this based on information provided:
<script>
$(document).ready(function() {
$('#parameters').submit(function(event) {
var table = $('#parameters_config').DataTable();
var dataToSend = table
.rows()
.data();
console.log( 'Data', dataToSend);
alert( 'There are '+dataToSend.length+' row(s) of data in this table');
$.ajax({
type: 'POST',
url: '{$this->homeURL}',
data: dataToSend,
dataType: 'json',
});
});
});
</script>
In my console window I see the following returned for "dataToSend" but no actual data!
[Array[2], context: Array[1], selector: Object, ajax: Object]
Where am I going wrong?
Where the examples went wrong
The two examples you linked in your post aren't really related to what you're trying to do (from what I can gather about your goal).
The first example is about how to obtain data from the server with a POST instead of the default GET, and has nothing to do with sending data to the server for some purpose.
The second example is about serverside processing, which is where you have pagination, ordering, sorting, filtering, and all other DataTables features handled in your own server code where you then send the results to the client (which is pretty complicated and unless you have a huge number of rows, unnecessary).
Therefore, remove serverSide: true!
Your Goal
What you actually want to do (I think) is send your data to a php script so that you can do something with it. This is not handled by any DataTables API call, but is a fairly simple feature to implement. All you really need is a function that will make an AJAX call that will send the data to the script.
Solution
The way you can do this is by obtaining the data with the t.data() API call, and then sending it with an ajax request. It might look like this:
function sendData(){
var dataToSend = t.data();
$.ajax({
type: 'POST',
url: 'URL OF SCRIPT HERE',
data: dataToSend
});
}
Then you simply have to call sendData() whenever it is that you want to send the data. Of course, you'll have to ensure that your controller handles the data correctly, but that's a different matter entirely.

JSON call giving value that is not actually in the .json file

I am a little new when it comes to JSON and Javascript , so please excuse me if if this is a stupid question, but I have run into a problem that is starting to drive me insane.
On a webpage I am including two scripts; jQuery and a file called "scripts2.js". In the same directory as scripts2.js, I have a JSON file; "settings.json". From within my "scripts2.js" file I am running he following code inside of a function.
var settingsPath = settings.json;
jQuery.getJSON(settingsPath, function (data){
jQuery.each(data, function(index){
console.log("!"+data[index].name);
/*unrelated other stuff */
});
});
Previously the settings.json file looked like this
[
{"name":"Standard Black"},
{"name":"Gold"},
{"name":"Silver"}
]
So naturally when I looked in the Chrome Dev Console the log would print out
!Standard Black
!Gold
!Silver
However, when testing what would happen upon editing my settings.json file I changed "name":"Gold" to "name":"Test".
[
{"name":"Standard Black"},
{"name":"Test"},
{"name":"Silver"}
]
After the json updates I tried refreshing the page but my console log is still printing out
!Standard Black
!Gold
!Silver
...
I am at a loss. I have no idea why the data being retrieved with jQuery.getJSON() is sending the data of my old settings.json even after the changes has been saved. I have perused my .php file (which is generating the HTML) , as well as my included javascript and there is no other mention of another json file or any sort of clone of my json file in any related directory.
I really have no idea what is going on and I am starting to go insane. Does anyone have an idea of what the issue might be?
I dont know if it matters but I am running a XAMPP stack on my localhost. All files (index.php, scripts2.js, and settings.json) are in a directory located inside XAMPP's htdocs folder.
EDIT: Thank you all for the speedy and thorough answers, many of you answered the question I was a bout to ask next. I really appreciate it!
This is because the browser is caching the file from your first request. Simply clear the cache and run it again and the new data will be retrieved.
UPDATE:
To prevent the browser from caching this file, change your AJAX settings like so:
jQuery.ajaxSetup({ cache: false });
Before you make the getJSON call
Try clearing web cache and restart local servers if you have not already
When using jQuery.ajax() instead of the shorthand method, you can disable caching like this:
jQuery.ajax(settingsPath, {cache: false})
jQuery will append a timestamp parameter to your request URL which changes with every request and therefore keeps the browser from caching the response.
To force the browser to get a new version each time you can use cache: false in jQuery.ajax()
$.ajax({
dataType: "json",
url: settingsPath,
cache: false,
success: function (data){
$.each(data, function(index){
console.log("!"+data[index].name);
});
}
});
Pass additional parameter to your requested url which value will change with every request.So,your browser will consider it as new request every time and will not cache the data.
var random = Math.round(new Date().getTime())
var settingsPath = 'settings.json&time=' + random;
jQuery.getJSON(settingsPath, function(data) {
});
});
You can use any algoritham that generate random new value everytime for random for every request.
OR
you can have same things with jQuery#Ajax method
jQuery.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So, set the optional parameter cache to false (this value by default is always true):
$.ajax({
dataType: "json",
url: url,
data: data,
cache: false, // If set to false, it will force requested pages not to be cached by the browser
success: success
});
Therefore, your getJson becomes:
var settingsPath = settings.json;
jQuery.ajax({
dataType: "json",
url: settingsPath,
data: data,
cache: false,
success: function(data) {
jQuery.each(data, function (index) {
console.log("!" + data[index].name);
/*unrelated other stuff */
});
}
});

How do I reload a page without the user noticing?

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

How to load new content to DIV without refreshing [duplicate]

This question already has answers here:
how to reload DIV content without refreshing whole page
(8 answers)
Closed 9 years ago.
I want to load new content from the server to the DIV without refreshing the whole page.
I tried the following
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
success: function (response) {
$("#testDIV").html(response);
}
});
But the problem is the whole page is loading in <DIV id="testDIV">. I want to replace the old DIV with New DIV content returned from the server not with the whole page.
You can keep your same process sense you are interested in using AJAX directly and want to manage your done function (instead of success because .done() will replace it). Here is how...
.done(function(data) {
...
}
Inside of that done function, you can filter the page content to what you want. Simply request what you want to filter with jquery like this...
var $response = $(data);
var response_title = $response.filter(".title").html(); //I'm assuming you are trying to pull just the title (perhaps an < h1 > tag, in this little example, from the entire external page!
THEN!...
$("#testDIV").html(response_title);
With the done function, based on jQuery's API, you can use this format...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
So your final code may look something like this...
$.ajax({
type: "GET",
url: "ht.tp://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+ occasionData +"&relationship="+ forData +"#"})
.done(function(response) {
var $response = $(response);
var response_title = $response.filter(".title").html();
$("#testDIV").html(response_title);
});
I like the answer by blackhawk. It uses the existing code with slight modification.
I would just condense it to a one line change like this:
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData+"&relationship="+ forData +"#",
success: function (response) {
$("testDIV").html($(data).filter(".title").html());
}
});
The code you are displaying is actually correct.
The problem comes from what your server is providing.
What you are doing here is GETing a whole page via an AJAX call, and replacing the content of One div with that whole page.
Your server should not render the whole page for that call, but only the content of the div you wish to replace. If you are using framework like rails or symfony, they often provide an easy way to detect if the query is a normal GET request, or an AJAX call.
Basically you have 4 strategies at your disposal :
Make the requests to a specific endpoint that is used only for the ajax call and that returns the content of the div you wish to replace. And not the whole page.
Make the request to the same page, and detect if the request is a normal HTTP request or an AJAX call. Based on that, return the whole page or just the content of the div. You'll probably have to look for the helpers in your framework / toolbox documentation.
Make the AJAX request but ask for a JSON object. Transform your JSON in HTML on the client side to replace the content of the div. This is the "my app is just an API" approach. This is my personal favorite as this JSON endpoint can be used for other purposes (eg: a mobile app) since it carries only content, and not presentation. This also tends to be the fastest way in terms of performance since a significant part of the computation is done on the client side. On the con side, this requires you to write more JS.
Always render the whole page, and filter only what you need on the client side. This is balchawk approach. Benefit is that you don't have to modify your server, but you will waste processing time and bandwidth by returning a whole page, when only a subset is necessary.
$(function(){
$('.classloader.').on('click', function(e){
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
beforeSend: function() {
$("#testDIV").hide();
$('div#loading').show();
},
success: function(html){
$("#testDIV").html($(html).filter("#mainContent").html()).show();
$('div#loading').hide();
}
});
return false;
});
})

if Ajax request don't finish, html links can't click

I have a jquery ajax request in my website page, and every page i need to post this request to server to get the status. But it have a issue: after i open the page in browser, before this request return the data, my page all link can't works, they can't click.But it render normal. so anybody have a solution for that? such as: make the page load this script after page loaded or other.
$(function(){
var login_status;
$.ajax({
async:false,
url:<%= url(:login_status_header_session, :from => from_uri).to_json %>,
dataType:"html",
success:function(data, textStatus){
login_status = data;
}
});
if(login_status) {
$(".loginDetails p .login_status").html(login_status);
} else {
$(".loginWrapper").remove();
}
});
this is the login_status_header actin:
self.headers["Cache-Control"] = "no-cache, must-revalidate"
self.headers["Expires"] = "0" partial "session_header",
:format => "html"
First, remove the async:false, line. This way the interface will keep responding while the AJAX request is being processed. Second, move your checking of the result into the success function - otherwise it runs before the request finishes, and so login_status hasn't been set yet (and thus defaults to null, which is treated as false).
$(function(){
var login_status;
$.ajax({
url:<%= url(:login_status_header_session, :from => from_uri).to_json %>,
dataType:"html",
success:function(data, textStatus){
login_status = data;
if(login_status) {
$(".loginDetails p .login_status").html(login_status);
} else {
$(".loginWrapper").remove();
}
}
});
});
Without more information I can only guess, and my guess is that since you're using async: false, the interface is not responding. Is there a reason for doing the request synchronously? If not try removing async:false and see if that works.
Uhm... without examining your code in too much detail, if this is supposed to occur at soon as the page is loaded, why not just put it on the server side, and generate the proper HTML in the first place? i.e. do it with PHP or whatever you're using and forget the AJAX?

Categories

Resources