I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#sale_type').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'getTypeDetails.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
});
});
And here is getTypeDetails.php:
<?php
require_once('../include/global.php');
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM purchases WHERE sale_type = :data";
// MySQL
$results = $conn->prepare($query);
$results->bindValue(":data", $data);
$exec = $results->execute();
$res = $results->fetchAll();
$data = array();
$i = 0;
foreach($res as $row){
$data[i] = $row['sale_details'];
$i++;
}
echo json_encode($data);
?>
the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
EDIT
Those are my HTML drop lists:
<label for="sale_type" class="col-lg-1 control-label" style="float:right">النوع</label>
<select id="sale_type" name="sale_type" class="dropdown-header" style="float:right">
<option value="undefined">اختر</option>
<?php
foreach($fetchType as $ft){ ?>
<option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
<?php } ?>
</select>
<label for="sale_details" class="col-lg-1 control-label" style="float:right">الصنف</label>
<select id="sale_details" name="sale_details" class="dropdown-header" style="float:right">
</select>
It should be something like this:
.done(function(data) {
var secondDropdown = $("#second-dropdown");
secondDropdown.empty();
$.each(data, function(index, value) {
secondDropdown.append("<option>" + value + "</option>");
});
return;
}
Replace your js code with my code
<script>
$(document).ready(function() {
$('#sale_type').change(function() {
var formData = { 'selectedValue' : $( "#sale_type option:selected" ).val() };
console.log(formData);
$.ajax({
type: 'POST',
url: 'getTypeDetails.php',
data: formData,
success: function(data){
var obj = jQuery.parseJSON(data);
var secondDropdown = $("#sale_details");
secondDropdown.html('');
for (var prop in obj) {
secondDropdown.append("<option>" + obj[prop] + "</option>");
}
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
});
</script>
and add jquery link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your <head> tag
Related
Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script
<input class='file' type="checkbox" class="form-control" name="hid" id="<?php $rs["carimgid"]; ?>" placeholder="Please choose your image">
this my ajax script where using this to delete multiple row without refresh
<script type="text/javascript">
$(document).ready(function(){
jQuery('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
}
else
{
$(".sub_chk").prop('checked',false);
}
});
jQuery('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
//alert(allVals.length); return false;
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
//$("#loading").show();
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
//for server side
var join_selected_values = allVals.join(",");
$.ajax({
type: "POST",
url: "delete.php",
cache:false,
data: 'ids='+join_selected_values,
success: function(response)
{
$("#loading").hide();
$("#msgdiv").html(response);
//referesh table
}
});
//for client side
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
jQuery('.remove-row').on('click', function(e) {
WRN_PROFILE_DELETE = "Are you sure you want to delete this row?";
var check = confirm(WRN_PROFILE_DELETE);
if(check == true){
$('table tr').filter("[data-row-id='" + $(this).attr('data-id') + "']").remove();
}
});
});
</script>
and my php code is
<?php
include("config.php");
if(isset($_POST['ids'])){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid ='$id'");
}
?>
Delete multiple rows by selecting checkboxes using PHP
Hi iam working on select and delete multiple rows from database using below code problem is iam having problem with php script
You haven't got the ids from POST.
Look at the following
$ids = mysqli_real_escape_string($con, $_POST['ids']);
if(!empty($ids)){
$result=mysqli_query($con,"DELETE FROM carimg WHERE carimgid IN ({$ids})");
}
Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>
I am new to JQUERY and I am trying to search for the something and based on the searched text I am doing an ajax call which will call php function and the PHP is returning me with JSON data.
I want to display the returned data in the Datatable form.
I have my PHP file table.php and JavaScript file jss.js and my main.php.
The PHP file is returning the JSON data and I able to use alert to display it.
I want to know how can I display it in datatable.
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off"/>
<button id="search" name="submit">Search</button>
</div>
my ajax/jss.js file
$(document).ready(function(){
$('#search').click(function(){
var search_query = $('#search_query').val();
if(search_query !='')
{
$.ajax({
url:"table.php",
method:"POST",
data:{search_query:search_query},
success: function(data)
{
alert("HEKKI "+data);
}
});
}
else
{
alert("Please Search again");
}
});
});
my table.php file
<?php
$data=array();
$dbc = mysqli_connect('localhost','root','','acdc') OR die('Could not connect because: '.mysqli_connect_error());
if (isset($_REQUEST['search_query']))
{
$name = $_REQUEST['search_query'];
}
if($dbc)
{
if (!empty($name))
{
$sql = "select c.res1 res1,
cc.res2 res2,
cc.res3 res3,
cc.res4 res4,
cc.res5 res5
from table1 c
inner join table2 cc
on c.id = cc.id
where c.name like '".$name."%'
and cc.ENABLED = 1";
$res = mysqli_query($dbc,$sql);
if(!(mysqli_num_rows($res)==0))
{
while($row=mysqli_fetch_array($res))
{
$data['RES1'] = $row['res1'];
$data['RES2'] = $row['res2'];
$data['RES3'] = $row['res3'];
$data['RES4'] = $row['res4'];
$data['RES5'] = $row['res5'];
}
}
else
{
echo "<div style='display: block; color:red; text-align:center'><br/> Not Found,Please try again!!!</div>";
}
}
}
echo json_encode($data);
/*
*/
?>
Can you please guide me how to display the result in main page.
Setting utf8 as charset is probably a good idea. If you have different charset in your table you will get a JSON error :
mysqli_set_charset($dbc, 'utf8');
Then use mysqli_fetch_assoc instead of mysqli_fetch_array. You want field: value records turned into JSON :
$data = array();
while($row=mysqli_fetch_assoc($res)) {
$data[] = $row;
}
Output the JSON :
echo json_encode( array('data' => $data) );
Now you can use it directly along with dataTables :
<table id="example"></table>
$('#example').DataTable({
ajax: {
url: 'table.php'
},
columns: [
{ data: 'res1', title: 'res1'},
{ data: 'res2', title: 'res2'},
//etc..
]
})
one approach is to create the form fulfiled with data just in table.php file and with support of jQuery you will need to populate the <form id="form_id"> with ajax result $('#form_id').html(ajax_response);
other aproach:
to use jQuery json data to populate every field separately.
var jsonData = JSON.parse( ajax_response ); // decode json
than
$('#id_input_1').val(jsonData.RES1);
$('#id_input_2').val(jsonData.RES2);
$('#id_input_3').val(jsonData.RES3);
Place a placeholder in this case I used #results, and dynamically create a table and append it to the placeholder. I commented out your ajax for this example, but just call the function I created to process the results from within the success callback and pass the new function a javascript object.
$(document).ready(function() {
$('#search').click(function() {
var search_query = $('#search_query').val();
if (search_query != '') {
//$.ajax({
// url: "table.php",
// method: "POST",
// data: {
// search_query: search_query
// },
// success: function(data) {
// alert("HEKKI " + data);
// }
//});
processResults({RES1: "result1", RES2: "result2"});
} else {
alert("Please Search again");
}
});
});
function processResults(obj){
var $tbl = $("<table>");
var $row = $("<tr>");
var trow;
$.each(obj, function(idx, elem){
trow = $row.clone();
trow.append($("<td>" + obj[idx] + "</td>"));
$tbl.append(trow);
});
$("#results").append($tbl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off" />
<button id="search" name="submit">Search</button>
<div id='results'></div>
</div>
I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}
I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});