I have a jQuery function that gets data from a form and puts it as a string (for now) into an #content.
$(document).ready(function() {
$('form').submit(function() {
var results = $(this).serialize();
var url = '<php? echo JURI::base(); ?>index.php?option=com_mls&task=ListData&' + results;
$('#content').html(url);
return false;
});
});
So, I know how to build the query string from the form.
I have a task in my controller that runs a mySQL query string from the URL.
function ListData()
{
error_reporting(E_ALL);
$db =& JFactory::getDBO();
$sort = JRequest::getVar('sort');
...some other stuff...
$query = [some big nasty thing]
$db->setQuery($query);
$array = $db->loadRowList();
return $array;
}
So I know how to query the mySQL DB and get an array().
Then, I have a PHP script that pulls the array data into HTML format:
<?php
$array = $this->disparray;
foreach($array as $key => $value){
$mlsnum = $value['1'];
...some other data gets....
echo '<div>' . $mlsnum . '</div>';
}
?>
Here's where I'm stuck. I don't know how to get the URL query from jQuery to the controller task and then get the array() returned by that task into the PHP script which would build the HTML and then get AJAX/jQuery to put that data into #content.
Action is going on in 3 steps.
First ajax call view.raw.php then you load/add/delete some data from model, and customize it as you want. Then you print it in JSON format - send it back to ajax, and then ajax put that into html.
$(document).ready(function() {
var url = '<php? echo JURI::base(); ?>index.php?option=com_mls&task=ListData&format=raw&' + results;
$.ajax({
url: url,
dataType: 'json',
success: function(json) {
if (json['output']) {
$('#content').html(json['output']);
}
if (json['redirect']) {
location = json['redirect'];
}
}
});
});
this will communicate with
/com_mls/(default_view)/view.raw.php
in there, you should probably do something like
class mlsView_your_view... extends JView
{
public function display($tpl = null) {
$task = JRequest::getCmd('task', 0);
// see what should we do now
switch( $task ){
case 'ListData':
$data = $this->get_data();
break;
}
// Get the document object.
$document = JFactory::getDocument();
// Set the MIME type for JSON output.
$document->setMimeEncoding('application/json');
// Change the suggested filename.
//JResponse::setHeader('Content-Disposition','attachment;filename="resp.json"');
// Output the JSON data.
echo json_encode($data);
}
function get_data() {
// load model
$model = $this->getModel('ajax');
// get data from model
$data = $model->getSomeData();
if( is_null($data) ){
return array( 'error' => 'missing data.');
}
$data['output'] = $model->prepareData($data);
return array( $data );
}
....etc....
}
Related
I have a calling js script
setInterval(function(){
$.get( "/fetch-data", function( data ) {
console.log(data);
});
},1000);
and my Routes look like this
Route::get('/fetch-data', 'PageController#fetchData');
my controller method
public function fetchData()
{
$results_array = [];
$file = new \SplFileObject('file.csv');
$file->setFlags(\SplFileObject::READ_CSV);
foreach ($file as $row) {
$results_array[] = $row[0];
$results_array[] = $row[1];
$results_array[] = $row[2];
$results_array[] = $row[3];
...
}
return response()->json($results_array);
//$json = response()->json($results_array);
//return view('view.blade',compact($json));
}
Note that with return response()->json($results_array); the raw json text is displayed directly on the page. Not what I want.
While return view('view.blade',compact($json)); returns the whole html file. Still not what I want.
What I would like to achieve is that the raw json text that was returned from the controller be pass to the callback from the calling js script.
Any ideas?
The code works as expected.
setInterval(function(){
$.get( "/fetch-data", function( data ) {
// code now works
});
},1000);
and this question was answered HERE already.
I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);
I have an issue when using AJAX to filter data on the table. I have a select box and table on the page. I want to filter data on the table using the select box. example, if the user chooses value 'Ganjil' on the select box then table just show row that has data 'Ganjil'.
AJAX Script:
<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:'<?php echo base_url("search/filter") ?>',
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
Controller:
public function filter()
{
$this->load->helper('url');
$key = $this->input->post('semester');
if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}
echo json_encode($data);
}
Model:
public function getGanjil($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
public function getGenap($key)
{
$sql = "SELECT * FROM tahunajaran WHERE jenis = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
When I choose the value of select box table show nothing.
1st Solution : use $key = $this->input->post('key'); in controller as you access key value pair. So in AJAX call $key is Key. You cant access javascript variable semester like $this->input->post('semester'); in your code.
2nd Solution :
in ajax call url:'<?php echo base_url("search/filter/key/") ?>'+semester
Use $key='' as parameter in controller method .
public function filter($key='') as there is no $key accessible in your controller method. You should be accessing in your controller as a parameter. So you can use it in model . In your case there is no $key coming as a parameter in controller.
Also in your code use
$key = $this->input->post($key); as we access $key thru parameter.
-------------Update 1----------
As per your requirement , AJAX call
<script>
var semester = $("#inputJenis").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("search/filter/key/") ?>'+semester,
data:"key="+semester,
dataType:'json',
success:function(data){
$("#tableData").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
And your controller should be like this ->
public function filter($key = '')
{
$this->load->helper('url');
if ( $key == 'Ganjil' ) {
$this->load->model('filter_model');
$data = $this->filter_model->getGanjil($key);
} else {
$this->load->model('filter_model');
$data = $this->filter_model->getGenap($key);
}
echo json_encode($data);
}
I am using PHP function to display geofences. I want to pass javascript variable to php function in same file without page refresh.
function load(id,type){
if(type===2){
window.location.href="basic.php?idd=" + id; // i want to change code here
<?php
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
PHP function is:
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($result)) {
$d[] = $myrow;
}
return $d; //returns result in array
}
javascript window.location.href passes javascript value to php function but it reloads page also.
If you're using jQuery, you can use $.ajax(). It allows you to send data to your server and do something with the response.
Eg:
$.ajax({
type: 'POST',
data: myvar
success: function(Response) { console.log(Response); }
});
will send myvar to your server (with a bit of tweaking of parameters of course) and log whatever the server sends back to your browser console.
Have a read of what you can do with jQuery.
You can do this using jQuery. Basically you don't refresh the page, you just do an async query to the server and you get the response. In the following example the response is showed in alert box.
Your "index" file:
function load(id,type)
{
$.post("basic.php", { idd: idd }, function(data){
alert(data);
});
}
and basic.php
<?php
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($rs)) {
$d[] = $myrow;
}
return $d;
}
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
I'm using codeigniter, I had a problem to process a data using jQuery $.post function. I want to send a value such as subjectid to ajax_get_subject_credit function and retrieve another field within same database table. The result shows on another text field. Here is my code.
View:
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(data){
$('#chours' + id).val(data); });
This get a value from drop-down and I want to make a text field automatic populate from drop-down. #chours is a text field ID.
Controller:
function ajax_get_subject_credit($result)
{
$this->db->select('subjectid, subjectcredit');
$query = $this->db->get('ref_subject');
$result = $query->result_array();
$query->free_result();
$subjectid = array();
foreach($result as $row)
{
$result = $result + array($row['subjectid'] => $row['subjectcredit']);
}
return $result;
}
Modified In Controller
I also tried using this statement in controller for direct calling the field but still no success :
function ajax_get_subject_credit($subjectid)
{
$this->db->select('subjectid, subjectcredit');
$this->db->where('subjectid',$subjectid);
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
echo $credithour;
}
I am going to provide a general example here
in view file
$.post('<?php echo site_url("test/test"); ?>', {'id':1}, function(response){
if(response.success)
{
alert(response.message);
} else
{
alert('Something went wrong!!');
}
}, 'json');
in controller Test.php
function test()
{
$id = $this->input->post('id');
//do additional stuff
$result = 'i am coming right out of controller!! ';
echo json_encode(array('success' => true, 'message' => $result));
}
Dont use return to return value to AJAX. use echo
change this,
return $result;
to
echo $result;
If you want your method to return an array that the javascript can use to populate a dropdown, you probably don't want to return a string.
Try something like this:
function ajax_get_subject_credit()
{
$query = $this->db->select('subjectid, subjectcredit')->get('ref_subject');
$result = $query->result();
$out = array();
foreach($result as $row) {
$out[$row->subjectid] = $row->subject_credit;
}
header('Content-Type: application/json');
echo json_encode($out);
}
This will return a JSON array to your view, which your javascript method can use to populate the dropdown with values and labels.
Here is my Result:
In View :
function subjectid_change(id, subjectid){
//Set value
setValue(id, subjectid);
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(response){
if(response.success)
{
$('#chours' + id).val(response.value);
} else
{
alert('Something went wrong!!');
}
}, 'json'); }
And my controller :
function ajax_get_subject_credit()
{
//Get Post Value
$subjectid = $this->input->post('subjectid');
//Select subjectid,subjectcredit FROM
$this->db->select('subjectid, subjectcredit');
//Where subjectid = 'subjectid'
$this->db->where('subjectid',$subjectid);
//Database name
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
$result = $credithour;
echo json_encode(array('success' => true, 'value' => $result));
}
Thanks to everybody who helped me.