Issue with Loading JSON data from PHP to Knockout - php

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. :)

Related

Ajax - variables are seen in chrome network tab but they don't seem to pass to the PHP function

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

PHP array to javascript conversion altering the index values

I have a javascript function which gets user info from database via ajax. It has following code.
var temp_id = new Object;
function checkRequests() {
$.ajax({
url: "bin/inc/classes/mechanism_class.php",
type: "POST",
data: {'checkrequest': '1'},
success: function(data1) {
for(var i=0; i<jQuery.parseJSON(data1).length; i++) {
$.ajax({
url:"bin/inc/classes/mechanism_class.php",
type: "POST",
data: {'checkrequest2': jQuery.parseJSON(data1)[i]},
success: function(data) {
requestPopper(data);
}
}).error(function() {
});
}
}
}).error(function() {
});
}
function requestPopper(data) {
var id = jQuery.parseJSON(data)[0];
var firstname = jQuery.parseJSON(data)[1];
var lastname = jQuery.parseJSON(data)[2];
var imagedir = jQuery.parseJSON(data)[3];
var imageext = jQuery.parseJSON(data)[4];
var imgsrc = 'uploads/'+imagedir+'/'+'thumbs/'+imagedir+'size2.'+imageext;
if($('#'+'requests_content_'+id).length == 0) {
if($('.requests_content').length == 0) {
$('#requests').after('<div id="dropdown_1"><div class="requests_content" id="requests_content_'+id+'"><a id="senders_name" href='+'profile.php?user='+id+'>'+firstname + ' ' +lastname+'</a><div id="acceptbutton">Accept</div><div id="rejectbutton">Reject</div></div></div>');
temp_id.id = id;
} else {
$('#'+'requests_content_'+temp_id.id).after('<div class="requests_content" id="requests_content_'+id+'"><a id="senders_name" href='+'profile.php?user='+id+'>'+firstname + ' ' +lastname+'</a><div id="acceptbutton">Accept</div><div id="rejectbutton">Reject</div></div>');
}
}
}
Also, the PHP class that handles ajax requests has the following code
class RequestsAndAlerts {
public function hasRequests() {
if(isset($_POST['checkrequest'])) {
$current_user = $_SESSION['cred_regiden'];
$query1 = "SELECT * FROM `requests` WHERE `ReqReceiver` = '$current_user' ORDER BY `sentdatetime` DESC";
$senders = array();
if($query_run1 = mysql_query($query1)) {
while($res = mysql_fetch_assoc($query_run1)) {
$sender = $res['ReqSender'];
array_push($senders, $sender);
}
}
echo json_encode($senders);
}
}
public function sendRequestInfo() {
if(isset($_POST['checkrequest2'])) {
$sender = $_POST['checkrequest2'];
$current_user = $_SESSION['cred_regiden'];
$info_request_senders = array();
$query1 = "SELECT * FROM `user_credentials` WHERE `cred_regiden` = '$sender'";
$query2 = "SELECT * FROM `prof_image` WHERE `cred_regiden` = '$sender'";
if($query_run1 = mysql_query($query1)) {
while($res = mysql_fetch_assoc($query_run1)) {
$info1 = $res['cred_regiden'];
$info2 = $res['cred_fname'];
$info3 = $res['cred_lname'];
array_push($info_request_senders, $info1);
array_push($info_request_senders, $info2);
array_push($info_request_senders, $info3);
}
}
if($query_run2 = mysql_query($query2)) {
while($res2 = mysql_fetch_assoc($query_run2)) {
$info4 = $res2['image_dir'];
$info5 = $res2['image_extension'];
array_push($info_request_senders, $info4);
array_push($info_request_senders, $info5);
}
}
echo json_encode($info_request_senders);
}
}
$RAA = new RequestsAndAlerts;
$RAA->hasRequests();
$RAA->sendRequestInfo();
Now, I want to extract the data of people who has sent current user a friend request. For testing purpose I sent the user1 two friend requests from user2 and user3 and log in from user1 account, when I press requests button, on first click user1's info div is at the top and user2's info div is at the bottom.. This is good up to here.. But when I click again, they swap places.. But they do it in irregular pattern. I don't want this to happen. I want the user1 to always be on the top and user2 to be on the bottom of him according to as whose request is sent first. But I did this in mysql.. I arranged the requests in DESC order in mysql.. It should have arranged the div as "user1 on top" and "user2 on bottom".. But this happens randomly.
I guess this is due to the fact that json_encode randomizes the indexes of array.. But I'm not sure.. Help me guys... Just point out where I'm wrong.
The problem is with your multiple ajax call.
Note that ajax is asynchronous HTTP request
For example you have user1 and user2, in the for loop first ajax call will be initialized for getting the user1 details, hence ajax is a asynchronous it will not wait for that requst. Tt will send next the ajax request immediately for getting the user2 results.
If request 2 completes before req1 .Then you will get the above error.
Solution:
1. Get the user details in the first ajax call itself.
Or
2 .Make the second ajax call as a synchronous.
I choose the first option.

Rating not add with ajax in wordpress

I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)

Pass objects card_id and coordinates in fabric.js in array to JQuery .post

I'm using this function to try and send my objects coordinates and id to my php script. I'm not sure how to setup how to get the card_id and it's top and left coordinates into the post so I can retrieve them in my php script as one array. I have the all the values alerting properly but how do I pass them make sure I'm getting the proper ones on the other end and that the coordinates go with the card_id?
document.getElementById('rasterize-scoutlog2').onclick = function() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}
else {
canvas.deactivateAllWithDispatch().renderAll();
//window.open(canvas.toDataURL('png'));
//var strDataURI = (canvas.toDataURL('png'));
//strDataURI = strDataURI.substr(22, strDataURI.length);
var objsInCanvas = canvas.getObjects();
objsInCanvas.forEach(function(object) {
var stickycard_ids = [object.card_id];
var stickycard_top = [object.top];
var stickycard_left = [object.left];
if(object.card_id != null){
stickycard_ids.forEach(function(stickycard_idarr) {
alert(stickycard_idarr+stickycard_top+stickycard_left);
});
}
});
var scoutlogname = $('#scoutmapselectcard').val();
$.post("maps/savescout_log.php",
{
//str: strDataURI,
// queryStr: queryStr,
scoutlogname: scoutlogname,
//**** stickycard_idarr: stickycard_idarr
},
function(data){
if(data == "OK"){
$("#msg").html("Scout Log saved to account!").css({'color':"green",'font-weight':"bold"});
}
if(data=="EMPTY"){
$("#msg").html("Please Enter a name for your Scout Log!").css({color:"red"});
}
if(data=="WRONGCH"){
$("#msg").html("Only A_Z,a-z,0-9-_ allowed in Scout Log name!").css({color:"red"});
}
if(data=="EXIST"){
$("#msg").html("Scout Log name all ready exists!<br> Delete the existing one before saving.").css({color:"red"});
}
if(data=="ERROR"){
$("#msg").html("Scout Log not saved!").css({color:"red"});
}
window.setTimeout(function() {
$('#msg').empty();
}, 5000);
});
}
};
I got the objects and their details all going to arrays. I used the .push method to populate the arrays with the objects values in the foreach loop. Now on to the php end to insert them into the mysql database table.
document.getElementById('rasterize-scoutlog').onclick = function() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}else {
canvas.deactivateAllWithDispatch().renderAll();
//window.open(canvas.toDataURL('png'));
//var strDataURI = (canvas.toDataURL('png'));
//strDataURI = strDataURI.substr(22, strDataURI.length);
var objsInCanvas = canvas.getObjects();
var stickycard_ids = [];
var stickycard_top = [];
var stickycard_left = [];
var stickycard_type = [];
objsInCanvas.forEach(function(object) {
if(object.card_id != null){
stickycard_ids.push(object.card_id);
stickycard_top.push(object.top);
stickycard_left.push(object.left);
stickycard_type.push(object.cardtype);
}
});
var scoutmapname = $('#scoutmapselectcard').val()
var scoutlogname = $('#scoutlogname').val();
$.post("maps/savescout_log.php",
{
//str: strDataURI,
//queryStr: queryStr,
scoutlogname: scoutlogname,
scoutmapname: scoutmapname,
stickycard_ids: stickycard_ids,
stickycard_top: stickycard_top,
stickycard_left: stickycard_left,
stickycard_type:stickycard_type
},
function(data){
if(data == "OK"){
$("#msg").html("Scout Log saved to account!").css({'color':"green",'font-weight':"bold"});
}
if(data=="EMPTY"){
$("#msg").html("Please Enter a name for your Scout Log!").css({color:"red"});
}
if(data=="WRONGCH"){
$("#msg").html("Only A_Z,a-z,0-9-_ allowed in Scout Log name!").css({color:"red"});
}
if(data=="EXIST"){
$("#msg").html("Scout Log name all ready exists!<br> Delete the existing one before saving or enter a new name.").css({color:"red"});
}
if(data=="ERROR"){
$("#msg").html("Scout Log not saved!").css({color:"red"});
}
window.setTimeout(function() {
$('#msg').empty();}, 5000);
});
}
};
Here's the php that will insert those mutiple arrays into into mysql using PDO. I'm using the stickycard_ids as the indexing value then posting that and the other assiociated array values to a new row every time the stickycard_ids value changes.
for ($i=0; $i < count($_POST['stickycard_ids']); $i++ ) {
$card_id = $_POST['stickycard_ids'][$i];
$cardtype = $_POST['stickycard_type'][$i];
$top_y = $_POST['stickycard_top'][$i];
$left_x = $_POST['stickycard_left'][$i];
$sql ="INSERT INTO tablename (scoutmapname,scoutlogname,card_id,left_x,top_y,cardtype)
VALUES (:scoutlogname,:card_id,:left_x,:top_y,:cardtype)";
$q = $pdo->prepare($sql);
$q->execute(array(':scoutmapname'=>$scoutmapname,':scoutlogname'=>$scoutlogname,':card_id'=>$card_id,':left_x'=>$left_x,':top_y'=>$top_y,':cardtype'=>$cardtype));
}

edit in angularjs using php

i wish to fetch the values to be edited, in the textbox, i.e. 1st the textboxes will be empty, then when user clicks on the edit link the values should be filled in the textbox. User can change the values, click on save button and the new values will be updated. following is the code:
html code:
Save
controller:
$scope.fetch = function(id) {
var elem = angular.element($element);
var dt = $(elem).serialize();
dt = dt+"&id="+id;
dt = dt+"&action=fetch";
alert(dt);
console.log($(elem).serialize());
$http({
method: 'POST',
url: 'php/products.php',
data: dt,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status) {
//~ $scope.status = status;
//~ $scope.data = data;
$scope.rs = data;
console.log($scope.rs); // Show result from server in our <pre></pre> element
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
products.php:
if($action == 'fetch') {
$query = '
SELECT
*
FROM
product
WHERE
`product_id` ="' . $_POST['id'] . '"
';
$result = mysql_query($query) OR die(mysql_error());
$data = array();
$row = mysql_fetch_assoc($result);
echo json_encode($row);
//print_r($row);
}
this code is not working- when user clicks on edit link of any user, the textboxes get filled with the value- Object object. If ti print the value then it gets printed but when i try to assign it to the textbox, it gets filled with Object object.
where am i getting wrong? how do i solve this?
Don't use jQuery to get/set fields anymore if you're using Angular.
<input type="text" ng-model="field1">
Controller:
//set
$scope.field1 = obj.field1;
//get
var f1 = $scope.field1;
You forgot to use the angular.fromJson function when receiving the response
.success(function(json, status) {
data=angular.fromJson(json);
//~ $scope.status = status;
//~ $scope.data = data;
$scope.rs = data;
console.log($scope.rs); // Show result from server in our <pre></pre> element
})
You might want to take a look into AngularPHP and save some time,

Categories