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,
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
I'm trying to save some data to a database without the use of an html form and was wondering if anyone could help me as I'm no expert in PHP. So far I have got:
JQuery
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: //Data to send,
success: function () {
$('.success_message').html("success");
}
});
});
There is no issue at the first stage as all my values are stored in the variables correctly. I just don't know in what format to send them across to save.php.
save.php
<?php
require_once 'dbconfig.php';
//Connects to database
if($_POST)
{
//Not sure what to post here
$current_date = date('Y-m-d');
try{
$stmt = $db_con->prepare("INSERT INTO entry(user_id, date, weight, bmi, calories_consumed, calories_burned, calorific_deficit) VALUES(:user, :date, :weight, :bmi, :consumed, :burned, :deficit)");
$stmt->bindParam(":user", $user_id);
$stmt->bindParam(":date", $current_date);
$stmt->bindParam(":weight", $summary_weight);
$stmt->bindParam(":bmi", $summary_bmi);
$stmt->bindParam(":consumed", $summary_consumed);
$stmt->bindParam(":burned", $summary_burned);
$stmt->bindParam(":deficit", $summary_total);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
I'm not sure how to post this data to save.php and then how to process it to be sent to the database. I've also added a variable of current_date to send the current date to a field in the database.
Can anyone help me and fill in the blanks? Or maybe I'm going about this the wrong way?
Send your data in an object, like so:
// Declare data as an empty object
var data = {};
// Assemble the properties of the data object
data.summary_weight = $('#summary_weight').text();
data.summary_bmi = $('#summary_bmi').text();
data.summary_consumed = $('#summary_consumed').text();
data.summary_burned = $('#summary_burned').text();
data.summary_total = $('#summary_total').text();
data.user_id = $('#user_id').text();
$.ajax({
type: "POST",
url: "save.php",
// pass the data object in to the data property here
data: data,
success: function () {
$('.success_message').html("success");
}
});
Then, on the server side, you can access directly via $_POST superglobal:
$summary_weight = $_POST['summary_weight'];
$summary_bmi = $_POST['summary_bmi'];
// etc...
You can send all this data in the data parameter as given below:
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: {summary_weight: summary_weight, summary_bmi:summary_bmi, summary_consumed:summary_consumed, summary_burned: summary_burned, summary_total:summary_total, user_id:user_id },
success: function () {
$('.success_message').html("success");
}
});
});
And the, process it in save.php like this
$summary_weight = $_POST['summary_weight'];
and use it in the query to save it in database.
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.
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 wish to add a record in MySQL database through AngularJS and PHP. the record is added successfully but the AngularJS effect is not seen. that is the page is not automatically refreshed. below is the code was given:
controller:
$scope.add = function() {
var elem = angular.element($element);
var dt = $(elem).serialize();
//alert($element);
console.log($(elem).serialize());
$http({
method: 'POST',
url: 'php/add.php',
data: dt,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status) {
$scope.status = status;
$scope.data = data;
console.log(data);
data.push(this);
$scope.products = data; // Show result from server in our <pre></pre> element
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
index.html
<li ng-repeat="product in products" ng-model = 'products'>
{{product.description}}|{{product.name}} | edit | delete
<input type="hidden" name="hdnid" ng-model="hdn" value="{{product.product_id}}"/>
</li>
add.php
<?php
include 'connect.php';
mysql_select_db($database,$con);
$nm = $_POST['keywords'];
$desc = $_POST['desc'];
$query = "INSERT INTO `product`(`name`,`description`) VALUES ('$nm', '$desc')";
$result = mysql_query($query) OR die(mysql_error());
?>
What should I do to automatically refresh the page
?
When you assign new array or modify existing to $scope.products, it will automatically list each product in the new/modified list in the html. You don't have to reload the page.
In your case the response data for the post should be json array and if it is not, it wont work.
Something like mysql_query($query).toJSON should work.
If you want refresh the page ( for some non -angular reasons), you should explicitly do it in the success of the http call. Remember the GET/POST calls made using the $http wrapper are ajax calls.
example: http://jsfiddle.net/Y3b3H/12/