I am trying to only update the page when their are updates in the database but i am unsure how to do that.
I was thinking of comparing ids stored into the database because each ID is unique so if i make some sort of expression that compares the current array stored or picked up by AJAX to the ids in the database. But i am unsure how to compare ids and check if their is a new update
Any help would be appreciated
Controller
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$id = array();
$arr = array();
$arr2 = array();
foreach($queryresults as $row)
{
$id[] = $row->id;
$arr[] = $row->post;
$arr2[] = $row->img;
}
$data = array();
$data[] = $id
$data[] = $arr;
$data[] = $arr2;
echo json_encode($data);
}
View
<script type='text/javascript' language='javascript'>
$('#getdata').click(function () {
$.ajax({
url: '<?php echo base_url().'index.php/welcome/insertJSON';?>',
async: false,
type: "POST",
success: function(data) {
// thought i could do something like
if(data.change in database) do bla bla
var id = data[0];
var arr = data[1];
var arr2 = data[2]
}
})
});
</script>
There is a simple way to do this.
create a session variable and assign it the last id. than on the page take this session id on a hidden input.
Now when you are sending ajax request you can take hidden input's value and send it to controller function where you can query for last id. If last id from query is not equal to session id you should echo other wise echo 0. in ajax request check if response is coming from controller and it is greater than 0 change the page with new id. Than update the session id with ajax
Related
I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database
Am I on the wrong path here?
I have a ajax call to upload some files.
I then create a array on the PHP side and send it back as JSON. But im not sure if the JSON format is correct.
Problem is I want to populate a dataTable with the returned JSON data, but I having difficulty reading the data. If its a single file then its fine and it works, but as soon as its more than one file
PHP CODE
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
$json = array();
$json[] = $row;
echo json_encode($json);
on the JQuery/AJAX call side
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: './inc/MediaScripts.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(html) {
var t = $('#vidlib_dtable').DataTable();
var obj = eval(html);
$.each(obj, function(key,value) {
t.row.add( [
value.name,
value.title,
value.path,
value.duration,
value.uploaded_date,
value.uploaded_by,
value.keyword,
value.comment,
] ).draw();
});
});
});
});
The original return has more columns, hence the above columns in the dataTable add.
The return looks like multiple (singular) JSON arrays.
[{"uuid":"236","name":"Koala.jpg"}]
[{"uuid":"237","name":"Lighthouse.jpg"}]
I was wondering if it should not take the shape of something like this
[{"uuid":"236","name":"Koala.jpg"}, {"uuid":"237","name":"Lighthouse.jpg"}]
If the format that I receive the data in is fine, how do I go about looping trhough the multiple arrays on the JQuery side?
That's because you are echo'ing 3 different JSON object arrays.
Each time your loop iterates you echo, the loop then re-creates the array and echo's the new JSON array.
$json = array();
//forloop{ START
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
array_push($json, $row);
//} END
echo json_encode($json);
Initialize your array before the loop, and echo it after it's been fully created.
We are making a website using PHP and Knockoutjs. We are able to sent the JSON data using $.ajax method in Knockoutjs.
But it is not loading the data requested initially.
PHP code
$students = $db->query("SELECT * FROM students WHERE status = 1");
$students_r = array();
while($row = $students->fetch_array()){
//default student data
$id = $row['id'];
$name = $row['name'];
$age = $row['age'];
//update status
//its false by default since
//this is only true if the user clicks
//on the span
//$name_update = false;
// $age_update = false;
//build the array that will store all the student records
$students_r[] = array(
'id' => $id, 'name' => $name, 'age' => $age,
);
}
echo json_encode($students_r); //convert the array to JSON string
and this is actually generating proper json data
[
{"id":"1","name":"monkey d. luffy","age":"15"},
{"id":"4","name":"son goku","age":"30"},
{"id":"5","name":"naruto uzumaki","age":"16"},
{"id":"6","name":"draco","age":"15"},
{"id":"10","name":"NIklaus MikaelSon","age":"1500"},
{"id":"16","name":"Elijah","age":"1000"},
{"id":"19","name":"Chitrank","age":"23"},
{"id":"20","name":"Rahul","age":"24"}
]
Now Knockout comes into play to show this data on the page, So here is the HTML page
function RefreshUser(data) {
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
};
var personModel = function(id, name, age){
var self = this; //caching so that it can be accessed later in a different context
this.id = ko.observable(id); //unique id for the student (auto increment primary key from the database)
this.name = ko.observable(name); //name of the student
this.age = ko.observable(age);
this.nameUpdate = ko.observable(false); //if the name is currently updated
this.ageUpdate = ko.observable(false); //if the age is currently updated
//executed if the user clicks on the span for the student name
this.nameUpdating = function(){
self.nameUpdate(true); //make nameUpdate equal to true
};
//executed if the user clicks on the span for the student age
this.ageUpdating = function(){
self.ageUpdate(true); //make ageUpdate equal to true
};
};
var model = function(){
var self = this; //cache the current context
this.person_name = ko.observable(""); //default value for the student name
this.person_age = ko.observable("");
this.person_name_focus = ko.observable(true); //if the student name text field has focus
this.people = ko.observableArray([]); //this will store all the students
this.createPerson = function(){
if(self.validatePerson()){ //if the validation succeeded
//build the data to be submitted to the server
var person = {'name' : this.person_name(), 'age' : this.person_age()};
//submit the data to the server
$.ajax(
{
url: 'refresher_save.php',
type: 'POST',
data: {'student' : person, 'action' : 'insert'},
success: function(id){//id is returned from the server
//push a new record to the student array
self.people.push(new personModel(id, self.person_name(), self.person_age()));
self.person_name(""); //empty the text field for the student name
self.person_age("");
}
}
);
}else{ //if the validation fails
alert("Name and age are required and age should be a number!");
}
};
this.validatePerson = function(){
if(self.person_name() !== "" && self.person_age() != "" && Number(self.person_age()) + 0 == self.person_age()){
return true;
}
return false;
};
$.getJSON("refresher_save.php", function(userModels) {
var t = $.map(userModels.people, function(item) {
console.log("Something");
return new RefreshUser(item);
});
self.people(t);
});
this.removePerson = function(person){
$.post(
'refresher_save.php',
{'action' : 'delete', 'student_id' : person.id()},
function(response){
//remove the currently selected student from the array
self.people.remove(person);
}
);
};
this.updatePerson = function(person){
//get the student details
var id = person.id();
var name = person.name();
var age = person.age();
//build the data
var student = {'id' : id, 'name' : name, 'age' : age};
//submit to server via POST
$.post(
'refresher_save.php',
{'action' : 'update', 'student' : student}
);
};
};
ko.applyBindings(new model());
Now here we are using $.getJSON to fetch all the JSON records, but it is not displaying the data on the page.
i can see little mistakes for example
this.people = ko.observableArray([]);
and others you should recheck your code i think they should be self.people..... self.person_age, later in your code you refer to them with self for example here
self.people.push(new personModel(id,
self.person_name(),self.person_age()));
you refer with self thats why the data is not loading you are not refering to the same object people
I see you have tried to create something based on a code from two sources (you have them scrambled), which are looking similar but simple are not the same (are not providing correct data).
First you are creating logic duplicity with RefreshUser() and personModel(). You should to left only personModel() as
var personModel = function(data){
var self = this;
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
this.age = ko.observable(data.age);
/* all the rest stays the same */
Then in createPerson() you should to update that line
self.people.push(new personModel(person));
Then finaly $.getJSON part should to looks like
$.getJSON("refresher_save.php", function(allData) {
var data = $.map(allData, function(item) { return new personModel(item) });
self.people(data);
});
and should be located at the bottom of model() view.
Thank you for your time, but my problem has been been solved, actually in my php script I was passing unused parameters, that cause the problem, when I removed those parameters, it worked and database values loaded when page refreshes. Thank you for your replies. :)
I am relatively new to cake and I am struggling with a custom filter that im making in order to display products based on which checkboxes have been ticked. The checkboxes get populated based on which attributes the user creates in the backend, i then collect all the values of the selected boxes into an array with javascript and post it to the controller, but for some reason I cannot access the controller variable named '$find_tags' in my view, it throughs undefined variable.
Here is my javascript and ajax which collects and posts correctly (when i firebug it 'data' in my controller has array values which im posting) so thats fine
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'data[ID]='+searchIDs;
$.post("",data,function(data){
console.log(data);
});
});
Here is my controller code which im assuming is where the fault lies
if ($this->request->is('post') ) {
$data = $this->request->data['ID'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
$this->set('find_tags', _($find_tags));
}
}
And here is my view code where i get Undefined variable: find_tags
foreach($find_tags as $all_tag)
{
echo $all_tag['Product']['name'];
echo '</br>';
}
Any help or suggestions would really be appreciated been struggling with this for a while now
If searchIDs is array of ids you just need to make the json of array and then send to your controller
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'ids='+JSON.stringify(searchIDs);
$.post("controller url",data,function(data){
console.log(data);
});
});
On php side you are getting wrong variable
if ($this->request->is('post') ) {
$data = $this->request->data['ids'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
}
$this->set('find_tags', _($find_tags));
}
I have a table that has sortable rows. The table is generated from a mysql database that has a field called "displayorder" that oders the table. When the user drags and drops rows, I want to use AJAX to submit those changes to the database whenever a user drops a row.
Currently, I can see the console.log() output from the success part of the AJAX call, and when i output the data there (order) it looks great, like this:
["order_1=1", "order_2=2", "order_4=3", "order_3=4"]
But according to Firebug, all that's getting passed in the $_POST is "undeclared".
How do I access that order variable from my indexpage_order.php file?
I have this jquery code:
<script>
$(document).ready(function() {
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index)
{
$(this).width($originals.eq(index).width())
});
return $helper;
};
var sortable = $("#sort tbody").sortable({
helper: fixHelper,
stop: function(event, ui) {
//create an array with the new order
order = $(this).find('input').map(function(index, obj) {
var input = $(obj);
input.val(index + 1);
return input.attr('id') + '=' + (index + 1);
});
$.ajax({
type: 'POST',
url: 'indexpage_order.php',
data: order,
error: function() {
console.log("Theres an error with AJAX");
},
success: function(order) {
console.log("Saved.");
console.log(order);
}
});
return false;
}
});
});
</script>
indexpage_order.php contains:
if(isset($_POST) ) {
while ( list($key, $value) = each($_POST) ) {
$id = trim($key,'order_'); //trim off order_
$sqlCommand =
"UPDATE indexpage
SET displayorder = '".$value."'
WHERE id = '".$id."'";
$query = mysqli_query($myConnection,$sqlCommand) or die (mysqli_error($myConnection));
$row = mysqli_fetch_array($query);
}
}
You can simply rewrite the js code that are generating the data for POST.
order = {}
$(this).find('input').map(function(index, obj)
{
return order[this.id] = index;
}
)
Rest should work in PHP.
Try $_REQUEST instead of $_POST on the PHP file for POST method with ajax.
convert the js array order to json object as ajax data needs to be in json using JSON.stringify. hence, it needs to be data:JSON.stringify(order), in the ajax function.
Or, use json_encode like this data: <?php echo json_encode(order); ?>, in the ajax function
order is an array. Convert the order to query string like this in your ajax script,
data: order.join('&'),
It looks like your sending your order in a JavaScript array
And when it arrives at your PHP, its unreadable.
If its an object look into the json_decode function.
If its an array, serialize the data before it goes, then unserialize on the php side.
PHP is unable to understand JavaScript array or objects unless they are encoded/serialized correctly.