This is my AJAX call:
function ck_loader() {
row_count = $('.grid-item').length || 0;
$.ajax({
type: "POST",
url: baseURL + "welcome/load_more",
data: {offset: row_count, numbdata: permaData},
datatype: 'json',
success: function (response) {
if (response === "") {
$grid.packery();
}
} else {
var $response = $(response);
$(".grid").append($response);
$grid.packery( 'addItems', $response);
$grid.packery();
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
//alert("ERROR");
}
});
so offset counts number of elements (rows) that are visable at the moment, and it helps control the offset of database (loading 15 elements per call)
numbdata: permaData is a variable where I'm saving the filter selection, so my menu has a filter selection, and data from there is saved in a variable (when someone press "video" filter, it saves "video" inside of permaData)
It connects to:
public function load_more()
{
$offset = $this->input->post('offset');
if($offset)
{
$new_rows = $this->postovi_model->get_next_10($offset);
if(isset($new_rows))
{
$data['users'] = $new_rows;
//this will return (echo) html to the ajax success function
//CI takes care of making the correct response headers - sweet
$this->load->view('user_rows_view', $data);
}
else
{
echo ""; //return an empty string
}
}
}
There is a model included in this PHP script:
public function get_next_10($offset = 0)
{
$this->db->limit(15, $offset);
$this->db->order_by('date', 'asc');
$query = $this->db->get("postovi");
return $query->num_rows() > 0 ? $query->result_array() : NULL;
}
}
In this model I am missing WHERE and the WHERE filter is the same as $permaData.
Every filter should reset $Offset back to 0 and run Database for that content.
permaData starts with "*" before any filter is selected.
Change your model function to take two parameters instead of one:
public function get_next_10($offset = 0, $numbdata = false)
and then just call it like:
$new_rows = $this->postovi_model->get_next_10($offset, $numbdata);
while numbdata would be (you're passing that via the AJAX call anyway):
$numbdata = $this->input->post('numbdata');
and finally, just add the WHERE clause in the model.
Related
I'm working on a project where I have some jQuery code that is supposed to check if a certain row in the database exists. If the row does exist, The code within the success stage gets executed. But the problem I have with this script is when the 'checkdb' function gets executed the code within success happens even though the row doesn't exist in the database. What is causing this?
jQuery code
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
The jQuery above gets executed every minute, To check if the row is present.
The PHP code below is supposed to check if the row in the database exists. If it does, it should return a response which then ends up in the succeeding stage in jQUery. If it does not already exist, Do something else
PHP code
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing');
}
}
Why is it executing the succeeding stage even though the row does not already exist? Thanks in advance
response('content', 200, $headers) and `json()` helper also takes three param `json($data, status, $headers)`
methods take three parameters replace the content of the else
like
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing',404);
}
}
In jQuery, success block gets executed when response status code is 200. If you send status code as 404 which is in else block when DB is not exist, then error block will get executed instead of success. Laravel by default will send 200 as status code for AJAX requests in response.
Add dataType:"JSON"
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
datatype:'JSON',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
I try to load database data in my Select2 input. (Im working on CI)
Here's my code from the controller : transforms array in echo json
class Ajax extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('client');
}
public function returnClientsAjax(){
echo json_encode($this->client->getClients());
}
}
Model : returning an array of results
function getClients(){
return $this->db->query("SELECT idclient AS id, CONCAT(societe,' [', nom,']') as text FROM du_client WHERE (societe != '' AND nom != '') AND evo2012 >=2 AND type_client != 'Particulier' AND statut_client = 'Demandeur' AND idclient = 6141;")->result_array();
}
My Select2 :
$("#sel_clients").select2({
placeholder: "Search for an Item",
ajax: {
dataType: "json",
url: "http://commexpert.dev.local/ajax/returnclientsajax",
results: function (data) {
return {results: data};
}
}
});
The input still empty so, don't know what to do.
Thnaks :D
I think something is missing on your data results method. Here is my code from working ajax select2 component:
results: function (data) {
var results = [];
var id1 = data.id;
var name = data.text;
$.each(data.data, function(index, item){
results.push({
id: item[id1],
text: item[name].trim()+' : '+ item[id1]
});
});
return {results: results};
}
also, I'm having somewhat diff data call also:
data: function (term) {
try {
mirko = $(this).closest('[rendered]').find( "input[fparamname$=" + $(this).attr('flookupfiltref') + "]" ).val();
if (mirko.indexOf(' : ') >=0 ) { // pocetna vrijednost
mirko = mirko.split(' : ')[1].trim();
}
} catch(e){
mirko = '';
}
return {
sp_name: $(this).attr('objectname'),
fl_name: $(this).attr('fparamname'),
node_id: $(this).attr('node_id'),
bound: mirko,
q: term,
};
},
I'm having somekind of manipulation before sending or returning q to server,, but I hope that can help you for your service :)
hth, k
I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this
I am using a MVC and I have a button that is using an AJAX call to remove an uploaded image on the site.
This is my Model:
public function remove_document($documentID, $documentName)
{
$objData = $this->objDB
-> setStoredProc('attritionRemoveDocument')
-> setParam('documentID', $documentID)
-> setParam('documentName', $documentName)
-> execStoredProc()
-> parseXML();
return $objData->data->response;
}
The response back from this is either true or false.
Here is my controller:
public function deleteFile()
{
// Get the documentID we are removing
$documentID = $this->input->post('documentID');
$documentName = $this->input->post('documentName');
// Check if the file is even there
if (file_exists('./uploads/'.$documentName)){
// Remove file
unlink('./uploads/'.$documentName);
$removeFile = $this->submit_model->remove_document($documentID, $documentName);
return $removeFile;
}
}
And finally, my AJAX Call:
$('[name=deleteDocument]').click(function() {
var documentID = $(this).attr('documentID'),
documentName = $(this).attr('documentName');
//Delete the image
$.ajax({
type: 'POST',
url: '../deleteFile',
dataType: 'xml',
data: {
'documentID': documentID,
'documentName': documentName
},
success: function(msg) {
// On Success, remove the current file section
console.log(msg);
}
});
});
When i echo the $removeFile value in the controller, I see the true/false value however it never makes it to the success function of the AJAX call.
Any ideas?
in Controller
if the result is true
echo "OK"
if the result is false
echo "NO"
in your View and in success part
success: function(msg) {
if(msg=="OK"){
alert("DELETED");
}else{
alert("NOT deleted");
}
Your controller should not return BOOL if you are using it with ajax , Your AJAX call , should control the result by success method .
I have one file json.js and one php function in php file .in json.js i want to check value returned by php function if value returned by function is 0 jquery should perform :$(':input').prop('disabled', true); otherwise nothing –
function loadJson (table, id) {
$.get("json-object.php", {'table': table, 'id':id}, function (data) {
console.log(data);
$.each(data, function (k, v) {
if ($('input[name="'+k+'"]').is('input[type="text"]')) {
$('input[name="'+k+'"]').val(v);
}
if($('select[name="'+k+'"]').val(v)){
get_input_value(k,v);
}
if ($('input[name="'+k+'"]').is('input[type="checkbox"]')) {
get_input_value(k,v);
}
console.log(k+' ==> '+v);
// Here I want to check condition of php function if value returned by fucntion is 0 it should perform :$(':input').prop('disabled', true); otherwise nothing //
});
}, 'json');
}
My php function:
function ronly($id) {
//$id=$_POST['noces'];
$sql = "SELECT COUNT(noces) FROM alterdetail WHERE noces = '$id'";
$sql.=';';
//echo "QUERY <br/>";
//echo $sql;
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
if($row['COUNT(noces)'] > 0)
{ echo "you can not alter data";
return 0;
}
else
{
echo " data new ";
return 1;
}
}
You can't, as Javascript is client-side executed, and PHP is server-side executed ...
A "solution" would be to assign a Javascript variable into the PHP file that you'll read into the Javascript file, as variable are global.
Use jQuery if possible.
$('#result').load('ajax/test.php', function() {
alert('Function called');
});
Or try JQuery forms. Use a form to submit any data, and it'll give you the response as a text or JSon object.
http://jquery.malsup.com/form/#ajaxSubmit
Here is an example for you:
$('#anyForm').ajaxForm({
url: "process.php?proc=7",
dataType: 'html',
success: function(responseText) {
if(responseText == "0") {
$(':input').prop('disabled', true);
}
}
});