I know this question have been asked many times, but I have tried for hours and nothing worked, I'm a noob with php and ajax so, I might be missing a small thing that I'm not aware of, What I'm trying to achieve here is that, I want the user to select a food group and based on that a list of ingredients will show up.
I tested my process.php file alone and it is working well, I have also tested the script what happens is that the line starting from $.ajax doesn't work when I comment it out and type alert(parent) I actually get the value of the option selected, so what am I doing wrong here? or am I missing an import?
P.S I'm using bootstrap 3.0 for the design
Here is my html code
<!-- field food group-->
<div class ="field form-group">
<label for="food-group"> Food Group * </label>
<div class="input-group input-group-lg">
<select class="form-control" id="food-group-id" name="food-group" onchange="ajaxfunction(this.value)">
<?php
// retreiving the recipe groups
$RecipeGroup = new FoodGroup();
$data = $RecipeGroup->findAll();
foreach ($data->results() as $recipegroup) {
// displaying the options
echo '<option value="'.$recipegroup->food_group_id.'">'.$recipegroup->food_group_name.'</option>';
}
?>
</select>
</div>
</div>
<!-- field Ingredients-->
<div class ="field form-group">
<label for="ingredients"> Ingredients * </label>
<div class="input-group input-group-lg">
<select class="form-control" id="ingredients">
<?php
// retreiving the recipe groups
$ingredients = new Ingrident();
if(Input::exists()){
$data = $ingredients->findByGroup(Input::get('food-group'));
}else
$data = $ingredients->findByGroup(1);
foreach ($data->results() as $ingredient) {
// displaying the options
echo '<option value="'.$ingredient->ingrident_id.'">'.$ingredient->ingrident_name.'</option>';
}
?>
</select>
<br> <br> <br>
<span id="helpBlock" class="help-block center">Ingredient not listed ?
<button class="btn btn-primary center" value="add-ing"> <span class="glyphicon glyphicon-plus"></span> Add New Ingredient </button>
</span>
</div>
</div>
Here is my script
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: 'process.php?food-group=' + parent;
success: function(data) {
$("#ingredients").html(data);
}
});
}
</script>
Here is my process.php file
<?php
mysql_connect('localhost', 'root','');
mysql_select_db("online_recipes");
$result = mysql_query("SELECT * FROM `ingrident` WHERE `food_group_id_fk` = " . mysql_real_escape_string($_GET['food-group']));
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['ingrident_id'],'">', $data['ingrident_name'],'</option>';
A list of my imports
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/docs.min.js"></script>
<script src="js/ie10-viewport-bug-workaround.js"></script>
$.ajax({
url: 'process.php',
type:'post',
data: {parent: parent},
success: function(data) {
$("#ingredients").html(data);
}
});
in your process.php
$parent = $_POST['parent'];
echo($parent);
Related
I have a problem. I want to display the data from database in the existing textbox but unfortunately, it does not display the result. My if else loop is not working. I don't want to display the textbox only if the button is click. I want the result display inside the existing textbox after the search button click.
here is my code html code:
<div class="row">
<div class="column middle2" style="background-color:transparent">
<div class="container"><br><br>
<div class="row">
<div class="col-01">
<label for="icno"><b>IC No :</b></label>
</div>
<div class="col-02">
<form action="" method = "POST">
<div class="input-group">
<input type="text" name="icpayer" value = "<?php if(isset($_POST['icpayer'])){echo $_POST['icpayer'];} ?>" class="form-control bg-light border-0 small" >
<div class="input-group-append">
<button type="button" id = "searchValue" class="btn btn-primary">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-01">
<label for="name"><b>Payer Name :</b></label>
</div>
<div class="col-02">
<input type="text" id="payername" name="payername" >
</div>
</div>
</div>
</div>
</div>
here is my javascript code:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
here is my php code:
<?php
if(isset($_POST['icpayer'])){
$searchValue = $_POST['icpayer'];
$query="SELECT * FROM ptregistration WHERE patientic = '$searchValue'";
$result = mysqli_query($con, $query) or die(mysqli_error($con,$query));
while($row = mysqli_fetch_array($result)){
echo $row['patientname'];
}
}else{
echo "No Record Found";
} ?>
my problem is when I click the search button, the result display "No Record Found" even there is similar data in the database. please help me as I am a beginner.
You should modify the ajax request to send the icpayer parameter. I do not use jQuery so I'm sure a better jQuery method exists but you can do so like this:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
data:{
icpayer:document.querySelector('input[name="icpayer"]').value
},
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
The PHP was exposing your database to SQL injection (potentially) so you should use Prepared Statements
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['icpayer'] ) ){
include($_SERVER['DOCUMENT_ROOT'].'/mhcsys/include/config.php');
$icpayer=filter_input( INPUT_POST, 'icpayer', FILTER_SANITIZE_STRING );
$sql='select `patientname` from `ptregistration` where `patientic`=?';
$stmt=$con->prepare($sql);
$stmt->bind_param('s',$icpayer);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows();
if( $rows > 0 ){
$stmt->bind_result( $patientname );
while( $stmt->fetch() )echo $patientname;
}else{
echo 'No Record Found';
}
}
?>
I’m using CodeIgniter framework and I want to make a chained drop-down with JavaScript code. Then I get this error:
SyntaxError: expected expression, got '<' //first line
But my first line is <!DOCTYPE html> and my file type is PHP not JavaScript, here is my JavaScript code:
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputBody">Body Number</label>
<select name="inputBody" id="inputBody" onchange="javascrip: ambildata(this.value);" class="form-control" required="required">
<?php foreach ($body as $bd) { ?>
<option value="<?php echo $bd->bodynumkids ?>" ><?php echo $bd->bodynumkids ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-6">
<label for="inputKiddie">Kiddies Name</label>
<!-- <div class="form-label-group"> -->
<input type="text" name="inputKiddie" id="inputKiddie" class="form-control" placeholder="ex. Super Cop" required="required">
<!-- </div> -->
</div>
<script type="text/javascript">
function ambildata(x) {
$.ajax({
type:'POST',
url :'<?php echo base_url("Repairpaint/chained"); ?>',
jsonp : 'callback',
dataType: 'jsonp',
data :{ '#inputBody' : x},
success: function(response){
console.log(response);
var len = response.length;
if(len > 0){
var tampil = response[0].namakids;
$('#inputKiddie').text(tampil);
} else {
$('#inputKiddie').text('wek');
}
}
})
}
</script>
</div>
</div>
And here the controller :
public function chained()
{
$dataKiddie = $this->input->post('inputBody');
$where = array('bodynumkids'=> $dataKiddie);
$response = $this->Model_repairpaint->chaincb('kiddiejadi', $where)->result();
echo json_encode($response);
}
I have searched similar questions and solutions around Stack Overflow but I found nothing. Can anyone help me find out the solution?
I want to ask, has someone ever created autocomplete using combo box / select box with code igniter?
I've tried but only managed to use autocomplete for 2 input text but I have another idea to create autocomplete with text combined with combo box. I've do created that but I have trouble my autocomplete in the text is successful but in the combo box does not work only show empty option. can someone help me? this is my source code
My Table : i probably using 2 table for autocomplete : 1. tb_produk and 2. tb_kategori_produk
https://imgur.com/a/xpysI | 2. https://imgur.com/a/DVgUl
My Controller : user.php
public function request_produk(){ //used for calling view
$data["kateprod"] = $this->db->where("f_status_kategori_produk","1")
->get("tb_kategori_produk")->result_array();
$this->theme->panel('user/v_request',$data);
}
public function mesin() //user for jquery called data
{
$keyword = $this->uri->segment(3);
$data = $this->db->from('tb_produk')->join('tb_kategori_produk','tb_kategori_produk.f_id_kategori_produk=tb_produk.f_kategori_produk')->like('f_nama_produk',$keyword)->get();
foreach($data->result() as $row)
{
$arr['query'] = $keyword;
$arr['suggestions'][] = array(
'value' =>$row->f_nama_produk,
'idpro' =>$row->f_id_produk,
'idkate' =>$row->f_id_kategori_produk,
'kategori'=>$row->f_nama_kategori_produk
);
}
echo json_encode($arr);
}
My Controller : v_request.php
<div id="content">
<script type="text/javascript">
var site = "<?php echo site_url();?>";
$(function() {
$(".autocomplete").autocomplete({
serviceUrl: site+"/user/mesin",
onSelect: function (suggestion) {
$("#v_idproduk").val(""+suggestion.idpro);
$("#v_kategori").val(""+suggestion.kategori);
$("#v_idkategori").val(""+suggestion.idkate);
}
});
});
</script>
<?php $id = $this->session->userdata('f_id_user');
<input type="hidden" name="dt[f_id_user]" value="<?php echo $this->session->userdata('f_id_user'); ?>">
<input type="hidden" id="v_idproduk" name="dt[f_id_produk]">
<input type="hidden" id="v_idkategori" name="dt[f_kategori_produk]">
<div class="form-group br-form"> <!-- This form group i used to autocomplete text -->
<div class="col-md-2">
<label class="control-label">Nama Mesin</label>
</div>
<div class="col-md-10">
<input type="search" class="autocomplete form-control" id="autocomplete1" name="nama_mesin" required/>
</div>
</div><br><br>
<div class="form-group br-form"> <!-- This form group i used to autocomplete combo box-->
<div class="col-md-2">
<label class="control-label">Kategori Mesin</label>
</div>
<div class="col-md-10">
<select id="v_kategori" name="dt[f_kategori_produk]" class="form-control" required>
<option value="">---Harap Pilih---</option>
<?php foreach ($kateprod as $key) { ?>
<option value="<?=$key['f_id_kategori_produk']?>" id="v_kategori"><?php echo $key["f_nama_kategori_produk"];?></option>
<?php } ?>
</select>
</div>
</div><br>
This is my demo
https://streamable.com/wvn25
Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"®ion="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?
The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..
You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().
My site is fully asynchronus, most of the html gets created and destroyed on button presses and every one of them prevents navigation.
At this part I produce a form with a "rate 1 to 10" array of radioboxes, post it using jQuery.ajax() and send it to process where it's either echoed back (for now) or echo "nothing was selected.".
This is the form,
<?php
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">';
for ($i = 0; $i <= 10; $i++) {
echo '
<span class="lead form-options">' .'</span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio'. $i .'" value="'. $i .'">'. $i.'
</label>';
}
echo '
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
?>
This is the javascript:
$('body').on('click', '.surveyForm', function(){
console.log("Clicked on .surveyForm-btn");
var data = $('#surveyForm').serialize();
console.log( data );
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log("Ajax call to processSurvey success");
$("#surveyForm").clearForm();
console.log(result);
console.log( data );
}
});
return false;
});
And this is the process php:
<?php
if (isset($_POST['sabor'])) // if ANY of the options was checked
echo $_POST['sabor']; // echo the choice
else
echo "nothing was selected.";
print_r($_POST);
?>
This is the console after clicking submit WITH a selected radiobox:
Clicked on #surveyForm
[EMPTY LINE]
Ajax call to processSurvey success
nothing was selected.
[EMPTY LINE]
This means the submit is successful, but the form data is empty. I've been trying to find the problem since yesterday, I'm pretty sure I'm passing the data wrong but can't find anything in google that I haven't tried.
EDIT: Added most sugestions, problem persists. Maybe the html structure is wrong? The form and the submit don't seem to be connected.
EDIT 2: I found something very strange, on the final code there seems to be an extra closing tag, like this
<form id="surveyForm" action="processSurvey.php" method="post"></form>
<h3>Alimentos</h3>
<h4>Sabor</h4>
I have no idea where is that coming from, but is defenitely the problem.
there are a lot of notes here
1- you will get confused with form id='surveyForm' and button class='surveyForm' so its better to change it a little bit to button class='surveyForm_btn'
2- I think you should serialize the form not the button
var data = $('#surveyForm').serialize(); // not .surveyForm
3- IDs must be unique
4- $("#surveyForm").clearForm(); // not .surveyForm
finally check all comments
and Its better to use
$('body').on('submit', '#surveyForm', function(){});
Edited answer:
1- please check everything after each step
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
in js
$('body').on('submit', '#surveyForm', function(){
var data = $(this).serialize();
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log(result);
}
});
return false;
});
in php
<?php
echo 'Connected successfully';
?>
this code will output Connected successfully in console .. if this work add your for loop and make a check again
Try to write your htm like that :
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<?php
for ($i = 0; $i <= 10; $i++) {
?>
<span class="lead form-options"></span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio<?=$i ?>" value="<?= $i ?>" /><?= $i?>
</label>
<?php
} ?>
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>