I'm creating a website and I want to load different queries onto a page depending on which button is clicked.
Can I do it like this?
The HTML :
<div id="Proceed">
4 Projects have been suggested to proceed.
</div>
<div id="result">
<!-- The title of the projects will be loaded here -->
</div>
<button id="foo"> Search </button>
The javascript:
$('#foo').on('click' function(){ //the button
var x = $(this).find('div').attr('id'); // get the id
$.ajax({
url: 'profile/inbox',
type: 'POST',
data: { id: x },
success: function(res){
('#result').html(res);
}
})
})
On profile.php:
function Inbox(){
$id = $_POST['id'];
$query = $this->db->query("SELECT `title` FROM `table` WHERE id=?",$id);
$load = $query->result_array();
$this->d['load'] = $load;
}
EDIT: I added some html to show where I plan to load the results of the query.
For eg:(This is your code I just slightly modified because for
example)
<div id="Proceed">
<select id="city" name="city">
<option value="">City:</option>
<option value="glasgow">Glasgow</option>
<option value="london">London</option>
</select>
</div>
<div id="result">
</div>
<button id="foo"> Search </button>
Script:(For eg:)
$("#foo").click(function() {
$.ajax({
url: 'profile/inbox', //Pass this value to the corresponding URL
type: 'POST',
dataType: "html",
data: {
"city": $('#city').val(), //Here request the value for id name is city
},
success: function(response){
$("#result").html(response); //Retrieve value form URL to pass the view page and value to set in <div id="result">
}
});
});
This is my url page(you just see what are the process there.. This is
for eg)
$sql = "SELECT * FROM entries";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "success"."id: " . $row["id"]. " - City: " . $row["city"]. "<br>";
}
} else {
echo "0 results";
}
When you want to use a POST variable from PHP side you have to use
$_POST/$_REQUEST method in your case $id = $_POST['id']; this will work
Related
I have a problem wherein I cannot put the data inside select element and make an option using the ID to append on what is inside my ajax. I got the data and it is showing in an input element but when I switched it into select element it doesn't work.
Here is the image of my form
JQuery / Ajax code
function ToolsChange(element) {
let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {
var dataSplit = response;
console.log(response);
var shouldSplit = dataSplit.split("#");
var shouldNotSplit = dataSplit.split();
console.log(shouldSplit);
console.log(shouldSplit[0]);
console.log(shouldSplit[1]);
console.log(shouldSplit[2]);
$("#sel_control_num").val(shouldSplit[0]);
var specs = [];
for (i = 1; i < shouldSplit.length; i += 3) {
specs.push(shouldSplit[i])
}
$("#sel_tools_spec").val(specs.join(', '));
$("#sel_tools_id").val(shouldSplit[2]);
}
});
}
}
HTML code(I had to comment select element because it is not showing the data)
<div class="form-group">
<label> Tools Specification: </label>
<input id="sel_tools_spec" class="form-control" name="tools_specification"
data-live-search="true" readonly>
<!-- <select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select> -->
</div>
PHP code
<?php
include("../include/connect.php");
if(isset($_POST['tools_id'])){
$ID = $_POST['tools_id'];
$query = "SELECT tools_masterlist.control_no, tools_masterlist.tools_id,
tools_masterlist.tools_name,
tools_spec.model_num,tools_spec.model_num_val, tools_spec.status
FROM tools_masterlist LEFT JOIN tools_spec ON tools_masterlist.tools_id = tools_spec.tools_id
LEFT JOIN tools_registration ON tools_masterlist.control_no = tools_registration.reg_input
WHERE status = 1 AND tools_name = '$ID'";
$con->next_result();
// $result=mysqli_query($con, "CALL GetAjaxForToolsRegistration('$ID')");
$result=mysqli_query($con, $query);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
// echo $row['control_no'] . "#" . $row['model_num'] . "#" . $row['tools_id'] ."#";
echo $row['control_no'] . "#" . '<option value="'.$row['tools_id'].'">'.
$row['model_num'] .'</option>' . "#" . $row['tools_id'] ."#";
}
}
else
{
}
}
?>
Don't need to split() or even return your response using echo ... #... #... .. Ok here is what you should do
The main idea in my code is: returning all the data from php/database
then control it in js/ajax and this will happen by using dataType : 'json' and echo json_encode($data)
in php
$return_result = [];
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
$return_result[] = $row;
}
}
else
{
$return_result['error'] = 'error';
}
echo json_encode($return_result);
in javascript (ajax)
$.ajax({
type: "post",
url: "form_JSON_approach.php",
dataType : 'json', // <<<<<<<<<<< here
data: {
"tools_id": tools_id
},
success: function(response) {
if(!response.error){
//console.log(response);
$.each(response , function(index , val){
// here you can start do your stuff append() or anything you want
console.log(val.control_no);
console.log(val.tools_id);
});
}else{
console.log('You Have Error , There is Zero data');
}
}
});
You are appending all datas at onces instead inside for-loop you can directly append options inside your selectpicker and refresh it.
Demo Code :
$("#sel_tools_spec").selectpicker() //intialize on load
ToolsChange() //just for demo..
function ToolsChange(element) {
/*let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {*/
//other codes....
$("#sel_tools_spec").html('');
//suppose data look like this...
var shouldSplit = ["1", "<option>A</option>", "1001", "2", "<option>B</option>", "1001"]
for (i = 1; i < shouldSplit.length; i += 3) {
//append options inside select-box
$("#sel_tools_spec").append(shouldSplit[i]);
}
$("#sel_tools_spec").selectpicker('refresh'); //refresh it
/* }
});*/
}
<link rel="stylesheet " type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<div class="form-group">
<label> Tools Specification: </label>
<select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select>
</div>
Since you are using bootstrap. Just do the following
$("#sel_tools_spec").empty().append('<option value="ID">LABEL</option>').selectpicker('refresh');
Source: how to append options in select bootstrap?
I have created an array of events and now I have a filter by location dropdown. How do I get the value selected in the dropdown and handle it in js or php? Which one would it be better so it shows events from that location and not all the events. I have have different files one for displaying the events (events.js and events.php) and the other files (filterevents.js and filter events.php) this is what I want to handle the filtering in.
HTML
<div class="events">
<form method="POST" id="eventForm">
Filter By Location<br/>
<select name="Locations">
<option value="Leeds">Leeds</option>
<option value="Newcastle">Newcastle</option>
<option value="London">London</option>
</select>
<input type="submit" name="submit" value="Search"/>
</form>
<div class="eventname"><!--obj.eventname--></div>
<div class="date"><!--obj.date--></div>
<div class="time"><!--obj.time--></div>
<div class="location"><!--obj.location--></div>
<p id="error" class="errormessage"></p>
<p id="allevents" class="postmessage"></p>
</div>
events.php
<?php
require_once('checklog.php');
require_once("db_connect.php");
require_once("functions.php");
session_start();
// Print out existing events
$query = "SELECT eventname, date, time, location FROM events ORDER BY eventname";
$result = mysqli_query($db_server, $query);
if (!$result)
die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)) {
$events[] = $row;
}
mysqli_free_result($result);
require_once("db_close.php");
echo json_encode($events);
?>
events.js
$(document).ready(function() {
var events = document.getElementById("allevents").value;
// Call Ajax for existing comments
$.ajax({
type: 'GET',
url: 'events.php',
success: function(result) {
var arr = JSON.parse(result);
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
var output = document.getElementById("allevents");
output.innerHTML += '<div class="comment-container"><div class="eventname">'+obj.eventname+'</div><div class="date">'+obj.date+'</div><div class="time">'+obj.time+'</div><div class="location">'+obj.location+'</div></div>';
}
}
});
filterevents.php
<?php
require_once('checklog.php');
require_once("db_connect.php");
require_once("functions.php");
This is where I want to filter but not sure how to do it.
?>
filterevents.js
// When post button is clicked
$(document).ready(function() {
var forum = $("#eventForm");
$("#eventForm").on('submit', function(event) {
event.preventDefault();
var events = new FormData(this);
if (events) {
// Call Ajax for new comment
$.ajax({
type: 'POST',
url: 'filterevents.php',
data: events,
processData: false,
contentType: false,
success: function(response) {
if(response == "Success")
{
document.getElementById("comment").innerHTML = response;
} else {
document.getElementById("error").innerHTML = response;
}
}
});
} else {
document.getElementById("error").innerHTML = "Please Select A Location";
}
return false;
});
});
I'm trying to put a Select2 box inside a while loop. But it only works the first select tag. Although loop works fine, the select tag is not working after the first 1. how can I fix this issue?
I also tried adding printing PHP unique id to fix it. but nothing happened.
<select type="text" name="city" id="city-<?php echo $id; ?>" class="form-control"></select>
This is the javascript part:
<script type="text/javascript">
$('#city-<?php echo $id; ?>').select2({
placeholder: 'Select city',
ajax: {
url: 'processes/cities.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
I'm expecting all the select boxes to work fine. But actually, only first 1 works.
It would be helpful if you provided the loop in your code example.
The most likely problem is that your id's are not unique. If you have multiple tags with the same id then javascript will only recognize the first one.
Here's an example to demonstrate.
https://jsfiddle.net/n8vxjoc1/1/
<div id="city-1">Content</div>
<div id="city-1">Content</div>
<script>
jQuery( '#city-1' ).html( jQuery( '#city-1' ).length );
</script>
Only the 1st element will change and it will display the number 1.
From the W3C specs:
The id attribute specifies its element's unique identifier (ID).
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute
You should give the select dropdowns a class and target that instead.
E.g.
https://jsfiddle.net/n8vxjoc1/1/
<select name="city" class="select2 form-control">…</select>
<select name="city" class="select2 form-control">…</select>
<script type="text/javascript">
$('select.select2').select2({});
</script>
You can take help from this link: Demo
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
PHP:
<?php
include 'config.php';// add your config details on that file
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
JS
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
First, I will summary my demo for you: I have a form for me to type an api link and type of the chart I want to draw from my api link. After that, I will click the button to create chart and insert my input to MySQL database to show it on screen. Each chart have a button for me to delete it if I want.
Everything worked fine except delete funtion to delete my input from database. When I press delete button, it's only delete in html, not delete in my database. Can you help me? Thank you!
Here is my code:
My input form:
<!--HTML Form input-->
<div class = "login-block">
<form id="form1" style="display: block" method="POST" action="chart_test.php">
<!--Input link api-->
<b>Link: </b><input type="text" id="link" name="apilink"><br>
<br>
<!--Chart Type-->
<b>Chart Type:</b>
<label class="custom-select">
<select id="chartType" name="chartType">
<option value="">Select</option>
<option value="pie">Pie Chart</option>
<option value="column">Column Chart</option>
<option value="bar">Bar Chart</option>
</select>
</label>
<br><br>
<!--Button create chart-->
<div class ="wrapper">
<button type="submit" name="create" onClick="drawChart()">Create</button>
<br><br>
</div>
</form>
</div>
Insert input to database and show to screen:
<!--insert form data to mysql-->
<?php
$con = mysql_connect("localhost","root","123456");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysql_select_db("activiti_report");
//check data when first load page to not showing notice error
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$apilink = $_POST["apilink"];
$chartType = $_POST["chartType"];
}
if(isset($_POST['create'])) {
$sql = "INSERT INTO chartinfo (link, typeChart) VALUES ('$apilink', '$chartType')";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
Query database to show chart on screen and the button with script to delete:
<?php //query data from database
$result = mysql_query("SELECT * FROM chartinfo");
?>
<?php //while loop to read data from query result
while($db_field = mysql_fetch_assoc($result)):
?>
<?php //unique chartId for not the same to show more chart
$idChart = 'chartContainer_' . uniqid();
?>
<!--Show chart from database-->
<br>
<div class = "chart-block">
<?php // 2 lines about chart infomation
echo ("<b>API Link:</b> "); print $db_field['link'] . "<BR>";
echo ("<b>Chart Type:</b> "); print $db_field['typeChart'] . "<BR>";
?>
<!-- The <div> and <script> to show the chart -->
<div id="<?=$idChart?>" style="height: 360px; width: 70%;"></div>
<script>
$(document).ready(function() {
var dataPointsA = []
var text = document.getElementById('chartType')
var strChart = text.options[text.selectedIndex].value
$.ajax({
type: 'GET',
url: "<?php echo $db_field['link']?>", //assign URL from query result field
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
label: field[i].name,
y: field[i].value
});
}
var chart = new CanvasJS.Chart("<?=$idChart?>", {
title: {
text: "Activiti Report"
},
data: [{
type: "<?php echo $db_field['typeChart']?>", //assign type of chart from query result field
name: "chart",
dataPoints: dataPointsA
}]
});
chart.render();
}
});
});
</script>
<br>
<!--Button to delete the chart and row in database-->
<button type="submit" name="delete" onClick="removeParent(this.parentNode)">Delete</button>
<!--Script remove <div> contain the chart-->
<script>
function removeParent(parent) {
parent.remove();
}
</script>
<!--Script delete form data from mysql-->
<?php
if(isset($_POST['delete'])) {
$sql = "DELETE FROM chartinfo (link, typeChart) WHERE link ='" .$db_field['link']. "' AND typeChart = '" .$db_field['link']. "'";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
I know I should use mysqli_* instead mysql_* but this is just a demo for me to understand PHP, I learned it only a few days. Sorry for a lot of code but I think I should show to you to understand what I am doing.
Thank you very much!
Your delete button trigger its action from the js code not the php code. It only remove from the view but will appear on reload. You can use ajax in your remove function or use a delete link instead of button
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php",
data: {id:id},
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
<script>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php?id="+id,
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
</script>
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>
I have a problem here about ajax. Actually I'm a beginner in using Ajax that's why I can't figure out my problem. I have a form that have 4 select boxes. The initial or main selectbox is the country selector. Second is the state next is city and last is barangay. My goal is like this. After the user select his'her country the second selectbox which is state will automatically change according to the user's country. And after selecting the state it will automatically change also the city and last is the barangay. It is just like a dynamic address fields. I am using codeigniter. Here's what I did. This is the process for getting the state.
In my PHP form I have this:
<tr>
<td><label style="font-weight: normal">State / Province: </label></td>
<td >
<select class="form-control" name="c_state" id="c_state">
<option value="">--Select State--<option>
</select>
</td>
</tr>
<tr>
<td><label style="font-weight: normal">Country: </label></td>
<td >
<select class="form-control" name="c_country" id="c_country">
<option value="">--Select Country--</option>
<?php
foreach($countries as $country){
if($country['country'] == 'Philippines'){
echo "<option value='".$country['code']."'selected='selected'>".$country['country']."</option>";
}else{
echo "<option value='".$country['code']."'>".$country['country']."</option>";
}
}
?>
</select>
</td>
</tr>
....
$("#c_country").on('change',function(){
var c_country = $("#c_country").val();
var var_country_selection = '<?php echo site_url("alliance_controller/get_provinces/'+c_country+'"); ?>';
console.log(c_country);
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(d){
alert(d['c_country']);
}
});
});
In my controller I have this:
public function get_provinces($id){
$country = $this->alliance_model->hhj_provinces($id);
echo json_decode($country);
}
In my model I have this:
public function hhj_provinces($id) {
$query = "SELECT * FROM ref_region_province WHERE country_code = '".$id."'";
$result = $this->db->query($query);
echo json_encode($result->result_array());
}
The output in the success in jquery which is in alert is 'undefined'. And I also use the developer tool in Chrome and I looked in the Network tab it shows the URL of my ajax together the Code. But in my preview I have something like this.
[]
No Properties
That's all guys. I just want to get the state of the country selected.
you must return a JSON object in the controller like this
public function get_provinces(){
$id = $this->input->post('id');
$country = $this->alliance_model->hhj_provinces($id);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $country));
}
then in the View
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(data){
$.each(data, function (key, value) {
console.log(value.field)
}
});