Answer the question
In order to leave comments, you need to log in
Multiple operations, one $.ajax request, one php file?
Hi hubr!
The essence of the problem: I am making a mobile application on cordova.
Client side: js, jquery, html
Server side: php, mysql
Data exchange: Json
I've already written enough code in js, jquery and php. And every day, I add functionality. The problem is, I don't use frameworks other than jquery. Recently, I myself do not understand my old code. Today I saw with horror that I did part of the connection to the database using old mysql commands, and part was done using PDO. I will say right away that I am still programming procedurally, without OOP.
Another problem is in ajax requests and processing of requests on the server by php scripts. For each button, I have a separate ajax request and a separate php script on the server that receives this request. The problem is the readability of the code, on one html page in the client, when there are 5 separate ajax requests, even sublime text hangs a little.
Question Is it possible somehow to collect all this bunch of scripts into a bunch, through one ajax request to one php script, which will be accepted on the server?
For you to advise me to read. What are some styles of organizing this whole thing? When I started this whole thing, I didn’t think that everything would go so far, it was addictive, but I didn’t want to do garbage code.
ps: I deliberately made everything separate so as not to get confused and it was easier to debug the code
Answer the question
In order to leave comments, you need to log in
RequestBlock == true; // разрешаем в глобале запросы
$('html').on('click','.element',function() {
var data = {
RequestHead: {
RequestTarget:'somePhpFunction', // вызываемая функция php, любое имя
RequestType:'Update' // тип
},
RequestData: {
select:'0' // id
}
}
var data = JSON.stringify(data);
var s = {
type:'POST',
url:'lib/CONNECT.php',
data:data,
dataType:'json',
parent:'somePhpFunction'
};
SendData(s); // отправляем данные
});
function SendData(s) {
if (s.type && s.type.length || s.url && s.url.length || s.data && s.data.length || s.dataType && s.dataType.length || s.parent && s.parent.length) {
if (RequestBlock == false) {
console.log('выполняется другой запрос');
} else if (RequestBlock == true) {
RequestBlock = false; // блокируем параллельный запрос, ждем выполнения текущего
$.ajax({
type: s.type,
url: s.url,
data: s.data,
cache: false,
dataType: s.dataType,
timeout: 15000,
success: function(r) {
RequestBlock = true; // для избежания ошибок получения данных не той функцией - блокируем повтороную отправку данных переменной RequestBlock. Теряем ассинхронность, зато упрощаем логику отправки и приема данных
SendSuccess(s, r);
},
error: function(jqXHR, textStatus, errorThrown) {
RequestBlock = true;
if (textStatus === 'timeout' || textStatus === 'abort' || textStatus === 'parsererror') {
console.log('ошибка');
} else if (textStatus === 'error') {
console.log('ошибка');
} else {
SendError(s, r);
}
}
});
}
}
}
function SendSuccess(s, r) {
if (s.parent == 'somePhpFunction') {
RsponseForSomePhpFunction = r; // выносим в глобал уникальную переменную или передаем функции
JsSomePhpFunction(r);
// вызываем функцию пост-обработки
}
}
function SendError(s) {
if (s.parent == 'somePhpFunction') {
console.log('ошибка');
}
}
$RequestParameters = json_decode(file_get_contents("php://input"));
if (!empty($RequestParameters->RequestHead) || !empty($RequestParameters->RequestData)) {
if (!empty($RequestParameters->RequestHead->RequestTarget) || !empty($RequestParameters->RequestHead->RequestType)) {
if ($RequestParameters->RequestHead->RequestTarget == 'somePhpFunction') {
// если надо, можно прямо тут задействовать RequestType
$Result = somePhpFunction($RequestParameters); // вызываем функцию
}
} else {
$Result = array(
'ResponseStatus' => "error",
'ResponseData' => "error: 0002"
);
}
} else {
$Result = array(
'ResponseStatus' => "error",
'ResponseData' => "error: 0001"
);
}
echo json_encode($Result);
Read Bob Martin's "Clean Code", in my opinion the basis of normal code organization.
Regarding the advice of colleagues in the shop - it's all right, but not the fact that you will do it the way it should. It is best if you find an experienced programmer to review and help with refactoring. It's like with a coach or a coach: a few lessons to understand the basic principles of how to do it right, and then whatever your heart desires.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question