I'm new with coding and I found some really valuable information that could help my register form look better using Ajax.
The problem is that, even though the php files are working fine, I think that the js file is not doing it's job. here:
in the register form there's this:
<?php
include 'php_includes/conexion.php'; (connect to DB users)
include 'php_includes/conexionlugar.php'; (connect to DB states/cities)
?>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.js"></script>
</head>
in the form there's this:
Select State
<select name="departamento" id="departamento">
<option value="">Seleccione Departamento</option>
<?php echo cargar_departamentos();?>
</select>
Select City
<select name="provincia" id="provincia">
<option value="">Seleccione Provincia</option>
</select>
Now, in the conexionlugar.php (tested/working):
<?php
function cargar_departamentos()
{
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output = '';
$sql = "SELECT * FROM departamentos ORDER BY NOMBRE_DEPA";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDDEPARTAMENTOS"].'">'.$row["NOMBRE_DEPA"].'</option>';
echo "$output";
}
}
return $output;
?>
in the jquery.js (don't know much about this :()
$(document).ready(function(){
$('#departamento').change(function(){
var IDDEPARTAMENTOS = $(this).val();
$.ajax({
url:'../php_includes/fetch_provincia.php',
type:"POST",
data:{departamentoId:IDDEPARTAMENTOS},
dataType:"text",
success:function(data)
{
$('#provincia').html(data);
}
});
});
});
in the fetch_provincia.php (tested/working)
<?php
$connect = mysqli_connect("localhost", "root", "root", "lugar");
$output ='';
$sql = "SELECT * FROM provincias WHERE departamentos_IDDEPARTAMENTOS = '".$_POST["departamentoId"]."' ORDER BY NOMBRE_PROV";
$result = mysqli_query($connect, $sql);
$output = '<option value="">Seleccione Provincia</option>';
while($row = mysqli_fetch_array($result))
{
$output = '<option value="'.$row["IDPROVINCIAS"].'">'.$row["NOMBRE_PROV"].'</option>';
echo $output;
}
return $output;
?>
Though separately the PHP files are working, the JS file changing departamentoId for IDDEPARTAMENTOS looks like it's not... help me please.
I think I fixed it, deleting the "return" on both php and adding the js to the same page and not calling it through
The data you are sending from php needs to be sent as json. I would actually not do the "formatting" in php. Just return $result:
echo json_encode($result);
then in your js file, just iterate through "data" and create the options:
success:function(data)
{
$.each(data, function(key, val){
console.log("Key: " + key + " val: " + val);
}
}
have a some errors in your code.
First, in "cargar_departamentos", the return it´s out of a function, and in your fetch_provincia.php, not need a return statement.
In your jQuery code, try remove one of both jQuery called in your head, and Change de dataType directive of "text" to HTML.
#gilgameshbk you are calling jquery 2 times in your head
maybe this may cause some conflict.
Related
I have the following the html/php code :
<!DOCTYPE html>
<html>
<head>
<title>Voiture</title>
</head>
<body>
Welcome<br>
<form method="post" action="">
Liste de voiture<select name="selected" id="selected">
<?php
$sql = 'select Type from voiture';
$result = $conn->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['Type'], $json)){
$json[] = $row['Type'];
echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
}
}
?>
</select> <br>
<span id="sel" name="sel"></span>
<table border="1">
<tr id="header">
<td>Type</td>
<td>Model</td>
<td>Couleur</td>
<td>Prix</td>
<td>User</td>
<td>Action</td>
</tr>
</table>
<input type="submit" name="submit" hidden>
</form>
<script src="jquery-3.2.1.js"></script>
<script>
$(function(){
$('#selected').on('change',function(){
$('#sel').text(document.getElementById('selected').value);
$.getJSON('phpVoiture.php',function(data){
for (var x = 0 ; x < data.length ; x++){
$('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
'</td><td>'+data[x]['Couleur']+'</td>'+
'<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
}
});
});
});
</script>
</body>
</html>
And the following php page :
<?php
require_once ('./dbConnect.php');
include ('./Voiture.php');
$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$json[] = [
'type' => $row['Type'],
'model' => $row['Model'],
'couleur' => $row['Couleur'],
'prix' => $row['Prix']
];
}
}
else{
echo mysqli_num_rows($result);
}
echo json_encode($json);
The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.
You're not sending the selected value to the server. Add it to the AJAX call:
$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
//...
});
Also, your <option> elements don't have values. You used name instead, but that belongs on the <select>. Use value:
echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
Additionally, you're using a GET request instead of a POST request. So you need to look for the value in the $_GET array:
$sel = $_GET['selected'];
You have other typos too, such as an incorrect use of a variable in PHP:
"...".sel."..."
would be:
"...".$sel."..."
Though this brings up a point about SQL injection. You really shouldn't be directly concatenating the variable like that at all. Instead, use prepared statements with query parameters.
It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet. You'll want your debugging to include two things:
Looking at your PHP logs for errors.
Using your browser's debugging tools to observe the AJAX request/response.
I have a code, where when i select a value through Drop-down, the name I am selecting should pass through a PHP variable $ch so a second drop-down which runs a mysql query.
Here is my code for first dropdown:
<select name="cha_name" id="cha_name" onChange="fillcha(this.value);">
<option value="0">--SELECT--</option>
<?php
$res = mysqli_query($con, "select customer_code, customer from master_customer where is_cha = 1 order by customer") or die(mysqli_error($con));
while($row = mysqli_fetch_array($res)){
echo "<option value=\"".$row[1]."$$".$row[0]."\" ".(($row[1]==$wo_order[1])?"selected='selected'":"").">".$row[1]."</option>";
}
?>
</select>
When i select this, the value should be capture in a PHP variable $ch without reloading the page show the PHP variable can be used further in a mysql query. Kindly help as I am still in learning phase for JQuery and Ajax.
the mysql query is as follows:
SELECT container_no FROM `cex_work_order_det` WHERE `cha_name`='$cha'
for that you have to use jquery and ajax
jquery code
<script>
$("document").ready(function()
{
$("select[name='cha_name']").change(function() // function sorting Domain according to server name
{
var customer_code=$("select[name='cha_name']").val();
$.get('ajax_actions.php?act=your-act-name&customer_code='+customer_code,function(data)
{
alert(data);
});
});
});
</script>
ajax_actions.php
<?php
error_reporting(0);
foreach ($_GET as $name => $value) { $$name = $value; }
foreach ($_POST as $name => $value) { $$name = $value; }
// warning Dont chnage anything in This ajax action file
// -------------------------------------------------------------------------------
if($act=="your-act-name") // do your actions
{
// fire here your query and echo you result here
}
As I wrote in the title I have this part of code in page page.php that is in a subfolder admin. So the path of page is ../admin/page.php:
<select name="my_select" id="my_select" onchange="function(this.value);">
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
}
?>
</select>
$var = $_POST['my_select'];
echo "I have selected $var";
I use a function that I have found on internet:
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'page.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("my_select").innerHTML=response;
}
});
}
What I have to do to take value in $var? Because I need this value to build other things. Is it possible?
EDIT:
Probably I don't explain very well my problem. I don't have very good with ajax because I never use it. I have a deadline so I can't study it now.
Now I have this situation:
I have a select-form with an input submit. After click on the button I use $_POST['myoption'] and I get the value.
Then I do it:
if($var == 1)
//a query from database
else if($var == 2)
//another different query
else
//other but no query
This work correctely. I need to change it and use in the same page. How can I do the same?
You don't to do a POST to do this you can do it with jQuery.
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
?>
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
<span id="selected"></span>
<script>
$("#my_select").change(function() {
$("#selected").html($("#my_select option:selected").text());
});
</script>
This will give the select value to PHP:
<?php
include "../db/db_config.php";
$conn = mysql_connect($host,$user,$password)or die(mysql_error());
mysql_select_db($db, $conn);
$query="Query";
$res=mysql_query($query,$conn);
if (isset($_POST['my_select'])) {
$var = $_POST['my_select'];
} else {
$var = '';
}
?>
<form id="my_form" action="" method="POST">
<select name="my_select" id="my_select">
<?php
while($row=mysql_fetch_array($res)){
$id=$row['id'];
$text=$row['text'];
echo "<option value='$id'>$text</option>";
}
?>
</select>
</form>
<span id="selected">I have selected <?php echo $var; ?></span>
<script>
$("#my_select").change(function() {
$('#my_form').submit();
});
</script>
Currently my dependent list is working on $_GET request. I'm trying to convert $_GET request to $_POST in Ajax without reloading the form. In the head I put #$cat=$_GET['cat']; I want this to be like $_POST and below ajax script is working on self.location which means its getting the value from $_GET url. I want the below script to work like $_POST and without reloading the form. Any help would very much appreciated.
my global declaration on the top as below
#$cat=$_GET['cat'];
my sql queries as below
<?php
# category and sub-category
$quer2="SELECT DISTINCT name,id FROM tblproductgroups order by name";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups where group_id=$cat order by sub_group_name";
}else{$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups order by sub_group_name"; }
?>
my ajax script as below
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='product-add.php?cat=' + val ;
}
function disableselect()
{
<?Php
if(isset($cat) and strlen($cat) > 0){
echo "document.myForm.subcat.disabled = false;";}
else{echo "document.myForm.subcat.disabled = true;";}
?>
}
</script>
my dependent drop down list as below
<?php
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
$sql = mysqli_query($customCon, $quer2);
while ($row = mysqli_fetch_array($sql)) {
if($row['id']==#$cat){echo "<option selected value='$row[id]'>$row[name]</option>"."<BR>";}
else{echo "<option value='$row[id]'>$row[name]</option>";}
}
echo "</select>";
echo "<select name='subcat'><option value=''>Select one</option>";
$sql2 = mysqli_query($customCon, $quer);
while ($row2 = mysqli_fetch_array($sql2)) {
echo "<option value='$row2[id]'>$row2[sub_group_name]</option>";
}
echo "</select>";
?>
Use jQuery (see their site for installation instructions) and add a change event handler to your select item. Also add an container div to your HTML code that will hold your dynamically loaded content like:
<div id="myCatContainer"></div>
In the event handler do:
$('#myCatContainer').load('product-add.php?cat=' . $('#mySelect').val();
Be sure to read about jQuery and how to define an event handler, before you try the above code!
I'm build an hybrid app based on JqueryMobile. And now I'm trying to get a simple array with the categorys that I select from my mysql table. I saw many questions related to this and tired a thousand solutions but nothing worked.
Here's what I have:
PHP Code:
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row;
//$id[] = $row['Tipo']; doesn't work either
}
echo json_encode($id);
mysql_close($conn);
with this I get blank result.
The closest I got was with this:
$id=array();
$i=0;
while ($row = mysql_fetch_assoc($sql)) {
$id[] = array("data$i" => $row['Tipo']);
echo json_encode($id[$i]);
$i++;
}
with the result:
{"data0":"Restaurantes"}{"data2":"Shopping"}{"data3":"Eventos"}{"data4":"Hoteis"}{"data5":"Oficinas"}{"data6":"Combustiveis"}
but this is obviously wrong because it has multiple json_encode invocations.
Im trying to get it with Jquery's .$get
<script type="text/javascript">
var inicio=function(argument){
$("#submit").click(function(e){
e.preventDefault();
$.get('http://myurl/get_category.php',{
},function(answer){
alert(answer.length+" "+answer); //trying to know whats happening with the data.
for (var i = 0; i < answer.length; i++) { //my final objective is to fill a listview.
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
}
$('#list').listview('refresh');
},"json"
);
});
}
$(document).on('ready',inicio);
</script>
As I said I searched into many questions and solutions but always got null values. I don't have too much experience with PhP and this is me studying and making experiences with JqueryMobile so.. something's wrong here that I can't see..
Thank you.
Found the solution here on this post
Everything on the DB must be set to UTF-8 or utf8mb4 and now it's finally working. Apreciated everyone's help :)
Try something like this...
If you want only to get the values of column 'Tipo',
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
$i=0;
while($row = mysql_fetch_assoc($sql)) {
$id["data".$i] = $row['Tipo'];
$i++;
}
echo json_encode($id);
mysql_close($conn);
If you awnt to get all the values,
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
$i=0;
while($row = mysql_fetch_assoc($sql)) {
foreach($value as $key=>$value){
$id["data".$i][$key] = $value;
}
$i++;
}
echo json_encode($id);
mysql_close($conn);
You can use the following query:
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row['Tipo'];
}
echo json_encode($id);
mysql_close($conn);
It will return the categories as an array of strings in JSON. e.g. ["entry 1","entry 2"]. If you decide to use this then you would need to adjust your Javascript code.
Your javascript code contains some problems on this line:
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
In the case of you using
$id[] = $row;
In PHP, then the column name would be named Tipo, not tipo (case sensitive). The second issue is that you are trying to access answer.tipo and not the element of the array answer[i].tipo.
So with your current php code you can make it working by changing the javascript.
This line
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
To
$('#list').append("<li> <h3>"+answer[i].Tipo+"</h3></a></li>");
Edit: Since your apparently having issues here is the full code I used.
//query.php
<?php
mysql_connect ('localhost','username','password');
mysql_select_db('db_test');
$sql=mysql_query("SELECT Tipo FROM db_test.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row;
}
echo json_encode($id);
mysql_close($conn);
?>
<html>
<head>
<title> JQuery db test </title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id='list' class='list'>
</div>
<script>
var debug;
$.get('http://www.example.com/test/query.php',{
},function(answer){
debug=answer;
//alert(answer.length+" "+answer); //trying to know whats happening with the data.
for (var i = 0; i < answer.length; i++) { //my final objective is to fill a listview.
$('#list').append("<li> <h3>"+answer[i].Tipo+"</h3></a></li>");
}
// $('#list').listview('refresh');
},"json"
);
</script>
</html>
[PHP]
$id = array();
while($row = mysql_fetch_assoc($sql))
$id[] = $row['Tipo'];
echo json_encode($id);
[JS]
$(document).ready(function(){
$('#submit').click(function(e){
$.ajax({
url: '/get_category.php',
type: 'GET',
dataType: 'json'
}).done(function(res){
$('#list').html('');
for(var i=0;i<res.length;++i)
$('#list').append('<li><h3>'+res[i]+'</h3></li>');
});
});