custom page with custom select2 submit form

Hi. I’ve create a custom file with multiple box for insert more values from db. I’ve adding also a button for submit form on same page and loading the data. Now i’m a trying to search with an select2 the data, for to make the search dynamic. I have some problem with the answer because execute Rows provides a different multidimensional array. A few suggestions?MyCustomPage.php with Header/Footer inlcluded

// Get Data select2
if(!isset($_POST['searchTerm'])){ 
  $fetchData =  ExecuteRows("SELECT Nome, Cognome from clienti order by Nome limit 15");
}else{ 
  $search = $_POST['searchTerm'];   
  $fetchData = ExecuteRows("SELECT Nome, Cognome from clienti where Nome like '%".$search."%' limit 15");
} 
var_dump($fetchData);
$data = $fetchData;
echo json_encode($data);

?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous"></script>
<!--
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 CDN -->
<!-- Abbonamenti -->
<!-- form Abbonamenti-->
<form enctype="multipart/form-data" id="homeclient" action="/mws/Home" method="POST" >
<?php if (Config("CHECK_TOKEN")) { ?>
<input type="hidden" name="<?= $TokenNameKey ?>" value="<?= $TokenName ?>"><!-- CSRF token name -->
<input type="hidden" name="<?= $TokenValueKey ?>" value="<?= $TokenValue ?>"><!-- CSRF token value -->
<?php } ?>
<div class="ew-basic-search">
	<div id="xsr_1" class="ew-row d-sm-flex">
		<div class="ew-quick-search input-group" id="homesearch" >
			<select type="text" name="client" id="client" class="form-control" value="" maxlength="30" autocomplete="off">
			<option value='0'><?php echo $err ?></option>
			</select>
			<div class="input-group-append">
			<button class="btn btn-primary" name="btn-submit" id="btn-submit" type="submit">Cerca</button>
			</div>

		</div>
	  </div>
	</div>
</form>
<script type="text/javascript">
	$(document).ready(function(){
	 $("#client").select2({
	  ajax: { 
	   url: "/mws/Home",
	   type: "GET",
	   dataType: 'json',
	   delay: 250,
	   data: function (params) {
		return {     
		  searchTerm: params.term // search term
		};
	   },
	   processResults: function (response) {
		 return {
			results: response
		 };1
	   },
	   cache: true
	  }
	 });
	});
</script>
</br>

var_dump($fetchData);
array (size=4)
  0 => 
    array (size=4)
      'Nome' => string 'Alba' (length=4)
      0 => string 'Alba' (length=4)
      'Cognome' => string 'Nera' (length=4)
      1 => string 'Nera' (length=4)
  1 => 
    array (size=4)
      'Nome' => string 'Luca' (length=4)
      0 => string 'Luca' (length=4)
      'Cognome' => string 'Trivi' (length=5)
      1 => string 'Trivi' (length=5)
  2 => 
    array (size=4)
      'Nome' => string 'Pippi' (length=5)
      0 => string 'Pippi' (length=5)
      'Cognome' => string 'Calzacorta' (length=10)
      1 => string 'Calzacorta' (length=10)
  3 => 
    array (size=4)
      'Nome' => string 'Sale' (length=4)
      0 => string 'Sale' (length=4)
      'Cognome' => string 'Pepe' (length=4)
      1 => string 'Pepe' (length=4)

GT73 wrote:

execute Rows provides a different multidimensional array. A few suggestions?

Can you explain in more detail, what is the difference between the ExecuteRows result and your expectation result?

let’s say i solved this, as i couldn’t convert the executer array to select2 format (‘id’, ‘text’). but to use executejson I have to add the commonfiles and the echo result is dirty as well as having problems with POST. If I use a clean file and mysqli everything works fine. How can I retrieve the query result in jQuery using the built-in PHPMaker functions? If I used userfn.php for my getData code but select2 in the ‘url’ parameter does not accept variables, how could I solve?

// Get Data select2
if(!isset($_POST['searchTerm'])){ 
  $data =   ExecuteJson("select * from clientirc order by idCliente limit 10");
}else{ 
  $search = $_POST['searchTerm'];   
  $data =  ExecuteJson("select * from clientirc where NC like '%".$search."%' || BarCode like '%".$search."%' limit 10");
} 
echo $data;
//echo json_encode($data);

Home.php ( customfile include common file)

<script>
loadjs.ready("foot", function() {
	$(document).ready(function(){
		$("#client").select2({
			ajax: { 
			width: 'resolve',
			url: "/mws/Getdata",
			type: "POST",
			dataType: 'json',
			delay: 250,
			data: function (params) {
				return {     
					searchTerm: params.term // search term
					};
			},
			processResults: function(data){
				output = $.map(data, function (obj) {
								obj.text = obj.text + " - " + obj.code
								return obj;
							});
				return { results: output };
			},
			cache: true
			}
		});
	});
});
</script>

also if I use POST (with common file) return 200 error

type: “POST”,
400
Bad Request
The server cannot or will not process the request due to an apparent client error.With GET returns header and footer not good
type: “GET”,

url: “/mws/Getdata”

It depends on how you created your action Getdata. If you defined it by $app->get(), you should use it by HTTP GET. If you defined it by $app->post(), you should use it by HTTP POST.Read How to create routes.

I think I did not understand. PHPMaker in the compilation creates routes with the GET method? Anyway I can use GET, but the problem I get all of the page, instead of just echo.
I could create an empty file and insert (https://discourse.hkvstore.com/t/use-phpmaker-scripts-in-my-existing-website-v2021/3735/1)
require_once $ RELATIVE_PATH. “vendor / autoload.php”;
require_once $ RELATIVE_PATH. “src / constants.php”;
require_once $ RELATIVE_PATH. “src / config.php”;
require_once $ RELATIVE_PATH. “src / phpfn.php”;
require_once $ RELATIVE_PATH. “src / userfn.php”;
but I don’t really like it as a solution.
I can create a function in userfn but how can I pass the value in select2 to the url:“?”
I can also use server event Route_Action, but how can i assign value to url: “?” in select2?

  1. If Custom File with Include common files, then
  • select2 and jQuery are already included, you do not need to include them yourself.
  • the route is generated with $app->any() so you can access it by HTTP GET or HTTP POST.



If I used userfn.php for my getData code… >

You must not put your actions in Global Code directly. You should use Route_Action server event. A route can have parameters, read https://discourse.hkvstore.com/t/using-route-action-server-event-v2021/3393/1


I could create an empty file and insert (viewtopic.php?f=18&t=49920)

You better avoid doing that unless you fully understand why you want to do it that way.

I’ve change i t to, but retunr always undefined in select2 option it appears to be unable to insert values into select2 optionsdrop down menu select2 in home.php
undefined - undefined
undefined - undefined
undefined - undefined
undefined - undefined


<script>
loadjs.ready("foot", function() {
	$(document).ready(function(){
		$("#client").select2({
			ajax: { 
			width: 'resolve',
			url: "/mws/myaction",
			type: "POST",
			dataType: 'json',
			delay: 250,
			data: function (params) {
				return {     
					searchTerm: params.term // search term
					};
			},
			processResults: function(data){
				output = $.map(data, function (obj) {
								obj.text = obj.text + " - " + obj.code
								return obj;
							});
				return { results: output };
			},
			cache: true
			}
		});
	});
});
</script>



function Route_Action($app)
{
    // Example:
    // $app->get('/myaction', function ($request, $response, $args) {
    //    return $response->withJson(["name" => "myaction"]); // Note: Always return Psr\Http\Message\ResponseInterface object
    // });
    // $app->get('/myaction2', function ($request, $response, $args) {
    //    return $response->withJson(["name" => "myaction2"]); // Note: Always return Psr\Http\Message\ResponseInterface object
    // });
	$app->any('/myaction', function ($request, $response, $args) {
		if(!isset($_POST['searchTerm'])){ 
			$data =   ExecuteJson("SELECT * from clientirc order by idCliente limit 10");
		}else{ 
			$search = $_POST['searchTerm'];   
			$data =  ExecuteJson("SELECT NC AS Text, BarCode AS Code from clientirc where NC like '%".$search."%' || BarCode like '%".$search."%' limit 10");
		} 
		$response->getBody()->write($data); // Write to response body
		return $response; // Return the response
	});
}

response for search luca

{Text: "Luca Trivi", Code: "42525125"}]
0: {Text: "Luca Trivi", Code: "42525125"}
Code: "42525125"
Text: "Luca Trivi"

If your database data is in utf-8, it is better to use withJson(), see Returning JSON, e.g.

$rows = ExecuteRows("SELECT ...");
$response->withJson($rows);

When you use a user input in a SQL, you should prevent SQL injection, e.g.

$search = AdjustSql($search);

thanks so it works fine

<script>
loadjs.ready("foot", function() {
	$(document).ready(function(){
		$("#client").select2({
			ajax: { 
			width: 'resolve',
			url: "/mws/myaction",
			type: "post",
			dataType: 'json',
			delay: 250,
			data: function (params) {
				return {     
					searchTerm: params.term // search term
					};
			},
			processResults: function(data){
				output = $.map(data, function (obj) {
								obj.text = obj.Text + " - " + obj.Code
								return obj;
							});
				return { results: output };
			},
			cache: true
			}
		});
	});
});
</script>



//add a route without create a custon file with content
function Route_Action($app)
{
	$app->any('/myaction', function ($request, $response, $args) {
		$oldresponse = "";
		if(!isset($_POST['searchTerm'])){ 
			$data =   ExecuteRows("SELECT idCliente AS id, NC AS Text, BarCode AS Code from clientirc order by idCliente limit 10");
		}else{ 
			$search = $_POST['searchTerm'];   
			$search = AdjustSql($search);
			$data =  ExecuteRows("SELECT idCliente AS id, NC AS Text, BarCode AS Code from clientirc where NC like '%".$search."%' || BarCode like '%".$search."%' limit 10");
		} 
		return $response->withJson($data);
		 
	});
}