A
A
aornos2015-06-15 21:40:01
JavaScript
aornos, 2015-06-15 21:40:01

Make ajax work synchronously?

Good time of the day
Fill out the form, check before submitting. One field in the form must be unique. We send it ajax to the script, the script returns true or false. If false, then we mark the field as erroneous and do not submit. Seems simple?
The problem is that the request is executed asynchronously, the field is marked as erroneous, because the result is undefined - the request does not have time to be processed. Error in console: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org .
But it also outputs that:
'translit check is: true';
'value is: displays the value of the field';
'result is: undefined'
here is the code:

//валидатор
result = checkTranslit($('#translit').val());
    if (result  !== 'true') {
        errorArray.push("translit");//кладем поле в массив с ошибками
        console.log('value is: ' + $('#translit').val() + '\n');
        console.log('result is: ' + result + '\n');
    } 

//запрос 
function checkTranslit(translit){
    $.ajax({
        url: 'http://site.com/scripts/checkTranslit.php',
        data: {'translit': translit},
        type: 'POST',
        dataType: 'json',
        async: false,
        success: function(data){
            answer = JSON.stringify(data);            
            console.log('translit check is: ' + answer.result + '\n');    
            return answer.result;
        },
        error: function(error){
            err = JSON.stringify(error);
           console.log('error is: ' + err.result + '\n');  
            return err.result;
        }
    });

}


How to make the request work synchronously? Or block GUI for runtime? Where to dig?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
Sergey, 2015-06-15
@serega_kaktus

here is option 2 - write your own js engine, in which ajax will be synchronous, promote this engine to all browsers, and in parallel correct the ActionScript standards. Even then, your shitty code won't work, because you need to return at least some value from the checkTranslit function.
Well, or you can just remember one simple rule - if you need to perform some action after the completion of the ajax request, then this action must be performed in the success callback.
Rewrite the code

//валидатор
checkTranslit($('#translit').val());
    

//запрос 
function checkTranslit(translit){
    $.ajax({
        url: 'http://site.com/scripts/checkTranslit.php',
        data: {'translit': translit},
        type: 'POST',
        dataType: 'json',
        async: false,
        success: function(data){
          if (!answer.result) {
            errorArray.push("translit");//кладем поле в массив с ошибками
            console.log('value is: ' + $('#translit').val());
            console.log('result is: ' + answer.result);
          } 
        },
        error: function(error){
           console.log('error is: ' + error + '\n');  
            return error;
        }
    });

}

If you have dataType: json, why are you doing any manipulations with them in callbacks? The script on the server should return json, and the callback will already have a deserialized object

D
Denis Smirnov, 2015-06-15
@Groov3

Ahaha. Well, in the JS settings, you can set synchronism, or asynchrony of execution on the AJAX client, stupidly setting such a priority when loading and executing, if it's not about deferred. Read your own code.

A
Alexey Zuev, 2015-06-15
@yurzui

The jqXHR objects returned by the jQuery.ajax() method implement the Promise interface , providing them with all the properties, methods, and behavior of the Promise. The jqXHR.done() method of the Promise interface has replaced jqXHR.success().
Based on this, you can get the jqXHR object and listen to its events.
Example

D
Dmitri Sinitsa, 2015-06-15
@unabl4

No need to make synchronous requests. This is a bad practice, because js is an event-driven, single-threaded programming language, and it is very unhappy when something blocking is slipped into it. Do not do it this way.
Read about callback functions and so on.

D
Denis Ineshin, 2015-06-15
@IonDen

In your case, it is best to block the gui. This is done for example like this:
1. We wrap the form in a container
2. Put a new .blocker div at the end of this container, something like this

.blocker {
    position: absolute;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(255, 255, 255, 0.5);
}

this div will take all the space on top of your form and make it translucent (you can also add some kind of gif-preloader to the center) + block access to it.
3. When starting the Ajax request, make this div visible.
4. At the end of the request, hide it inside the success callback.
5. So we got the GUI blocking for the duration of the request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question