How to use AJAX

AJAX is used for loading content.

Why should you use AJAX?

AJAX can be used to…

  • Load PHP without reloading the page

Notes:

  • Do not use AJAX repeatedly. This could get you suspended on InfinityFree.

Methods and Attributes

First, you will need a JavaScript XMLHTTPRequest object.

<script>
var myReq = new XMLHTTPRequest(); // This is an object.
</script>

Here is a list of the methods and attributes.

MethodsDefined
open(method, url, a)method is for the way you would send the request, either "GET" or "POST". POST is sent through the send() method and GET is set through the URL. You could also use both. a is "true" if you want it to load with the other content and "false" if you must load it before the content. true is better.
setRequestHeader(name, value)Sets the header for the URL. name is the name of the header and value sets the value.
getResponseHeader(name)Gets the content of the response header.
abort()Stops the entire request from happening.
getAllResponseHeaders()Gets all response headers as a string.



AttributesDefined
onreadystatechangeThe function to be used when the ready state changes.
readyStateThe ready state, i.e., 4 - Finished, or 3, 2, or 1.
statusThe status, i.e., 200 (Ok), 404 (Not Found).
statusTextThe status text, like Ok (200) or Not Found (404)
responseHTMLThe HTML received
responseXMLThe XML received

Setup

You need JavaScript.

Name this file ajax.js:

function myTime() {
  // Stop the browser from caching the request
  var myRand = Math.random();
  myReq.open("GET", "time.php?rand=" + myRand, true);
  myReq.onreadystatechange = function() {
    if (myReq.status == 200 && myReq.readyState == 4) {
      var result = myReq.responseText;
      var content = document.getElementsById('content');
      content.innerHTML = result;
    }
  }
  myReq.send();
}

Name this file time.php

<?php
/* Replace with format date */
echo date(); # optional
?>

Name this file index.html

<!DOCTYPE html>
<html>
<head>
<style>
body {
  font-family: Verdana;
}
#content {
  padding: 5px;
  border: solid black 2px;
  width: 100%;
  height: 200px;
}
</style>
<script src="ajax.js"></script>
<script>
var myReq = new XMLHttpRequest();
</script>
</head>
<body>
Getting the time: <button onClick="myTime();">Get Time</button>
<div id="content"></div>
</body>
</html>

In the example above, you only need to get the time by pressing the button.

How about POST data?

If you are using POST data, then you would need:

<script>
var params = "item=6&nothing=false";
myReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myReq.setRequestHeader("Content-length", params.length);
myReq.setRequestHeader("Connection", "close");
myReq.send(params);
</script>

Hope this helps with AJAX!

4 Likes

Just as a note in your AJAX code:

You never created an XMLHttpRequest, so that script would just throw a load of errors.

9 Likes

Yes.
Here is a general tip for InfinityFree users:

DO NOT USE AJAX CONTINUOUSLY IN THE BACKGROUND
If you’re using InfinityFree, your account will get suspended in no time

9 Likes

I just realised that, whoops.

Yes, good point.

ajax the best way to clean out your account :smiley:
https://www.youtube.com/watch/Ir25Eu6iQdI

sorry I couldnt help myself

3 Likes

Oh my god lol :smiley:
lmaoooooooo

1 Like

AJAX vs jQuery AJAX
  • AJAX
  • jQuery AJAX
0 voters

A part of being a good programmer is to reduce your usage of frameworks and code things yourself as much as you can. (Unless you’re either a basic programmer or that thing is very hard to develop like Electron.js)

  1. Because you’ll know how your own code works better than frameworks’ source codes, hence it’ll be easy to debug your own code when a problem occurs.
  2. Since frameworks contain lots of functions and codes, their source files will be fat and reduce the speed of your website’s loading. So it doesn’t make sense to don’t write 20 lines of code and use a big sized framework just for ajax.

:neutral_face: For example beside the rain effect, my whole website is made with pure javascript.

1 Like

Yes, I do know how to use AJAX, I prefer jQuery, as it saves me lots of time :smiley:
Usually, I reduce my usage of frameworks. One reason why people might find me weird is that I rarely use Angular or React.

Primarily, the only Javascript framework I use is jQuery.
Otherwise, I stick to the good old Javascript.

When it comes to CSS frameworks, that’s a different story.
I use Materialize, and bootstrap primarily, and sometimes I try out new frameworks…
I’ve made my own framework :smiley:

Usually for backend, I don’t use any frameworks.

I disagree with you there.

Even to an experience developer, using a framework brings many benefits. It saves you from having to re-invent the wheel every time, and the framework itself is generally developed, tested and used by a lot more people than your code will. That’s a lot of labor which you can just get for basically free.

I’m not using Laravel for the client area because I don’t how how to write a web application myself. I’m using Laravel because the time it would take me to develop my own URL router, request/response abstraction, ORM (with all the bells and whistles that includes), event bus, queue system and so on and to build it in a robust and clean way would take me more time than the entire client area ever did. And I get all of those things for free now.

I’ve worked on large applications without frameworks too. They all tended to fall apart at some point because of they cut corners in the design of the overall architecture, which caused so much technical debt it ground development to a halt, created many bugs, etc.

Don’t think that just because frameworks are big that they are always slower. When your application grows larger, you’ll inevitably need the complexity too, and you’ll build in a worse way than the framework developers did. And your site will be slower because of it.

To many companies, there are many things that are more important than raw performance. Being able to develop and iterate on products quickly, using scarce developers efficiently is far more important. If they want a faster site, it’s cheaper to just buy faster and more powerful servers.

8 Likes

Ah, I might have gone wrong with first statements. (causing misunderstanding)

I agree, frameworks make work much easier for everyone and developers, good for saving time. but might be a waste if you use it for just a few simple stuff, I mentioned “reduce using it as much as you can”. For example what does it mean to use packages and third party frameworks for such simple stuff?

This looks quite complex to develop such thing, so using a framework should be required for this, I used to work with this before and I ended up with that i don’t really need this for my simple project (not bigger ones)

Oh, I meant using a big framework just to don’t write 20 lines, I would use 20 lines rather than using a framework for it, what’s the need when i don’t need all of its features? You should use a framework if you need most of its features.

Well, I don’t think that’s wise if you’re using a framework just because you don’t know how it works (not to reduce the speed), if there’s a speed quiz for coding projects, I’d first look into whatever it is complex or not. Having skills regarding a programming language before using its frameworks is important, I wouldn’t use a framework if I don’t know how its root language works.

Probably because I’m that kind of person who deals with Spaghetti better than blocks.

4 Likes

Ah right, that explains.

The things you’re talking about are things which I would call “libraries”, not “frameworks”. A library just provides a bit of functionality, a framework actually dictates how your software is organization.

Excessive use of third party libraries is indeed an issue, it can make a project brittle especially if the library isn’t well written.

5 Likes

My bad actually. I just learned a new thing and sorry for causing misunderstanding… As usual.

3 Likes

Yes,
Bootstrap is a framework,
JQuery is a library.

2 Likes

Even node.js (which I’m using for my projects) is a framework.

I was thinking that framework and library are the same.

2 Likes

It seems like so…

Wait, frameworks (like bootstrap) contain libraries, don’t they? Bootstrap contains jQuery. Bootstrap is a framework, jQuery is a library.

2 Likes

yeah.

:neutral_face: my weird opinions.

1 Like
  1. Yes, I agree, there’s no reason, like, use a library that is 260 KB and then create AJAX requests. Most of the features you won’t need; and, hey, what do you say if you used a function and the entire webpage crashes?

  2. Like, for example, you just use a library that is up to 985 KB and wait, like, 79 seconds for it to load.

1 Like

I either wouldn’t use it or try to debug it.

Yeah, I prefer not to use libraries as I know how to code (most of) things. That’s why you may not see that I’m using library for my projects.

But when it comes to something like game engines, then I use a framework or library. Although I’ve coded my own frameworks/libraries for js game development but never uploaded to github because… Who really cares about my stuff?

1 Like