Adding a loading text while an AJAX function is executing - javascript

I've been trying to add a loading text that would display while an AJAX function is being executed for a long while now, and all of my attempts (which includes using the ajaxStart and ajaxStop, among other things) haven't been working at all. Any help is appreciated!
Here is the webpage that the script in question is located on, if you want to see it in action. The way it works is that you enter in a url and the function will grab the meta tags of that URL.
Meanwhile, here is the relevant HTML, Javascript, and PHP:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Keywords Grabber</title>
<script src="ajax.js"></script>
<script>
function display(content) {
document.getElementById("displaydiv").innerHTML = content;
}
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var url = document.getElementById("txt1").value;
doAjax("metatags.php", "url=" + url, "display", "post", 0);
}
}
</script>
</head>
<body>
http://<input type="text" id="txt1" value="" />
<input type="button" id="btn1" value="Get Keywords" />
<h3>Keywords Received:</h3>
<div id="displaydiv"></div>
</body>
</html>
JavaScript
function getXMLHttpRequest() {
try {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return new ActiveXObject("Msml2.XMLHTTP");
}
}
catch(e) {
return new XMLHttpRequest();
}
}
function doAjax(url, query, callback, reqtype, getxml) {
var myreq = getXMLHttpRequest();
myreq.onreadystatechange = function () {
if (myreq.readyState == 4) {
if (myreq.status == 200) {
var item = myreq.responseText;
if (getxml == 1) item = myreq.responseXML;
eval(callback + '(item)');
}
}
}
if (reqtype.toUpperCase() == "POST") {
requestPOST(url, query, myreq);
} else {
requestGET(url, query, myreq);
}
}
function requestGET(url, query, req) {
var myRandom = parseInt(Math.random()*99999999);
if (query == '') {
var callUrl = url + '?rand=' + myRandom;
} else {
var callUrl = url + '?' + query + '&rand=' + myRandom;
}
req.open("GET", callUrl, true);
req.send(null);
}
function requestPOST(url, query, req) {
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(query);
}
PHP
<?php
$tags = #get_meta_tags('http://'.$_REQUEST['url']);
$result = $tags['keywords'];
if(strlen($result) > 0) {
echo $result;
} else {
echo "No keywords metatag is available.";
}
?>

something like this
<div id="loading" style="display:none;">loading</div>
Javascript
$('#loading').css('display', 'block');
$.post(url, {}, function(data){
$('#loading').css('display', 'none');
});

Related

Probleme with ajax

I need help with my project, i have to do an 'drag n drop' zone, and, when the image is droped, it must be saved on the server (via PHP, which I succeeded), but also appear on the HTML thanks to the response from AJAX via PHP. I don't know what to do anymore, here is some code bugs. Each time I see the JS alert announces: 'An exception is produced: undefined'. I don't use Jquery or anyting else, it's just vanilla PHP and Javascript, Thanks for your help
Sorry for my bad English, I'm french :)
my code :
<body onload="init()" >
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p>Drop file here</p>
<p>or</p>
<p><input type="button" value="Select File" onclick="file_explorer();"></p>
<input type="file" id="selectfile">
</div>
</div> <br>
<img id = "imageSource" src="uploads/"/>
<script type="text/javascript">
var fileobj;
var url = "ajax.php";
function upload_file(event) {
event.preventDefault();
var target = document.getElementById ("drop_file_zone");
for (var i = 0; i < 1; i++) {
var fileobj = event.dataTransfer.files[i];
ajax_file_upload(fileobj);
}}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function init() {
request = new XMLHttpRequest();
var x = document.getElementById("imageSource");
}
function prepareData() {
let url = "ajax.php";
makeRequest( url, fileobj );
}
function ajax_file_upload(file_obj) {
request.onreadystatechange = alertContents;
var formData = new FormData();
formData.append('file', file_obj);
request.open('POST', url)
request.send(formData)
}
function alertContents() {
try {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var reponse = JSON.parse( request.reponseText);
x.setAttribute("src", 'uploads' + reponse.text);
//document.getElementById("imageSource").src = reponse.text;
} else {
alert("Un problème est survenu au cours de la requête.");
}
}
}
catch( e ) {
alert("Une exception s’est produite : " + event.description);
}
}
</script>
</body>
</html>
And my PHP
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'. $_FILES['file']['name']);
$test = '{ "text":"uploads/'.$_FILES['file']['name'].'"}';
echo $_FILES['file']['name'] ;

How to get HTML source with JavaScript?

I am trying to get HTML source with JavaScript:
Why this does not work?:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function MyGetHTML()
{
$.get("www.example.com/test1.html", function(data){
return data;
});
}
</script>
</head>
<body>
test 30.9.2015
<script>
alert(MyGetHTML());
</script>
</body>
</html>
(Below, i'm assuming that you need to get content from filen IN your source, from the same origin of your page.)
Your code doen't works because the the return of your MyGetHTML method is the get request itself, and the success callback of your request returns the data.
You could do:
function MyGetHTML(){
$.get("www.example.com/test1.html", function(data){
//alert(data);
//or use console.log() instead.
console.log(data);
});
}
And then
MyGetHTML(); //This will log your data after the succesfull request.
Further reading: https://api.jquery.com/jquery.get/
Hint on your use case:
A simple tutorial from Tuts+ on making simple ajax requests.
With pure JS:
load('test.html', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Or with jquery library
$('#container').load('test.html');
Because you're returning to the get not the function itself. Try like this:
function MyGetHTML()
{
var datum = '';
$.get("www.example.com/test1.html", function(data){
datum = data;
});
return datum;
}

Data manipulation for Instgram API with Ajax and JSON

Im trying to retrieve users from Instagram API whose names contain the certain word from a JSON file , by using this jQuery
I had to make a PHP file as a server in my local host i named it ' get_info.php' and it return an Array of elements
but for some reason I can't seem to display the output after manuplating the data :(
I'm new to Ajax and JSON, could you possibly help me find the error in my code?
here's my JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" >
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var jsonObj ;
var q = document.getElementById('keyword').value;
ajaxRequest.open('POST', 'get_info.php?keyword='+ q , true);
// callback function to handle the server response
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
if ((ajaxRequest.status >= 200 && ajaxRequest.status < 300) || ajaxRequest.status === 304) {
var jsonObj = ajaxRequest.responseText;
jsonStr = JSON.parse( jsonObj );
}
}
}
$(document).ready(function () {
$("#submit").click(function(){
$.ajax({
type: 'GET',
url:'get_info.php',
data: { keyword: q },
success: function(jsonStr) {
$.each( jsonStr.data , function(index, element) {
var res ;
res += '<img src="'+element.username+'"/>';
res += '<img src="'+element.profile_picture+'"/>';
});
$("#photos").html(res);
}
});
});
});
}
</script>
The HTML only has these tags.
<form id="form" method="POST" onclick="ajaxFunction();" >
<input value="" id="keyword" type="text" required>
<input value="search" id="submit" type="submit" >
</form>
<div id="photos"> </div>
To avoid confusion, jquery ajax is enough
<script>
$(document).ready(function () {
var q = document.getElementById('keyword').value;
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
type: 'GET',
url:'get_info.php',
data: { keyword: q },
success: function(jsonStr) {
var element = jsonStr.data;
var res ;
for(var i = 0; i<element.length;i++) {
res += '<img src="'+element[i].username+'"/>';
res += '<img src="'+element[i].profile_picture+'"/>';
}
$("#photos").html(res);
}
});
});
});
</script>
Remove the onclick from form
<form id="form" method="POST" >
<input value="" id="keyword" type="text" required>
<input value="search" id="submit" type="submit" >
</form>
<div id="photos"> </div>
Check and let me know what you are getting in the console
<?php
//Get data from instagram api
$keyword = $_GET['keyword'];
if(!isset($_GET['count'])) $count = 20;
else $count = $_GET['count'];
//Query need client_id or access_token
$query = array(
'client_id' => '',
'count' => $count
);
$url = 'https://api.instagram.com/v1/users/search?q='.$keyword.'&'.http_build_query($query);
try {
$curl_connection = curl_init($url);
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
//Data are stored in $data
$data = curl_exec($curl_connection);
curl_close($curl_connection);
echo $data;
} catch(Exception $e) {
return $e->getMessage();
}
?>

Ajax Javascript Scope Issues

I am having a javascript scope issue I want to take the responce text from the ajax call and place it into a global variable. Then process the JSON in another function here is my code.
var JSONDATA = "not gatherd";
var ajaxCalls = (function(){
var ajaxer = {
defaults:{
url:"test.php",
DirectHTML: true,
element:"#ajaxerizer"
},
setup:function(setup){
var defaulLengther = this.defaults
for (var key in defaulLengther)
{
if(setup.hasOwnProperty(key))
{
this.defaults[key] = setup[key];
}
}
if(this.defaults.DirectHTML === false)
{
if (window.XMLHttpRequest) {
this.ajaxRequester = new XMLHttpRequest();
}
if (window.ActiveXObject) {
this.ajaxRequester = new ActiveXObject("Microsoft.XMLHTTP");
}
this.ajaxRequester.open('POST', this.defaults.url, true);
this.ajaxRequester.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.ajaxRequester.send();
}
this.callIt();
},
callIt:function(){
if(this.defaults.DirectHTML === true)
{
$(this.defaults.element).load(this.defaults.url);
}
if(this.defaults.DirectHTML === false)
{
this.ajaxRequester.onreadystatechange = function(){
if (this.readyState == 4) {
//This is where I have trouble
alert(this.responseText);
JSONDATA = this.responseText;//This is the data I want to process and use
alert(JSONDATA);
}
}
}
}
}
return ajaxer
})();
Here is the Index
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="simpleHtmlAjax.js"></script>
</head>
<body>
<div id="ajaxerizer">
<script>
ajaxCalls.setup({
url:"json.php",
DirectHTML: false,
});
alert(JSONDATA);
</script>
</div>
</body>
</html>
and the JSON data
<?php
$json = array("one" => 1,"two" => 2,"three" => 3,"four" => 4);
echo json_encode($json);
?>
Thank you for any help.
You're already including jQuery in your HTML, so why not just use jQuery's AJAX helper functions to automatically process the JSON data?
$.post("json.php", function (data) {
// do something with data, which should be a plain JS object:
// {"one":1, "two":2, "three":3, "four":4}
}, "json");

JavaScript + Querystring + div

How to load content in to a html page. please note IM not allowed to use php or C. Only javascript and html.
for example
load Page B in to Page A
http:myweb.com/index.html?load=pageb
thank you.
Issue an AJAX request to Page B
Get the contents using responseText
Display the contents inside a div using innerHTML property.
If you can use a js framework then I would suggest jQuery and #marcgg's answer will do it.
Just plain JavaScript:
<html>
<head>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
function createRequestObject() {
var ro;
// Mozilla, Safari,...
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
if (ro.overrideMimeType) {
ro.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ro) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
return ro;
}
function sndReq(param,server,handler) {
//location.href = server+"?"+action; //uncomment if you need for debugging
http = createRequestObject();
http.open('GET', server, true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.onreadystatechange = handler;
http.send(param);
}
handler_function = function()
{
if(http.readyState == 4)
{
if (http.status == 200)
{
document.getElementById("your_div_element").innerHTML = http.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<div id="your_div_element"></div>
<script>
var getvars= getUrlVars();
sndReq(null, getvars['action'], handler_function);</script>
</body>
</html>
html:
//Page A
<html>
<head><title>Page A</title></head>
<body>
<div id="pageB"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pageB').load('pageb.html')
});
</script>
</body>
</html>
Using jQuery:
$.ajax({
type: "POST",
url: "http://some.com/page.html",
success: function(msg){
alert( "here's your data: " + msg );
jQuery("#yourDivID").html(msg);
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
edit: added how to put it into a div

Categories