Несколько вызовов AJAX для одного и того же файла, чтобы выполнить другой код в одном файле? - PullRequest
0 голосов
/ 29 сентября 2018

Я все еще довольно новичок в серверных сценариях и AJAX.Что мне интересно, так это то, что я могу сделать несколько вызовов AJAX для одного и того же файла, но с помощью моих вызовов AJAX, только прочитать определенный сценарий в этом файле для выполнения для этого конкретного вызова AJAX?Мне интересно, почему это происходит потому, что когда я делаю вызов ajax, он анализирует весь код моего скрипта, чтобы он тоже выполнял вызов ajax вместо конкретного кода, который находится внутри моих других скриптов вызова ajax.

Теперь я могу полностью решить эту проблему, просто создав новый файл и указав мои ajax-вызовы на отдельные файлы, но разве это не считается плохой архитектурой?Например, 1 ajax-вызов editusers.js, другой для deleteusers.js, почему бы просто не иметь все разные ajax-вызовы в одном файле?

Вот мой код, я использую таблицы данных начальной загрузки с рендерингом на стороне сервераЗОП не mysqli.Первый ajax-вызов предназначен для запроса всех записей в моей таблице, а второй ajax-вызов предназначен для функциональности, связанной с редактированием записи пользователя в самой таблице.Тем не менее, я остановился на редактировании функциональности записей пользователей, потому что мне было интересно, если бы я мог добиться этого?

HTML & JavaScript

<script type="text/javascript">
$(document).ready(function() {

    $('#userDetails').DataTable({
    	"scrollY": "400px",
    	"scrollCollapse": true,
    	"processing": true,
    	"serverSide": true,
    	"ajax": {
    		"url": "../user-actions-script.php",
    		"type": "post",
    	},
   		"deferRender": true,
 		oLanguage: {sProcessing: "<i class='fas fa-spinner fa-3x' id='loader'></i>"},
    });

	$(document).on('click', 'i.fas.fa-edit', function(e){
		$.ajax({
			url: '../user-actions-script.php',
			success: function(){
				console.log('works');
			}
		})
	});

});
</script>

<body>
	<div class="fluid-container">
		<header>
			<nav class="navbar navbar-expand-lg navbar-dark bg-dark"></nav>
		</header>
		<div class="container">
			<h2>User Actions</h2>

			<div class="userdetailsContainer">
				<table class="table table-dark table-striped table-bordered table-hover" id="userDetails">
					<thead>
						<!-- adding this in later -->
					</thead>
				</table>
			</div>
			<!-- Edit Actions Modal -->
			<!-- Modal -->
			<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
			  <div class="modal-dialog" role="document">
			    <div class="modal-content">
			      <div class="modal-header">
			        <h5 class="modal-title" id="exampleModalLabel"></h5>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
			          <span aria-hidden="true">&times;</span>
			        </button>
			      </div>
			      <div class="modal-body">
			       	<div class="editHeader">
			       		<i class="fas fa-edit fa-2x"></i>
			       		<span>Edit User</span>
			       	</div>
			       	<div class="form-group">
			       		<form
			       			method="POST"
							
			       			>
				       		<label for="email">Email:</label>
				       		<input
				       		 	type="email"
								class="form-control"
								name="email"
				       		>
							<label for="fullName">Full Name:</label>
							<input
								type="text"
								class="form-control"
								name="fullName"
							>
							<label for="area">area:</label>
							<select
								class="form-control"
								name="area"
								id="area"
							>
								<?php include ("_global/includes/login_select_options-approved.php") ;?>
							</select>
							<label for="requestor">Requestor:</label>
							<select
								class="form-control"
								name="requestor"
								id="requestor"
							>
								<?php include ("_global/includes/select_options.php") ;?>
							</select>
  							</div>
			       		</form>
			        	<button
			        		type="submit"
			        		class="btn btn-primary">
			        		Save changes
			        	</button>
			       	</div>
			      </div>
			    </div>
			  </div>
			</div>
		</div>
	</div>
</body>

PHP PDO / Ajax-скрипт

<?php 
	include "_global/includes/config.php";

	// Set all fetch requests as an object by default
	$dbo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

	// Custom Usergroups Inputs
	$admin = 'ADMIN';
	$emptyValues = '';
	$adminLive = 'ADMIN-live';
	$adminType = 'ADMIN_US_Type';
	$customusDomestic = 'US_domestic';
	$adminChina = 'China_admin';
	$adminIndia = 'India_admin';
	$adminCustom = 'ADMIN_custom';
	$customusaustinCulver = 'US_Austin_Culver';
	$customuschinaTokyo = 'US_China_Tokyo';
	$customcorkuaeBayarea = 'Cork_UAE_BayArea';
	$customchinashanghaiBeijing = 'China_Shanghai_Beijing';
	$adminselfMoves = 'ADMIN_selfmoves';
	$adminmilanVienna = 'ADMIN-milan-vienna';
	$custombayareaSeattle = 'Bayarea_Seattle_admin';
	$custombayareaCulver = 'ADMIN_Culver_Bay';
	$customculverSingapore = 'ADMIN_Culver_Singapore';
	$customcanada = 'ADMIN_canada';

	// Datatable serverside processing script
	$request = $_REQUEST;
	$columns = array(
		0 => 'name',
		1 => 'email',
		2 => 'usergroup',
		3 => 'user',
		4 => 'DateAdded'
	);

	// Prepare the query
	$sqlAll = 'SELECT mem_id, email, name, usergroup, user, DateAdded
			FROM plus_signuptestdata
			WHERE usergroup NOT IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
		 	GROUP BY email
		 	ORDER BY dateAdded DESC';

	$stmt = $dbo->prepare($sqlAll);

	// Execute the query
	$stmt->execute([$admin,$emptyValues,$adminLive,$adminType,$customusDomestic,$adminChina,$adminIndia,$adminCustom,$customusaustinCulver,$customuschinaTokyo,$customcorkuaeBayarea,$customchinashanghaiBeijing,$adminselfMoves,$adminmilanVienna,$custombayareaSeattle,$custombayareaCulver,$customculverSingapore,$customcanada]);

	// Count Rows
	$rowCount = $stmt->rowCount();
	// Fetch the query
	$totalData = $stmt->fetchAll(PDO::FETCH_ASSOC);
	$totalFiltered = $rowCount;


	$sqlAll = "SELECT mem_id, email, name, usergroup, user, DateAdded ";
	$sqlAll .= " FROM plus_signuptestdata ";
	$sqlAll .= " WHERE usergroup NOT IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	if(!empty($request['search']['value'])){
		$sqlAll .= " AND name LIKE '%".$request['search']['value']."%' ";

		$sqlAll .= " OR email LIKE '%".$request['search']['value']."%'";

	}
	// Order by with empty or without empty user string
	$sqlAll .=" ORDER BY ". $columns[$request['order'][0]['column']]." ".$request['order'][0]['dir']."  LIMIT ".$request['start']." ,".$request['length']."   ";

	$stmt = $dbo->prepare($sqlAll);
	// Execute the query
	$stmt->execute([$admin,$emptyValues,$adminLive,$adminType,$customusDomestic,$adminChina,$adminIndia,$adminCustom,$customusaustinCulver,$customuschinaTokyo,$customcorkuaeBayarea,$customchinashanghaiBeijing,$adminselfMoves,$adminmilanVienna,$custombayareaSeattle,$custombayareaCulver,$customculverSingapore,$customcanada]);

	$totalData = $stmt->fetchAll(PDO::FETCH_ASSOC);


	$newData = array();
	// Convert all the data to UTF-8 unicode format.
	foreach($totalData as $item) {
		$nestedData=array(); 

		$nestedData[] = mb_convert_encoding($item['name'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['email'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['usergroup'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['user'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['DateAdded'], 'UTF-8', 'UTF-8');
		$nestedData[] = '<i class="fas fa-edit" data-toggle="modal" data-target="#editModal" id="'.$item['mem_id'].'"></i> <i class="fas fa-trash" id="'.$item['mem_id'].'"></i>';
	
		$newData[] = $nestedData;
	}


	$json_data = array(
		"draw"            => intval( $request['draw']), 
		"recordsTotal"    => intval( $rowCount ),  
		"recordsFiltered" => intval( $totalFiltered ),
		"data"            => $newData  
	);

	echo json_encode($json_data);
  
  // This is fine but what happens when I need to make another ajax call to this file? It'll read all the contents of this script how can I make it to where it reads only certain code within the same file?

Ответы [ 2 ]

0 голосов
/ 29 сентября 2018

Вы можете использовать условие блока if для выполнения определенного вызова ajax. Предположим, что вы хотите выполнить первый блок if из первого вызова ajax, тогда вы должны передать параметры с помощью ajax, что ваше первое условие блока if является истинным и таким же образом.для всех вызовов ajax.

КОД PHP

 <?php 
     if($_POST['DATA']=='FIRST'){
       all statements are here.
      }else if($_POST['DATA']=='SECOND'){
       all statements of second block is here.
      }else if($_POST['DATA']=='THIRD'){
        all statements of the third block are here.
      }   so on 
  ?>

AJAX CALL

  // First AJAX CALL for FIRST IF BLOCK
  $.ajax({
        url: 'please give php file url',
        data:{ DATA: 'FIRST' },
        success: function(){
            console.log('works');
        }
    });
  //  Second AJAX CALL for SECOND IF BLOCK
    $.ajax({
        url: 'please give php file url',
        data:{ DATA: 'SECOND' },
        success: function(){
            console.log('works');
        }
    });
  // so on 

Думаю, я на правильном пути:)

0 голосов
/ 29 сентября 2018

но разве это не считается плохой архитектурой?Нет, делать это по-своему было бы плохой архитектурой.Отдельные действия (delete.php, update.php, create.php) в разных файлах были бы лучше и более удобны для сопровождения, но я говорю о части php. Да, вы можете иметь на том же javascript все ваши обращения к этим файлам, например:

//crud.js

$("#delete_button").on('click', function(e){
        $.ajax({
            url: '../delete.php',
            success: function(){
                console.log('deleted');
            }
        })
    });

$("#update_button").on('click', function(e){
        $.ajax({
            url: '../update.php',
            success: function(){
                console.log('updated');
            }
        })
    });
$("#create_button").on('click', function(e){
        $.ajax({
            url: '../create.php',
            success: function(){
                console.log('created');
            }
        })
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...