i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)
Related
i want to assign javascript variable value to php variable to loop products
here is my php code:
$products = wc_get_products( array(
'include' => $products_ids // `**i want to pass value from javascript here**`
) );
foreach ( $products as $product ) {
// fetching my product details
}
here is my js code:
(function($){
$(document).ready(function(){
$(document).on('change', '#myform', function(e) {
e.preventDefault();
data = $(this).serialize();
var settings = {
"url": "<?php echo WC_AJAX::get_endpoint( 'myajaxfunction' ) ?>",
"method": "POST",
"data": data,
}
$.ajax(settings).done(function (result) {
// i want to make $products_ids = result
// result value is array(1,2);
});
});
});
})(jQuery);
**
i want to make $products_ids = result so i can pass it in my php
code,
result value is array(1,2);
**
Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);
Parameters are not being passed to the model, so the sql query is not yielding results. It just shows nothing, not even errors. Why are not the parameters being passed to the model?The sql query in the database works correctly, the date before the variables is to ignore the time, since in the database the field is of type datetime
Controller
function __construct()
{
parent::__construct();
$this->load->model('M_Login');
$this->load->model('M_Porcentaje');
}
public function tabla_porcentaje(){
$fecha_ini = $this->input->post('fecha_ini');
$fecha_ter = $this->input->post('fecha_ter');
$data['consulta'] = $this->M_Porcentaje->tabla_porcentaje($fecha_ini, $fecha_ter);
$this->load->view('usuarios/test.php',$data);
}
Model
public function tabla_porcentaje ($fecha_ini, $fecha_ter){
$this->db->select("motivos_citas.descripcion_mot,COUNT(*) AS cantidad_motivos, (SELECT COUNT(motivos_citas.descripcion_mot)* 100 / COUNT(citas.id_ci) FROM citas AS citas WHERE date(citas.fecha_ini) BETWEEN date('$fecha_ini') AND date('$fecha_ter') ) AS porcentaje");
$this->db->from("citas");
$this->db->join("motivos_citas","citas.id_mot=motivos_citas.id_mot");
$this->db->where("date(citas.fecha_ini) BETWEEN date('$fecha_ini') AND date('$fecha_ter') ");
$this->db->group_by("motivos_citas.descripcion_mot");
$consulta = $this->db->get();
return $consulta->result();
}
AJAX
<script>
$(document).ready(function(){
$("#btn_buscar").click(function(evento){
var fecha_ini = $("#fecha_ini").val();
var fecha_ter = $("#fecha_ter").val();
$.ajax({
url: "<?php echo base_url();?>C_Porcentaje/tabla_porcentaje/",
type: 'post',
data: { "fecha_ini": fecha_ini, "fecha_ter": fecha_ter },
success: function(response){
alert($("#fecha_ini").val());
alert($("#fecha_ter").val());
window.open('<?php echo base_url();?>C_Porcentaje/tabla_porcentaje/', '_blank');
}
});
});
});
</script>
Your binding is not okay. You should use :
$(document).on('click', '#buscar',function(url){
Try using json_decode(file_get_contents("php://input")) rather than $this->input->post() if the controller will read the data.
public function tabla_porcentaje(){
$input_post = json_decode(file_get_contents("php://input"));
$data = array (
'fecha_ini' => $input_post->fecha_ini,
'fecha_ter' => $input_post->fecha_ter
);
$this->load->model('M_Porcentaje_PDF');
$this->M_Porcentaje_PDF->tabla_porcentaje($data);
}
I have a users table in my database that stores an ip address.
I have an api that gets the users latitude and longitude.
Firstly, I need to get every users lang and long.
At the moment, my code is only returning the last user in my database's lang and long.
This is my code for trying to return every clients long and langs:
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$username_ = $users_['username'];
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
}
Then I return this to my home PHP page using:
$response = array('client_latitude'=>$client_latitude,'client_longitude'=>$client_longitude);
echo json_encode($response);
I recieve the AJAX request with the following JS / JQUERY code:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#lat').html(data['client_latitude']);
$('#long').html(data['client_longitude']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
And then finally, I try and display these in div's for testing.
Eventually, I want them to go in to the jVectorMap Markers JS code so It can plot markers on my map from each users lang and long.
But for now, It's not getting each users lang and long. Only the last user in my database's.
UPDATED CODE
The code Sumarai posted below isn't working.
It is not updating the div id - all-the-coordinates.
Does anyone know what's wrong with my version ?
I am using some different code to the question I asked. I have been using it from the start but didn't post it here because I didn't think it would be this difficult.
My new script is the same but I am calling them in separate files now because I am already calling an array in my other file (get_dash_settings).
This is my script in my main PHP file:
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
$.ajax({
url: "includes/get_dash_map.php",
context: document.body,
type: 'POST',
data: {get_data_:true},
success: function(value_) {
const data_ = JSON.parse(value_);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${data_['client_latitude']}, ${data_['client_longitude']}`);
$parent.append($element);
}
},
complete:function(){
setTimeout(fetchOnline,5000);
}
});
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
My get_dash_map.php:
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = ['client_latitude' => $client_latitude,'client_longitude' => $client_longitude];
}
echo json_encode($response);`
Since you want to get a bunch of coordinates back, it makes sense to return them in an array of sorts. You are currently only getting the last one, because you are overwriting the values. Make an entry, then add that entry to the response as an array item. You can easily create a new array item with the [] suffix. $response[] = $x will add an array item to $response containing $x.
$user_grab = mysqli_query($con, "SELECT * FROM users");
$response = [];
while($users_ = mysqli_fetch_array($user_grab)) {
$client_ip = $users_['ip'];
//This is for getting each users location on our map
$ip = $client_ip;
$geocode = file_get_contents("http://freegeoip.net/json/{$ip}");
$output = json_decode($geocode);
$client_latitude = $output->latitude;
$client_longitude = $output->longitude;
$response[] = [
'client_latitude' => $client_latitude,
'client_longitude' => $client_longitude
];
}
echo json_encode($response);
You obviously need to change your javascript too, as it currently expects an Object back with two keys, but you now get an Array of Objects back.
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
type: 'POST',
data: {get_data:true},
success: function(value) {
const data = JSON.parse(value);
const $parent = $('#all-the-coordinates');
for (const row of data) {
const $element = $('<span></span>');
$element.text(`${row['client_latitude']}, ${row['client_longitude']}`);
$parent.append($element);
}
}
})
}
$(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
with in the html
<div id="all-the-coordinates"></div>
jQuery code of ajax function is as follows:
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) { alert(result.join('\n'));
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
PHP code snippet is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
list($data) = prepare_response($request);
$smarty->assign('data', $data);
} else {
$data = $objUserLogin->GetResponse();
echo $data;
}
die;
break;
In PHP code the $data contains data in following manner :
<pre>Array
(
[id] => 23212
[zip_code] => 28445
[place_name] => Holly Ridge
[state_code] => NC
[created_at] => 1410875971
[updated_at] => 1410875971
)
</pre>
From the above data(i.e. response which will be available in variable result in ajax response) I want to access only two fields place_name and state_code.
I tried printing the content of result variable using alert(result) in console but I get the word Array
How to achieve this is my doubt?
Thanks in advance.
You should encode your result to json. So instead of the statement echo $data
use
echo json_encode($data);
it will return your result in json format. like
{"id":23212,"place_name":"Holly Ridge"...}
and in your javascript your can access your data