How to retrieve a value from a select in PHP without submit?
Aucune_solution
-
jordane45 Posted messages 30426 Registration date Status Moderator Last intervention -
jordane45 Posted messages 30426 Registration date Status Moderator Last intervention -
Hello,
I would like to retrieve the value of a country that is in a list, in order to associate the phone code with my phone field. And I would like to do this before validating my form; I can't find any solution, how can I do this please?
Thank you
I would like to retrieve the value of a country that is in a list, in order to associate the phone code with my phone field. And I would like to do this before validating my form; I can't find any solution, how can I do this please?
Thank you
6 answers
You want :
You select a COUNTRY from your dropdown list
At that moment .. the phone code of the corresponding country appears in your TEL input field...
Knowing that :
- The list of country codes is stored in a table in your database ....
SO :
- You detect the change of country in your select using the ONCHANGE method
- You retrieve, via AJAX, the code of the concerned COUNTRY
it is necessary that you create a dedicated PHP page to retrieve the country code via a SQL query and use it with the AJAX call.
- You put in your TEL INPUT ... the code retrieved via AJAX (in JavaScript)
In JavaScript (AJAX):
And in PHP
There you go ...
I leave you to complete!
You select a COUNTRY from your dropdown list
At that moment .. the phone code of the corresponding country appears in your TEL input field...
Knowing that :
- The list of country codes is stored in a table in your database ....
SO :
- You detect the change of country in your select using the ONCHANGE method
<select id="countrySelect" name="country" onchange="check();getCountryCode();">
- You retrieve, via AJAX, the code of the concerned COUNTRY
it is necessary that you create a dedicated PHP page to retrieve the country code via a SQL query and use it with the AJAX call.
- You put in your TEL INPUT ... the code retrieved via AJAX (in JavaScript)
In JavaScript (AJAX):
function getCountryCode(){ var urlAjx = 'path/to/your/file/countryCode.ajx.php'; var country = $("#countrySelect").val(); var data = {country:country}; $.ajax({ url: urlAjx, dataType: "json", type: "POST", data: data, async: false, success: function(response){ $("#tel_struct").val(response); }, error: function(jqXHR, textStatus){ var error = formatErrorMessage(jqXHR, textStatus); alert('error :' + error); } }); } function formatErrorMessage(jqXHR, exception) { if (jqXHR.status === 0) { return ('Not connected.\nPlease verify your network connection.'); } else if (jqXHR.status == 404) { return ('The requested page not found. [404]'); } else if (jqXHR.status == 500) { return ('Internal Server Error [500].'); } else if (exception === 'parsererror') { return ('Requested JSON parse failed.'); } else if (exception === 'timeout') { return ('Time out error.'); } else if (exception === 'abort') { return ('Ajax request aborted.'); } else { return ('Uncaught Error.\n' + jqXHR.responseText); } } And in PHP
// here you include your database connection file // then : // retrieving POST variables $country = isset($_POST['country'])?$_POST['country']:NULL; if($country){ // here your query: $sql = "SELECT * FROM yourtable WHERE country='$country'"; // execution of your query : $result = ------ } // Then return data to ajax : echo json_encode($result); There you go ...
I leave you to complete!
Hello,
For that, you need to use JAVASCRIPT with AJAX
The ideal being to go through JQUERY (the syntax and use of ajax being simplified, I find)
https://openclassrooms.com/fr/courses/1567926-un-site-web-dynamique-avec-jquery/1569648-le-fonctionnement-de-ajax
--
Best regards,
Jordane
For that, you need to use JAVASCRIPT with AJAX
The ideal being to go through JQUERY (the syntax and use of ajax being simplified, I find)
https://openclassrooms.com/fr/courses/1567926-un-site-web-dynamique-avec-jquery/1569648-le-fonctionnement-de-ajax
--
Best regards,
Jordane
I set the Ajax file aside, the file that contains the inputs aside, with the Ajax URL: fichier_des_inputs.php, is that right?
I don't think so...
The Ajax file... what does that mean? The file that contains the PHP code for the AJAX part or the JavaScript code?
If it’s the PHP code you’re talking about... that’s what needs to go in the URL...
Ideally, you should post the code of each of your files (making sure to indicate its name so we can keep track).
In order:
The code that contains your fields (your dropdown list, your inputs (Tel ....)
This file can also contain the AJAX JavaScript (unless you placed it in a separate file)
The code of the PHP file called by the AJAX.
PS: When you are doing Javascript (and/or AJAX) development, it is STRONGLY recommended to use the debugging tools of your web browser to check for errors and see what’s going on. I highly recommend you use the FIREBUG plugin for Firefox....
And here’s a tutorial to learn how to use it: https://eric-pommereau.developpez.com/tutoriels/outil-web/firebug/
--
Best regards,
Jordane
I want to know the country code before I submit the form, I need it to specify the phone number prefix
Do you need it OR?
To do what?
Why BEFORE the SUBMIT?
Your question is not clear and precise enough... it's almost impossible for us to answer you!
We know nothing about your code... nor what you exactly want to do...
--
Best regards,
Jordane
```html
<form action="traitement_formulaire.php" method="post" id="sky-form" class="sky-form">
<select id="countrySelect" name="country" onchange="check()">
<?php
$reponse = $bdd->query('SELECT * FROM pays');
echo '<option value="">Pays</option>';
while ($donnees = $reponse->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$donnees[" id_pays="">' . $donnees["pays"].'</option>';
}
?>
</select>
<input type="tel" name="tel_struct" id="tel_struct" placeholder="Téléphone générique" />
</form>
```
<form action="traitement_formulaire.php" method="post" id="sky-form" class="sky-form">
<select id="countrySelect" name="country" onchange="check()">
<?php
$reponse = $bdd->query('SELECT * FROM pays');
echo '<option value="">Pays</option>';
while ($donnees = $reponse->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$donnees[" id_pays="">' . $donnees["pays"].'</option>';
}
?>
</select>
<input type="tel" name="tel_struct" id="tel_struct" placeholder="Téléphone générique" />
</form>
```
Voici mes fichiers :
file 1: test2_country.php
file 2: test_country.php
file 1: test2_country.php
<select id="countrySelect" name="country" onchange="check();getCountryIndicator();"> ?php $response = $bdd->query('SELECT * FROM countries'); echo '<OPTION VALUE="">Country</OPTION>'; while ($data = $response->fetch(PDO::FETCH_ASSOC)) { echo '<OPTION VALUE="'.$data["id_country"].'">'.$data["country"].'</OPTION>'; } ?> </select> <input type="tel" name="tel_struct" id="tel_struct" placeholder="Generic phone"> file 2: test_country.php
<?php // here you include your database connection file include("connection.php"); // then : // retrieving POST variables $country = isset($_POST['country']); if($country){ // here your query: $sql = "SELECT * FROM countries WHERE id_country='$country'"; // executing your query : $bdd->exec($sql); } // Then return data to ajax : echo json_encode($result); ?> <script> function getCountryIndicator(){ var urlAjx = 'test2_country.php'; var country = $("#countrySelect").val(); var data = {country:country}; $.ajax({ url: urlAjx, dataType: "json", type: "POST", data: data, async: false, success: function(response){ $("#tel_struct").val(response); }, error: function(jqXHR, textStatus){ var error = formatErrorMessage(jqXHR, textStatus); alert('error :' + error); } }); } function formatErrorMessage(jqXHR, exception) { if (jqXHR.status === 0) { return ('Not connected.\nPlease verify your network connection.'); } else if (jqXHR.status == 404) { return ('The requested page not found. [404]'); } else if (jqXHR.status == 500) { return ('Internal Server Error [500].'); } else if (exception === 'parsererror') { return ('Requested JSON parse failed.'); } else if (exception === 'timeout') { return ('Time out error.'); } else if (exception === 'abort') { return ('Ajax request aborted.'); } else { return ('Uncaught Error.\n' + jqXHR.responseText); } } </script>
oups ... no ... !
You have a document that contains :
- Your HTML fields (including your country list) + the associated javascript
- A PHP file containing only the code needed for your AJAX
In short :
Code for the AJAX PHP file :
Furthermore, you were able to modify some code ... when all it took was a simple copy/paste...
To correctly retrieve a variable you need to use :
Whereas you.. by retrieving what I gave you.. modified it to :
==>>> Which will not work !
Then ...
When you make SELECT queries ... don't forget that you need to FETCH the result to read the content...I suggest you to directly use a fetchall()
Not forgetting that it is better to use prepared queries rather than an EXEC.
and thus .. your code becomes :
You have a document that contains :
- Your HTML fields (including your country list) + the associated javascript
- A PHP file containing only the code needed for your AJAX
In short :
<select id="countrySelect" name="country" onchange="check();getIndicateurPays();"> ?php $reponse = $bdd->query('SELECT * FROM pays'); echo '<OPTION VALUE="">Country</OPTION>'; while ($donnees = $reponse->fetch(PDO::FETCH_ASSOC)) { echo '<OPTION VALUE="'.$donnees["id_pays"].'">'.$donnees["pays"].'</OPTION>'; } ?> </select> <input type="tel" name="tel_struct" id="tel_struct" placeholder="Generic Phone"> <script type="text/javascript"> function getIndicateurPays(){ var urlAjx = 'test2_pays.php'; var pays = $("#countrySelect").val(); var data = {pays:pays}; $.ajax({ url: urlAjx, dataType: "json", type: "POST", data: data, async: false, success: function(reponse){ $("#tel_struct").val(reponse); }, error: function(jqXHR, textStatus){ var error = formatErrorMessage(jqXHR, textStatus); alert('error :' + error); } }); } function formatErrorMessage(jqXHR, exception) { if (jqXHR.status === 0) { return ('Not connected.\nPlease verify your network connection.'); } else if (jqXHR.status == 404) { return ('The requested page not found. [404]'); } else if (jqXHR.status == 500) { return ('Internal Server Error [500].'); } else if (exception === 'parsererror') { return ('Requested JSON parse failed.'); } else if (exception === 'timeout') { return ('Time out error.'); } else if (exception === 'abort') { return ('Ajax request aborted.'); } else { return ('Uncaught Error.\n' + jqXHR.responseText); } } </script> Code for the AJAX PHP file :
<?php // here you include your connection file to your DB include("connexion.php"); // then : // retrieval of POST variables $pays = isset($_POST['country']) ? $_POST['country'] : NULL; if($pays){ // your query here: $sql = "SELECT * FROM pays WHERE id_pays='$pays'"; // execution of your query : $bdd->exec($sql); } // Then return data to the ajax : echo json_encode($result); ?> Furthermore, you were able to modify some code ... when all it took was a simple copy/paste...
To correctly retrieve a variable you need to use :
// retrieval of POST variables $pays = isset($_POST['country']) ? $_POST['country'] : NULL;
Whereas you.. by retrieving what I gave you.. modified it to :
$pays = isset($_POST['country']);
==>>> Which will not work !
Then ...
When you make SELECT queries ... don't forget that you need to FETCH the result to read the content...I suggest you to directly use a fetchall()
Not forgetting that it is better to use prepared queries rather than an EXEC.
and thus .. your code becomes :
if($pays){ // your query here: $sql = "SELECT indicatif FROM pays WHERE id_pays=':pays'"; $params = array(':pays'=>$pays); // execution of your query : $sth = $bdd->prepare($sql); $sth->execute($params); $result = $sth->fetchAll(); } // Then return data to the ajax : echo json_encode($result[0]['indicatif']);
Initially, the country has a certain value, and in this case, I don't have the code, so I need to select the country first.
How can I get the code in this case?
Your dropdown list... it returns the "value" of the country (in this case, its ID)
So, in the where of your query... you use it...
Of course... the code I'm giving you is purely for example... not knowing the structure of your database... but I can deduce that it should look something like this:
I tried your code, it worked the first time, but I don't remember how. I'm trying again now but nothing is happening, I put the Ajax file separately, the file that contains the inputs separately, with the Ajax URL set to: fichier_des_inputs.php, is that correct?