Say I have a URL:
hello
When someone clicks this link, I want it to fire a script off using ajax so we can track how many times this link has been clicked behind the scene.
My page is called track.php which will pull the ID 4298 via GET, track.php?id=4298 and then it updates the database respectively.
How would I go about coding this in javascript/ajax so upon this link being clicked, in form of an "onclick event", this track.php will be ran behind the scene?
Keep in mind that to do a request in the background, you will need to wait for the AJAX response to follow the click. If that's what you want, then using jQuery:
<script type="text/javascript">
var track = function(obj) {
$.ajax({
url: "track.php?id="+obj.id,
success: function(){
window.location.href = obj.href;
}
});
return false;
};
$('a').click(track);
</script>
<script>
window.doTheThing = function() {
//send a request to your 'track.php' URL here
};
</script>
hello
var anchors = document.body.getElementsByTagName('a');
for (var i = 0, anchorsLength = anchors.length; i < anchorsLength; i++) {
a.onclick = function(event) {
event.preventDefault();
var id = this.id,
xhr = new XMLHttpRequest();
xhr.open('track.php?id=' + id);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == 200) {
window.location = this.href;
}
}
}
xhr.send();
}
}
Keep in mind that XMLHttpRequest() doesn't support older versions of IE.
If you are using jQuery, use the library's AJAX functions.
Related
so I am loading a portion of a page using jquery/ajax.
On the page the user sees, there is a "menu" where they select the date of the signup form they want to see. All the forms are hosted on another page, each one inside a div id'd with the respective date of the form. When the user clicks and item on the menu, there is an ajax call that displays the correct form on the user's page, pulling it from the other page by it's parent div and id.
The plugin I am using for the signup forms (it is a Wordpress site) has the page reload when you click Sign up, which then takes you to a form to fill out. I have it so that the user's page does not reload, but via ajax shows the form. This all works great - the only problem now is when the user clicks to submit the form. This should be a normal form submit not using ajax, as I am not sure how to modify the plugin code to utilize it. For some reason, the form is never actually submitted although the user's page does reload.
*NOTE: I am currently using the same exact signup form for each date, but once it is functional it will be a different signup form for each. This should not effect any functionality.
link to page user sees: summitsharks.net/volunteer-signup-page
link to page forms are hosted on: summitsharks.net/formhost
jquery/ajax code:
;(function($){
var ahref1;
$(document).ready(function(){
$(document).on('click', '.entry-content li a', function(e){
e.preventDefault();
ahref1 = $(this).attr('href');
$('#formloader').load('/formhost ' + ahref1);
return false;
});
});
$(document).ready(function(){
$(document).on('click', '.entry-content #formloader a', function(e){
e.preventDefault();
var ahref2 = $(this).attr('href');
$('#formloader').load(ahref2 + ' ' + ahref1);
return false;
});
});
})(jQuery);
PHP code of file that (I think) handles form submit:
http://pastebin.com/PeXB4Afi
I am looking for a solution that successfully signs the user up. If somebody knows how to alter the plugin code to accept ajax submission, or normal submission that actually works, either one is perfectly fine with me.
Thanks a lot for looking through and thanks in advance for your help!
The form is expected to be posted from it's original URL, including the HTTP GET parameters ?sheet_id=1&task_id=1&date=2016-06-30. Updating the form's action attribute to make it post to the proper URL can be done by changing
$('#formloader').load(ahref2 + ' ' + ahref1);
to
$('#formloader').load(ahref2 + ' ' + ahref1, function() {
$('#formloader form').attr("action", ahref2 + ' ' + ahref1 );
});
However, using AJAX to post the form, this can be skipped:
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
})
The utility method formdata (see code snippet below) converts jQuery's serializeArray() result to a proper hash.
In the working example below, I've moved the installation of form click handlers into the .load completion handler, rather than relying on jQuery to fire a second document ready event after injecting the form.
;jQuery(function($) {
$('.entry-content li a').off('click').on('click', function(e) {
var ahref1 = $(this).attr('href');
$('#formloader').load( "/formhost " + ahref1, function() {
$('.entry-content #formloader a').off('click').on('click', function(e) {
e.preventDefault();
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
});
return false;
});
});
return false;
});
});
function formdata(form) {
var data = {};
for ( var i in d = form.serializeArray() )
data[d[i].name] = d[i].value;
return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE: Here is a code snippet that can be pasted in the browser's Javascript console:
$ = jQuery;
$('.menu-volunteermenu-container li a').off('click').on('click', function (e) {
loadFormSelector($(this).attr('href'));
return false;
});
$('#formloader').on('load', function(){console.log("FORMLOADER UPDATD")});
function loadFormSelector(ahref1)
{
console.log("Loading form selector");
$('#formloader').load('/formhost ' + ahref1, function ()
{
console.log('form selector loaded');
$('.entry-content #formloader a').off('click').on('click', function (e)
{
e.preventDefault();
loadForm(ahref1, $(this).attr('href') );
return false;
});
});
}
function loadForm(ahref1, ahref2)
{
var ahref = ahref2 + ' ' + ahref1;
console.log('Loading form', ahref);
$('#formloader').load(ahref, function () {
console.log('form loaded', arguments);
$('#formloader form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: ahref,
type: 'POST',
data: $.param(formdata($(this))),
success: function (data, status, jqXHR) {
$('#formloader').html( $(data).find( ahref1 ) )
}
});
return false;
});
$('#formloader a').on('click', function () {
loadFormSelector(ahref1);
});
return false;
});
}
function formdata(form) {
var data = {
};
for (var i in d = form.serializeArray())
data[d[i].name] = d[i].value;
return data;
}
It is refactored to show the 2-layer approach more clearly.
I am trying to write a function that will call getproduct.php?id=xxx when clicked. I can get the innerHTML portion to appear, but how do I also call the php page that actually does the work?
var id = id;
document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
url = getproduct.php?id=id;
you can call or load php page inside a div using this line as :-
$("#content_div").load("ajax/page_url.php");
the "ajax/page_url.php" its a relative path of php file.
so here you can replace it with external url as well.
please share you knowledge if i am wrong.
You can do it with jQuery for example.
var id = 1;
$('#digital_download').html('Downloading...'); // Show "Downloading..."
// Do an ajax request
$.ajax({
url: "getproduct.php?id="+id
}).done(function(data) { // data what is sent back by the php page
$('#digital_download').html(data); // display data
});
There are many ways by which you can load a page into a division .
The very method is
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('digital_download').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'getproduct.php?id=' + id,true);
xmlhttp.send();
}
this is a typical method with no external reference.
If you go with reference then there are 5 ways to make a ajax call with jQuery
load(): Load a piece of html into a container DOM.
jQuery.getJSON(): Load a JSON with GET method.
jQuery.getScript(): Load a JavaScript.
jQuery.get(): Use this if you want to make a GET call and play extensively with the response.
jQuery.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
jQuery.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the
fly.
Edit: the original question didn't reference jQuery. Leaving this answer here as others may find it useful.
Here's how you would do this using the XHR object for an ajax request without jQuery or Prototype or other JS library.
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('digital_download').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'getproduct.php?id=' + id,true);
xmlhttp.send();
}
Hi You can call the below function to perform this it loads the data from server on success you can create fail function as well
function setValue(Id) {
document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
var data1 = {
message: Id,
};
$.ajax({
data: data1,
type: 'GET',
url: "http://urltoscript/index.php",
cache: false,
dataType: "json",
crossDomain: true,
success: function(data) {
console.log("Response for cancel is: " + data);
document.getElementById("digital_download").innerHTML = data
}
});
}
You can use get or post request using query
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
example
i want to be able to make the submit button in jquery form plugin disabled and then when the response is retrieved, it should become enable. i am trying thru the code below but as soon as in the onlick event i disabled the button it somehow stops the submission. although i am able to change the class of the button.
what am i doing wrong?
code is like this:
function timing(){
d=Math.round(new Date().getTime() / 1000);
$('input[name=timedate]').val(d);
var btn1 = $('#post_global');
btn1.val('posting');
btn1.removeClass('t_s').addClass('t_sDisabled');
btn1.prop('disabled',true);
}
(function() {
$('form').ajaxForm({
dataType: 'json',
beforeSubmit: validate,
success: processResponse
});
})();
function processResponse(data) {
document.getElementById('upfile').value = "";
document.getElementById('fileinfo').innerHTML = "";
document.getElementById('txt1').value="post anything...";
var status = $('#status');
if(data.errors == ""){
status.hide().html(data.htmlResponse).fadeIn(1000);
} else{
alert(data.errors);
}
var btn2 = $('#post_global');
btn2.val('post');
btn2.removeClass('t_sDisabled').addClass('t_s');
btn2.prop('disabled',false);
}
This is the answer that I think you're looking for. If you want more, just comment what you want below:
$("#btn2").click(function() {
$('#btn2').attr("disabled", true);
//Do the request here
$('#btn2').attr("disabled", false);}
Possibly this?
function timing(){
d=Math.round(new Date().getTime() / 1000);
$('input[name=timedate]').val(d);
var btn1 = $('#post_global');
btn1.val('posting');
$('#btn2').attr("disabled", true);
}
(function() {
$('form').ajaxForm({
dataType: 'json',
beforeSubmit: validate,
success: processResponse
});
})();
function processResponse(data) {
document.getElementById('upfile').value = "";
document.getElementById('fileinfo').innerHTML = "";
document.getElementById('txt1').value="post anything...";
var status = $('#status');
if(data.errors == ""){
status.hide().html(data.htmlResponse).fadeIn(1000);
} else{
alert(data.errors);
}
var btn2 = $('#post_global');
btn2.val('post');
$('#btn2').attr("disabled", false);
}
This is my ajax function
<script language="JavaScript" type="text/javascript">
var num = 1;
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (++num)); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
Now i have this too find the correct div/class to run the ajax function in:
$('.eventcontainer.button').click(function() {
$.post('javas.php', function(data) {
$(this).parent('div').find('.status').html(data);
})
});
However im not sure where to implement this in my code
It's not a good idea to write your own ajax-request if you want to run your code on multiple browsers. If you have jQuery on your hand and you want a post ajax-request use the jQuery function:
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
example for document ready to use:
function fooBar() {
//some code
}
$(document).ready(function(){
// all your jquery in here
$('body').hide().fadeIn(2000);
// or call your own functions
fooBar();
});
You can use this:
$(function(){
$('.eventcontainer.button').click(function() {
$.post('javas.php', function(data) {
$(this).parent('div').find('.status').html(data);
})
});
})
So I have a table pulling information from a database and I was wondering how I could make it refresh its information without reloading the whole page.
You'll need a getTable.php page that displays your table, and nothing else: no headers, footers, etc.
PHP (getTable.php) - this can be any server side code (asp, html, etc..)
<?php
echo '<table><tr><td>TEST</td></tr></table>';
?>
Then, in your JS, you can easily refresh the table by using the load() method:
HTML
<div id="tableHolder"></div>
JS
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>
Use ajax, following example is in jQuery:
$(function() {
var prevAjaxReturned = true;
var xhr = null;
setInterval(function() {
if( prevAjaxReturned ) {
prevAjaxReturned = false;
} else if( xhr ) {
xhr.abort( );
}
xhr = $.ajax({
type: "GET",
data: "v1="+v1+"&v2="+v2,
url: "location/of/server/script.php",
success: function(html) {
// html is a string of all output of the server script.
$("#element").html(html);
prevAjaxReturned = true;
}
});
}, 5000);
});
The success function assumes that your server script outputs the html that you want to replace in the element with id 'element'.
You should have a page that return the information and pull data using Ajax / jQuery.
<div class="result"></div>
setInterval(function() {
$.get('table.php', function(data) {
$('#result').html(data);
});
}, 5000);
Here is another option for you to use. This solution is using an IIFE which is preferred over setInterval. You can read more about IIFE at the link above.
JAVASCRIPT:
var $results = $('#results'),
loadInterval = 5000;
(function loader() {
$.get('script.php', function(html){
$results.hide(200, function() {
$results.empty();
$results.html(html);
$results.show(200, function() {
setTimeout(loader, loadInterval);
});
});
});
})();
HTML:
<div id="results"></div>
setTimeout(function(){
jqueryFunction(Args);
},100);
will work...
100 = 100 milliseconds
The following works with JQuery Datatables 1.10
`var tableName;
//Set AJAX Refresh interval.
$(function() {
setReloadInterval(10); //Refresh every 10 seconds.
}
//Because function takes seconds we * 1000 to convert seconds to milliseconds.
function setReloadInterval(reloadTime) {
if(reloadTime > 0)
internalId = setInterval("reloadTable()", (reloadTime * 1000);
}
//Auto Refresh JQuery DataTable
function reloadTable() {
tableName.ajax.reload();
}
//Table defined...
$(document).ready(function () {
tableName = $('#tableName').DataTable({
"sAjaxSource": "/someUrl",
});`