0

I try to create a simple ajax request class in jQuery. The problem I have here is that in the process function I can get the response from variable response . I return response but outside the request it is undefined .. I tried with global variables of some sorts, didn't work out. So now I try to get help from here.

The app.js

var AjaxRequest = Class.extend({

    init: function(url) {
        this.url = url;
    },

    process: function() {

        var response;

        $.get("http://test.dec/ajax.php", function(data) {
            var obj = jQuery.parseJSON( data);
            response = obj;

            console.log(response); // Get correct output

            return response;
        });

    }

});

$('#test').on('click', function() {
    var request = new AjaxRequest('ajax.php');

    console.log(request.process()); // Get undefined
});

The PHP ajax.php

<?php

$json = json_encode(['test' => 'test123']);
echo $json;

?>
KrisInception
  • 155
  • 2
  • 6

2 Answers2

0

The problem is that ajax requests are asynchronous. What you want to do maybe is pass in a callback to process so when it completes, it will call the function to continue.

Here is an example:

var AjaxRequest = Class.extend({

    init: function(url) {
        this.url = url;
    },

    process: function(callback) {

        var response;

        $.get("http://test.dec/ajax.php", function(data) {
            var obj = jQuery.parseJSON( data);
            response = obj;

            console.log(response); // Get correct output

            callback(response);
        });

    }

});

$('#test').on('click', function() {
    var request = new AjaxRequest('ajax.php');

    request.process(function(data) { console.log(data); });
});

Please have a read through this on how asynchronus calls work.

Community
  • 1
  • 1
0

please Try this:

$.ajax({
            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false,
            success: function() {}
        });
  • I would work on your grammar a bit. "asynchronouz" is not a word. –  Mar 29 '15 at 05:00
  • oh sorry, what i mean is "async" – Fajar Yusuf Mar 29 '15 at 05:02
  • Saying "Your ajax cannot async" is also not proper english. –  Mar 29 '15 at 14:32
  • so what? so what your problem? my english or your code? – Fajar Yusuf Mar 29 '15 at 15:12
  • My problem is two things. #1, you don't show the poster how to return data from the function like he asked (I see no return statement anywhere in your code), and #2, I still see atrocious grammar. Sentences start with capital letters. –  Mar 29 '15 at 15:16
  • Trouble with you? i just try for answering.. so if i right or not, i just learn.. Sorry before. – Fajar Yusuf Mar 29 '15 at 15:27