2

Ok, pardon the dramatic title, but making AJAX calls has to be the most confusing thing to do for me in my coding journey so far.

I’m completing a project where a user enters a keyword into a search bar and results are returned using the Wikipedia API. I’ve watched several tutorials on making AJAX calls and gone over the documentation, but it’s just not clicking.

The main questions that go on in my head when trying to figure this out:

What the heck is supposed to go into an AJAX call and how do I find out? I've gone over the documentation and know that there are a number of settings that can be specified in an AJAX call, but how do I figure out what settings I need to use? What do these settings mean?!

I know this might be a stupid question to most, but I'm just starting out and want to learn!

This is honestly all I have and currently understand:

$(function() {

  // make ajax request
  $.ajax({
    url: "https://en.wikipedia.org/w/api.php", // this is the API endpoint
    dataType: json;
  });

});
user8473431
  • 121
  • 2
  • 17
  • Give us some code example – Nebojsa Nebojsa Sep 18 '17 at 13:04
  • It is not different than submitting a form to the server. You put the data you want the request and it is sent up. Plenty of tutorials on Ajax since 2005 when I wrote a book on it. What settings are you confused with? All you probably care about right now is method, data, success, and error. – epascarello Sep 18 '17 at 13:05
  • updated with the code i have so far – user8473431 Sep 18 '17 at 13:07
  • So you are missing success or done() Look at the example code under the yellow box: http://api.jquery.com/jquery.ajax/#jqXHR or the examples http://api.jquery.com/jquery.ajax/#entry-examples – epascarello Sep 18 '17 at 13:08
  • To find our what exactly goes inside an Ajax request you have to read the doc of the api provider. They might request you to use this or that argument and what you can specify and so on. – user5014677 Sep 18 '17 at 13:29

4 Answers4

2

What is an AJAX request?

Ajax is a set of web development techniques using many web technologies on the client side to create asynchronous web applications.

With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.

Think of an AJAX request the same way you would think about an HTTP request. You are simply requesting files, text, or any other resource that is located on a server.

Why should I use AJAX requests?

They provide benefits to user experience, functionality, and performance.

For example, let's say you are trying to build a text-messaging application. To build something like this, you will need to have the new text messages appear on the page without the user needing to do something. This is called: Dynamically loaded content.

This can be achieved with AJAX.

How can I make an AJAX request?

By using jQuery, a framework for Javascript, we can make the experience alot easier. Here's a basic AJAX request with jQuery AJAX.

$.ajax({ *properties* });

The AJAX method takes some properties:

  • URL: The source you want to pull information from.
  • Method: The request method you want to use. (POST, GET, PULL)
  • Data: The data you wish to send to the source.

There's a lot more, however for simplicity reasons I am only going to name those.

Let's say you want to create a login system without a page refresh. This is really simple!

First, we need to setup the backend.

if (isset($_POST['username']) && isset($_POST['password'])) {

    $username = $_POST['username'];
    $password = $_POST['password'];

    if ($username == 'USER' && $password == 'PASS') {
        echo('success');
    } else {
        echo('failure');
    }
}

Save this inside a file called login.php.

Second, let's setup the frontend.

<form method="POST" action="login.php">
    <input name="username" type="text" placeholder="Username">
    <input name="password" type="password" placeholder="Password">
</form>

We now have a foundation for an ÀJAX request. Before I implement it, let's talk about what the PHP and HTML are doing.

The HTML has a form, which has two inputs, username and password. As we can see from the attributes, the form will send the data to login.php using the POST method. The PHP will check if they're set, and if they're correct.

Unfortunately, this setup causes one of the most hated website features. THE REFRESH.

How can we solve this? AJAX Baby!

First, remove the attributes on the form.

<form>
    <input name="username" type="text" placeholder="Username">
    <input name="password" type="password" placeholder="Password">
</form>

Second, add a submit event listener.

$('form').submit(function(event) {


});

Third, add a preventDefault() on the event to stop the page refresh.

$('form').submit(function(event) {

    event.preventDefault();

});

Fourth, get the form values.

$('form').submit(function(event) {

    event.preventDefault();

    var $form = $(this);
    var username = $form.find('input[name="username"]').val();
    var password = $form.find('input[name="password"]').val();
});

Fifth, add the AJAX.

$('form').submit(function(event) {

    event.preventDefault();

    var $form = $(this);
    var username = $form.find('input[name="username"]').val();
    var password = $form.find('input[name="password"]').val();

    $.ajax({
        url: 'login.php',
        method: 'post',
        data: { username: username, password: password },
        success: function(response) {
            alert(response);
        }
    });

});

This will send the data to the login.php file on form submission. If the values are set, the PHP will echo (or give the data to AJAX) the status. It will return success or failure depending on the username and password accuracy.

Hope this helped! It took forever.

Lars Peterson
  • 1,508
  • 1
  • 10
  • 27
1

Ok, I'm not an "Ajax master" but here is an example of how you can use it, I hope it will help you.

Imagine you have a simple log in form in HTML :

<form method="POST" name="connexion" id="connexion">
  <input type='text' id='add_url' name="add_url" required/>
  <label for="add_url">Add URL</label>
  <input type="submit" name="sub_add" value="Add">
</form>

Now I have a.js file where I want to check if the value added is good and I want to show a result if it's okay, but I don't want to reload my page. So I will make an Ajax call :

function add_url () {
  var data = $('input[name = "add_url"]').val(); // Here I select my input "add_url" and put the value on my var "data"

  $.ajax({
    type: "POST",          // How I want to send my data on my php page
    url: "mypage.php"      // the name of the file where I will use this data
    data: {"add" : data},  // The data I will use in my php, with the name "add"
    dataType: "json",      // The type of data I want to receive
    success: function(response) {

    // If my ajax call worked, I will do some code here

    },
    error: function (xhr, status, msg) {

   // If my ajax call failed, I want to know why so I will use "xhr, status and msg" to have some information about why it failed

    }
  });
}

Now in my php, I will use the data send with ajax and build a JSON response :

// mypage.php
<?php
$url = $_POST['add']; // I put the data send in my var $url

// you do some code here with your data, for example I add the new URL in some array and the new array is $data

$result['status'] = "success";      // All is ok so I say it
$result['message'] = "All is ok !"  // I add some message
$result['data'] = $data;            // The data I will use in my JS

$result = json_encode($result);     // I need a JSON as response, remember?

echo $result;                       // My response

?>

Now in my ajax function, if all is ok I can use what I send in the success part:

 success: function(response) {

    if (response.status === "success") {   // I test if the status I send is "success"
      alert(response.message);             // The message I send
      console.log(response.data);          // I want to see in my console the data I receive
    }

 }

This is just an example, but I hope you have a better idea of how to use it :)

Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36
  • Why confuse this with php? OP was already confused, now probably moreso! – Jamiec Sep 18 '17 at 14:02
  • You think? I though using Ajax with php file was the simpliest way to understand it ! That's how they explain it to me in class. I hope you are wrong about OP :s – Mickaël Leger Sep 18 '17 at 14:12
  • They were trying to use the [wikipedia API](https://www.mediawiki.org/wiki/API:Main_page) - why not just give an example of calling that? Any way this is closed so probably no point – Jamiec Sep 18 '17 at 14:14
0

It is hard to answer this question here and write about the use of all configuration of AJAX. I would suggest you to learn about HTTP Request in general. How it works and what all headers are there and their use. There is this nice tutorial on HTTP requests and AJAX . Please look into https://code.tutsplus.com/tutorials/a-beginners-guide-to-http-and-rest--net-1634 . Keep on using and exploring the AJAX calls. You will learn it with the time.

Vijay Rathore
  • 593
  • 8
  • 16
0

This question is closed so I hope other newbies who are learning about ajax and are not looking for jQuery solution will get some idea from this page.

Asynchronous Javascript And XML (AJAX) is something that runs without stopping your entire code execution (in short, AJAX is asynchronous).

In normal JavaScript, codes are executed synchronously. This means that one code cannot be executed before the codes before it have been executed.

However, in AJAX, the codes after ajax code are still executed, even though the ajax code has not finished executing.

jQuery's $.ajax method is basically the over-simplified JavaScript below:

function ajax(settings){
    var ajax = new XMLHttpRequest(),     // initializing AJAX constructor
        header = 'application/x-www-form-urlencoded';
    ajax.addEventListener('readystatechange', function(e){
        if (this.readyState == 4){       // if request is ready
            if (this.status == 200)      // if request is successful
                settings.success(this);  // run `success` function
            else                         // if request is unsuccessful
                settings.fail(this);     // run `fail` function
        }
    });
    if (settings.dataType === 'json') header = 'application/json';
    ajax.open(settings.type, settings.url, settings.async);  // opens connection with the server
    ajax.setRequestHeader('Content-Type', header);           // sets ajax request header
    ajax.send(settings.data);                                // sends data to server
}

ajax({
    type: 'POST',
    url: 'api.php',
    dataType: 'json',
    data: {},
    async: true,
    success: function(e){
        alert('Ajax successful');
    },
    fail: function(e){
        alert('Ajax failed');
    }
});

The code above explains what AJAX is. The code below explains what asynchronous mean.

If ajax is set to be synchronous:

var a = 0;

a += 1;

ajax({
    type: 'POST',
    url: 'api.php',
    dataType: 'json',
    data: {},
    async: false,          // async is set to false
    success: function(e){
        a += 10;
        console.log(a);
    },
    fail: function(e){
        alert('Ajax failed');
    }
});

a += 2;

console.log(a);

After a few seconds (because of awaiting server's response), the console will log two 13 in the console. This is because the a += 2 will only be executed after the ajax()'s execution has ended.

However, if ajax is set to be asynchronous:

var a = 0;

a += 1;

ajax({
    type: 'POST',
    url: 'api.php',
    dataType: 'json',
    data: {},
    async: true,           // async is set to true
    success: function(e){
        a += 10;
        console.log(a);
    },
    fail: function(e){
        alert('Ajax failed');
    }
});

a += 2;

console.log(a);

The console will immediately first log 3, then after a few seconds, logs 13. This is because while the ajax() is waiting for the server's response, the a += 2 and the codes behind are still being executed, even though the ajax() is still executing (waiting for server's response). Once the server responds, it will then only execute the a += 10 and the other console.log(a).

Of course, to make meaningful ajax request, you will need some code at the server side.

Assuming we have a fake api from api.php:

if (isset($_POST['hello']) && isset($_POST['foo'])){
    $array = [
        'one' => $_POST['hello'],
        'two' => $_POST['foo'];
    ];
}
echo json_encode($array);

Then in JavaScript:

ajax({
    type: 'POST',
    data: {
        hello: 'world',
        foo: 'bar',
    },
    success: function(response){
        console.log(response);
    },
});

The console will then log something similar to the following:

{
    'one': 'world',
    'two': 'bar',
}
yqlim
  • 6,898
  • 3
  • 19
  • 43