Ajax approach, PHP Post and JSON array CURL - javascript

I tried everything but I can not figure it out.
This is old discussion: PHP Group By value - JSON
In this other thread I was told that the ajax approach is different. I tried to run their advice but when I write the code Javascript in ajaxData.php file seems not to work.
I need to populate reservationTime dropdown with time array (splitted in ajaxData) and dependent by reservationDate (grouped Date Array).
The code below works and fills reservationDate dropdown with date(splitted). Now I would like populate second dropdown.
Dropdown Image
reservationDate Dropdown Image
I have index.php with:
<form id="my-form" method="post" autocomplete="off">
<div class="a-row">
<div id="input-parent">
<select name="company" required="" id="company">
<option value="">Select company</option>
<option value="1">Rome</option>
<option value="2">New York</option>
<option value="3">Madrid</option>
<option value="4">Tokyo</option>
</select>
</div>
<div id="input-parent">
<select name="productCode" required="" id="product">
<option value="">Select product</option>
<option value="IPAD">iPad</option>
<option value="GALAXY">Samsung Galaxy</option>
<option value="LGTV">LG TV</option>
</select>
</div>
<div id="input-parent">
<select name="reservationDate" required="" id="date">
<option>Select date</option>
</select>
</div>
<div id="input-parent">
<select name="reservationTime" required="" id="time">
<option>Select time</option>
</select>
</div>
</div>
<div class="a-row">
<div>
<input type="submit">
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // serializzo
})
.done(function(data){
})
.fail(function(){
alert('Error');
});
});
// Company change
$('#company').on('change', function(e) {
e.preventDefault(); // Prevent Default Submission
var productID = $("select#product option:checked" ).val();
var companyID = $(this).val();
if(companyID && productID != ""){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{company:companyID,productCode:productID},
success:function(html){
$('#firstSelect').html(html);
}
});
}else{
console.log("Nothing");
}
});
// Product change
$('#product').on('change', function(e) {
e.preventDefault(); // Prevent Default Submission
var companyID = $("select#company option:checked" ).val();
var productID = $(this).val();
if(companyID && productID != ""){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{company:companyID,productCode:productID},
success:function(html){
$('#firstSelect').html(html);
}
});
}else{
console.log("Nothing");
}
});
});
</script>
And ajaxData.php where I split date and time and insert loop date values into date dropdown of index.php:
<?php
if(isset($_POST["company"]) && isset($_POST["productCode"]))
{
// Token ID
$authToken = 'XXXXXXXXXXXXXXXXX';
// To send API
$companyData = $_POST["company"];
$productData = $_POST["productCode"];
// Setup cURL
$ch = curl_init('https://.../'.$companyData.'/'.$productData.'' );
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Aythorization: '.$authToken,
'Content-Type: application/json'
),
));
// Send Request
$response = curl_exec($ch);
// Response
$responseData = json_decode($response, TRUE);
$responseData = json_decode($response);
// Setup Var
$availableSlots = $responseData->availableSlots;
$slots_start = $responseData->availableSlots->slots;
// Check if errors
if($response === FALSE){
die;
}
$times = array();
foreach($slots_start as $option){
list($date, $time) = explode(" ", $option->start);
if (!array_key_exists($date, $times)){
$times[$date] = array();
}
if (!in_array($time, $times[$date])){
$times[$date][] = $time;
}
}
foreach ($slots_start as $option){
echo '
<option value="' . $option->start. '">' . $option->start . '</option>';
}
}
?>
My JSON data:
{
"response": {
"storeTimeZone": "Europe/Paris",
"slots": [
{
"start": "2017-01-23T08:00:00Z"
},
{
"start": "2017-01-23T08:20:00Z"
},
{
"start": "2017-01-23T08:40:00Z"
},
{
"start": "2017-01-16T08:00:00Z"
},
{
"start": "2017-01-16T08:20:00Z"
},
{
"start": "2017-01-16T08:40:00Z"
}
...

Related

I'm trying to do dynamic dropdown but it seems that ajax is not working/running

I'm trying to do a dynamic dropdown with my form with Philippine locations, it goes like this choose city -> then barangay data will show up depends on what city you chose.
I have a problem with running ajax, it seems like the moment it reaches $ajax it stops there.
I've already tried alert (city) before if (city) and within if (city) and it works, the alert shows.
I tried putting alert(city) or alert(error) within ajax but nothing showed up, so I concluded that ajax is not running at all (unless my syntax is wrong)
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-field col s6">
<select name="barangay" id="barangay">
<option value="" disabled selected>Choose a Barangay</option>
</select>
<label for="barangay">Barangay</label>
<?php echo form_error('barangay'); //------------------------------------------------?>
</div>
<div class="row">
<div class="input-field col s6">
<select name="city" id="city">
<option value="" disabled selected>Choose a City</option>
<?php
foreach ($cities as $city)
{
echo '<option value="'.$city->city.'">'.$city->city.'</option>';
}
?>
</select>
<label for="city">City</label>
<?php echo form_error('city'); //--------------------------------------------------?>
</div>
</div>
$(document).ready(function(){
/* Populate data to state dropdown */
$('#city').on('change',function(){
var city = $(this).val();
//alert(city);
if(city){
$.ajax({
type:'POST',
url:'index.php/createPatient/getphilippineLocations',
data:'country_id='+city,
success:function(data){
$('#barangay').html('<option value="">Select State</option>');
var dataObj = jQuery.parseJSON(data);
if(dataObj){
$(dataObj).each(function(){
var option = $('<option />');
option.attr('value', this.name).text(this.name);
$('#barangay').append(option);
});
}else{
$('#barangay').html('<option value="">State not available</option>');
}
}
});
}else{
$('#barangay').html('<option value="">Select country first</option>');
}
});
});
//this is the function it is suppose to call
public function getphilippineLocations()
{
$states = array();
$country_id = $this->input->post('country_id');
if($country_id)
{
$states = $this->createPatient_model->getAllBarangays($country_id);
}
echo json_encode($states);
}
function getAllBarangays($city)
{
$sql = "SELECT * FROM ph_locations WHERE city = '".$city."' ORDER BY name ASC";
$query = $this->db->query($sql);
return $query->result();
}
Sadly there is no error message, I can't tell if ajax is running but it suppose to show all the barangays for that city once the city is chosen by the dropdown(an administrative division in the Philippines, similar to village or district)
Hope below will be helpful for you.. try once and let us know if it won't work
<select name="barangay" id="barangay">
<option value="" disabled selected>Choose a Barangay</option>
</select>
var UrlCities = url To Get Cities,
BindDropDownValues(UrlBindBenefitPlans, 'barangay', 'ID', 'Name', true, selectedValueInEditMode);
function BindDropDownValues(url, controlToBind, dataValueField, dataTextField, isSelectRequired, valueToSelect) {
var ajax = $.ajax({
cache: false,
url: url,
dataType: "json",
global: globalAjax,
success: function (data) {
if (data != null && data != undefined && data.length > 0) {
$("#" + controlToBind).empty();
if (isSelectRequired == true) {
$("#" + controlToBind).append($("<option title=\"-Select-\"></option>").val(0).html("--Select--"));
}
for (var itemIndex = 0; itemIndex < data.length; itemIndex++) {
var singleObj = data[itemIndex];
$("#" + controlToBind).append($("<option></option>").val(singleObj[dataValueField]).html(singleObj[dataTextField]));
}
if (valueToSelect != undefined && valueToSelect != "") {
$("#" + controlToBind).val(valueToSelect);
}
}
}
});
return ajax;
};
</script>

Insert to mysql with PHP and AJAX not working

I try to make a form for updating status (select) with AJAX. What I have is:
HTML + JS:
<select id="Bname">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript">
var sel = document.getElementById('Bname');
sel.addEventListener("change", myFunction);
function myFunction() {
jQuery.ajax({
url : "insert.php",
type : "post",
contentType : 'application/json',
dataType : 'json',
data : {
stat : sel.value
}
})
.done(function() {
console.warn('ok!');
})
.fail(function() {
console.warn('error');
});
console.log(sel.value);
}
</script>
In insert.php file I have:
<?php
defined('_JEXEC') or die;
$stat = $_POST["stat"];
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$fields = array(
$db->quoteName('cars') . ' = ' . $db->quote($stat)
);
$conditions = array(
$db->quoteName('id') . ' = 1'
);
$query->update($db->quoteName('#__cars'))->set($fields)->where($conditions);
$db->setQuery($query);
$result = $db->execute();
?>
Question is – why PHP file is not inserting? Any kind of script in insert.php isn't working. It's made with Joomla.
Thanks guys!
You need to first import the joomla libraries if you are calling ajax with single file.

Choosing an option from select and then show data on another select box using Codeigniter

I'm not much good at jquery and ajax, and I'm now having difficulties on a select box. I use CI and My code is below.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
And, another select box "category" data will be show according to the "brand". How can I carry data from "brand" and show data in "category" with jquery?
You can use ajax. See example below
$(function(){
$('#brand').on('change', function(){
var brand = $(this).val();
$.ajax({
type : 'post',
url : '<?php echo base_url();?>controller_name/function_name',
data : 'brand='+brand,
dataType : 'json',
success : function(msg){
// here you can populate data into category select option
var options;
for(var i = 0; i<msg.length; i++)
{
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options); // your html part for category should look like this <select id="category"></category>
}
});
});
});
php code in controller part(function name showCategory)
function showCategory(){
$brand = $this->input->post('brand');
$data['category'] = $this->your_model->your_function_to_select_data();
echo json_encode($data);
}
<?php
?>
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?></option>
<?php
}
}
?>
</select>
<p>Category:</p>
<select name="category">
<!--Content will be popullated from ajax call-->
</select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"> </script>
<script type="text/javascript">
(function($){
$(function(){
$(document).on('change' , '[name=brand]', function(){
var brand_selected = $(this).val();
$.ajax({
url: '[your url to fetch category based on categoryid]' ,
dataType:"json",
data: {brand : brand_selected},
success: function(r){
/**
* your response should be in json format
* for easy work
{catd_id: catname, cat_id :catname}
*/
var html = '';
if(r && r.length){
$.each(r, function(i, j){
html +='<option value="'+i+'">'+j+'</option>';
})
}
/**
* finaly populat ethe category data
*/
$('[name="category"]').html(html);
}
})
})
})
})(jQuery)
</script>
Change the portion as per yours...
Use this approach to detect changing value of select tag.
$( "#brand" ).change(function() {
var myOption = $(this).val();
// use ajax to get data for 'category' select by using "myOption"
});
then when you get ajax response add new select tag with
for (var i = 0 ; i < response.length; i++)
{
$('#category').append('<option>'+response[i]+'</option>')
}
I still don't get the required answer. Below is my view.
<select name="brand" class="form-control" id="brand" required>
<?php
if($items) {
foreach($items as $key) {
?>
<option value="<?php echo $key->brand_id ?>">
<?php echo $key->brand_name ?>
</option>
<?php
}
}
?>
</select>
<select name="category" class="form-control" id="category" required>
</select>
Ajax:
<script>
$(function() {
$("#brand").on('change', function() {
var brand = $(this).val();
$.ajax ({
type: "post",
url: "<?php echo base_url(); ?>receiving/showCategory",
dataType: 'json',
data: 'brand='+brand,
success: function(msg) {
var options;
for(var i = 0; i<msg.length; i++) {
options = '<option>'+msg.category[i].category_name+'</option'>;
}
$('#category').html(options);
}
});
});
});
</script>
My Controller:
function showCategory() {
if($this->session->userdata('success')) {
$brand_id = $this->input->post('brand');
$data['category'] = $this->item_model->category($brand_id);
echo json_encode($data);
} else {
//If no session, redirect to login page
redirect('login', 'refresh');
$this->load->helper('url');
}
}
My category table contains: category_id, category_name, brand_id.

How to get the selected text from form_dropdown?

I can't get the text in form_dropdown it always return the option value. Please help.
view
<?php echo form_open_multipart('upload/do_upload');?>
<?php
$cont ='';
$dept='';
foreach($level->result() as $row) {
$cont = $row->userlevel;
$dept = $row->department;
}
if(strtoupper($cont)=="USER") {
echo "<strong>".$dept." </strong>";
}
else {
echo form_dropdown('department_name', $dept_name,'','id="department_name"');
}
?>
<br/><br/>
<div class="btn-group">
<span id="status2"><?php echo form_dropdown('document_name', $document_name, '', 'id="document_name"'); ?></span>
</div>
<br/><br/>
<label for="file">Select File To Upload:</label>
<input type="file" name="userfile" multiple class="btn btn-file"/>
</br></br>
<input type="submit" value="Upload File" class="btn btn-primary"/>
<?php echo form_close(); ?>
<script>
window.onload = function() {
var form_data = {
dept_name: "<?php echo $dept; ?>",
ajax: 1
};
$.ajax({
url:"<?php echo site_url("document/document_dept_received"); ?>",
data:form_data,
type:'POST',
success: function(msg){
document.getElementById("status2").innerHTML = msg;
}
});
};
$("#department_name").change(function() {
var form_data = {
dept_name: $("#department_name option:selected").text(),
ajax: 1
};
$.ajax({
url:"<?php echo site_url("document/document_dept_received"); ?>",
data:form_data,
type:'POST',
success: function(msg){
document.getElementById("status2").innerHTML = msg;
}
});
});
</script>
controller
$upload_data = $this->upload->data();
$data['thumbnail_name'] = $upload_data['raw_name']. '_thumb' .$upload_data['file_ext'];
$file_array = array(
'image' => $data['thumbnail_name'],
'image_name' => $upload_data['file_name'],
//'description' => "",
'date_created' => date('Y-m-d H:i:s', now()),
'date_modified' => date('Y-m-d H:i:s', now()),
'author' => $this->session->userdata('username'),
'size' => $upload_data['file_size'],
'type' => $upload_data['image_type'],
'width' => $upload_data['image_width'],
'height' => $upload_data['image_height'],
'document_name' => $this->input->post("document_name"),
'department' => $this->input->post("department_name"),
//'notes' => "",
);
when I try this...
print_r($this->input->post("document_name"));
print_r($this->input->post("department_name"));
it shows 1 and 1...
what I want is the text not the id or value of options.
Example: I selected the IT Department and Folder 1, it will display/record IT Department and Folder 1 to database.
Check this: http://jsfiddle.net/Lev0sjjx/2/
Note: The jquery code is just for demonstration purposes
HTML
<select id="test">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
Javascript / jQuery
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
$(function() {
$('#test').change(function() {
var text = getSelectedText('test');
alert(text);
});
});
Exchange array values and keys:
$dept_name = array_flip($dept_name);
form_dropdown('department_name', $dept_name,'','id="department_name"');
Same for $document_name.
This switches from <option value="id">name</option> to <option value="name">id</option>.
If you need <option value="name">name</option>, rebuild the array to get a name 2 name relationship.
$dept_names2 = array();
foreach($dept_name as $item_id => $item_name)
{
$dept_names2[$item_name] = $item_name; // name as key and value
}
form_dropdown('department_name', $dept_names2,'','id="department_name"');
An array with structure "name=>name" will work with your ajax requests, too - because you are using $("#department_name option:selected").text(). so you are already working with the names, not the ids. no adjustment needed.

Bind on change event to a <select> populated by ajax request

I have in my projects two elements, the first one have a change listener that populates the second one like this.
<select id="user_id" style="width: 100%;">
<option value=""></option>
<?php foreach ($clients as $client) : ?>
<option value="<?php echo $client['Client']['id'] ?>"><?php echo $client['Client']['name'] ?></option>
<?php endforeach; ?>
</select>
<select id="pet_id" style="width: 100%;" disabled>
<option value=""></option>
</select>
--
$('#user_id').change(function() {
var client = {
client_id: $(this).val()
};
$.ajax({
type: "POST",
url: "<?php echo Router::url(array ('controller' => 'grooming', 'action' => 'getClientById')); ?>",
data: client,
success: function(data)
{
var json = JSON.parse(data);
if (json.result === "success") {
$('#pet_id').select2('data', null);
$('#pet_id').empty();
$.each(json.list, function()
{
$('#pet_id').append($("<option/>").val(this.breed_id).text(this.name));
});
if(!$('#pet_id').is(':enabled')){
$('#pet_id').removeAttr('disabled');
}
}
else
{
$('#pet_id').attr('disabled', 'disabled');
$('#pet_id').select2('data', null);
$('#pet_id').empty();
}
}
});
});
Now I have to add another change listener to the second selector (#pet_id) but it is not working any of these alternatives.
$('#pet_id').on('change',function (){
alert('finally worked :)');
});
$('#pet_id').bind('change',function (){
alert('finally worked :)');
});
¿What I'm doing wrong?
Thanks in advance.

Categories

Resources