Summary:
I have a list of posts, each post also containing a list of comments within it. I have the option to add a comment directly on the post (much like twitter). I submit those posts via ajax.
Problem:
When submitting a new comment, is updates all the "comments lists" of each and all posts, and not only the one I have submitted from.
Any ideas? (code below)
JS:
$(document).ready(function () {
var options = {
//clearForm: true,
//resetForm: true,
//beforeSubmit: ShowRequest,
success: function (html) {
$('.post_comment_list').prepend(html);
$('.footer-post').hide();
$('.comments-feed').hide();
$('.small-textarea-main-feed').removeClass('set-large');
resetForm($('.footer-comment'));
},
error: function () {
alert('ERROR: unable to upload files');
},
complete: function () {
},
};
$(".footer-comment").ajaxForm(options);
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
});
PHP
<?php
if (empty($_POST) === false && empty($errors) === true) {
//register user
$post_comment = array(
'comment' => $_POST['comment'],
'id' => $_POST['id'],
);
$user_id = $_SESSION['user_id'];
post_comment_db($user_id, $post_comment);
//print_r($post_question['tags']);
load_comment($user_id,$post_comment);
} else{
echo output_errors($errors);
}
?>
PHP/HTML: Li (the comment to be added)
function load_comment($user_id,$post_comment){
$username = mysql_result(mysql_query("SELECT `username` FROM `users` WHERE `user_id` = $user_id"), 0, 'username');
$timestamp = mysql_result(mysql_query("SELECT `timestamp` FROM `comments` WHERE `user_id` = $user_id"), 0, 'timestamp');
$r = format_time($timestamp);
$question_id = $post_comment['id'];
$q = "SELECT `comment_id` FROM `question_has_comments` WHERE `question_id` = $question_id ORDER BY `timestamp` DESC LIMIT 1" ;
$q = "SELECT `comment_id` FROM `comments` WHERE `question_id` = $question_id ORDER BY `timestamp` DESC LIMIT 1" ;
echo
'
<li id="" class="post_comment">
<!-- wrapper da imagem -->
<div id="" class="give-margin">
<div id="" class="profile-page-avatar-wrapper">
<img id="" class="profile-page-avatar-image" src="./images/test/chemistry.jpg" alt=""><!-- A imagem -->
</div>
<!-- o botao e o texto-->
<div id="" class="profile-page-uploader-tools">
<!-- o botao -->
<div id="" class="profile-image-btn">
<div id="" class="profile-page-btn-wrapper">
<div id="" class="header-id">
<span id="user-name">' . $username . '</span>
</div>
<div id="" class="question-page-feed-answer-header-timer">
<a id="feed-answer-header-timer" href="#"><span class="timer" data-time="">' . $r . '</span></a>
</div>
</div> <!-- fecha Div wrapper do botao-->
</div>
<!-- fecha botao
http://www.w3.org/TR/html-markup/Overview.html#toc-->
<p>' . $post_comment['comment'] . '</p>
</div>
</div>
</li>';
}
Your last comment response identified the problem:
the class "post_coment_list" is an "ol" present in all posts, where the comments to a post reside
From the api:
.prepend(): Description: Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
In your code, the ajax success function prepends the returned HTML as follows:
$('.post_comment_list').prepend(html);
Since $('.post_comment_list') is a set of all elements with class .post_comment_list, and since every post has that class, your HTML will be prepended to each and every post.
To solve this, assign each post a unique ID and, in the success function, prepend the HTML only to that one ID.
To get that ID, you can grab it at the time the ajax call is made and either:
assign the ID to a global var and grab it again in the success fn, or
send the ID along with the other ajax data, and then send it back to the success fn along with the HTML. For example:
PHP side:
$post_id = $_POST['postid'];
$send_back = $post_id . '|' . '<li id="" class="post_comment">
<!-- wrapper da imagem -->
<div id="" class="give-margin">
etc
';
echo $send_back
jQuery/javascript: (inside success: function)
var arrHTML = html.split('|');
var postId = arrHTML[0];
var html_code = arrHTML[1];
$('#'+postId).prepend(html_code);
Note that, above, I did not demonstrate sending the post ID over to the PHP side. I'm sure you are alright with that. Just showed enough to explain what I was suggesting.
Related
Sorry for disturbing again with my very basic question. First of all, sorry if my English is a little bit hard to understand. My current situation is I want to do a popup modal in my drag and drop boxes. In my popup modal, I can view and edit the details of the user based on what we click in the button in the box. The problem is, I cannot SELECT the data by id. But, when I SELECT all the data, the data appear in the modal boxes. But, it appears all the data. I just want the selected id. Back to my question for past few days, I've redo again to get more understanding on this popup modal part. I've done ajax and a little bit JavaScript, also, I tried to debug my code just what I've been told but I got an error saying "Parameter is missing" . What is causing by that ? I've done some reading about parameter but I still don't get the actual understanding about it. Can someone give an idea what is actually parameter is missing . And what I suppose to do by it?
Here what I've tried so far.
This is the button
<button data-id="<?php echo $row['userid'];?>" data-target="doubleClick-1" class='jobinfo' type='button' id='btnInfo' ondblclick="document.getElementById('doubleClick-1').style.display='block'">Info</button>
This is the modal popup
<div id="doubleClick-1" class="modal">
<label class="tabHeading">User Info</label>
<div class="contentTechJobInfo">
<div class="tech-details">
<div class="techClose" onclick="document.getElementById('doubleClick-1').style.display='none'" >×</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.jobinfo').click(function() {
var userid = $(this).data('userid');
// AJAX request
$.ajax({
url: 'ajaxhome.php',
type: 'post',
data: {userid: userid},
success: function(response) {
// Add response in Modal body
$('.tech-details').html(response);
// Display Modal
$('#doubleClick-1').modal('show');
}
});
});
});
</script>
This my ajaxhome.php
<?php
$connection = mysqli_connect("", "", "");
$db = mysqli_select_db($connection, '');
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$userid = intval($_GET['userid']);
$query = "SELECT * FROM user WHERE userid ='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
while ($row = mysqli_fetch_array($query_run)) {
?>
<div class="input-box">
<label for="">Name</label>
<input type="text" id="username" name="username" value="<?php echo $row['username']?>">
</div>
<div class="input-box">
<label for="">Number</label>
<input type="text" id="usernumber" name="usernumber" value="<?php echo $row['usernumber']?>">
</div>
<div class="input-box">
<label for="">Class</label>
<input type="text" id="userclass" name="userclass" value="<?php echo $row['userclass']?>">
</div>
<button type="submit" id="submit" name="update" class="btn btn-primary"> Update Data </button>
<?php
if (isset($_POST['update'])) {
$username = $_POST['username'];
$usernumber = $_POST['usernumber'];
$userclass = $_POST['userclass'];
$query = "UPDATE user SET username='$username', usernumber='$usernumber', userclass='$userclass' WHERE userid='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
echo '<script> alert("Data Updated"); </script>';
header("location:homepage.php");
} else {
echo '<script> alert("Data Not Updated"); </script>';
}
}
} ?>
<?php
}
?>
In short, I think the problem comes from these lines of code in your modal:
var userid = $(this).data('userid');
you should replace it with
var userid = $(this).data('id'); // you should pass 'id' to .data() function instead of 'userid'
With your current code userid variable in your modal will always be undefined. It means it wont exist in $_GET when you send ajax request to PHP. And it causes your ajaxhome.php moves to die("Parameter is missing!");.
To get data-xxx attribute with jQuery, you should use pass 'xxx' to .data() function.
var xxx = $(this).data('xxx');
In your button, you are storing userid in data-id attribute
<button data-id="<?php echo $row['userid'];?>"
so if you need to get that userid you should pass 'id' into .data() function
Update:
In your ajax, you are using type: 'post', so in your php code you should check $_POST instead of $_GET
I don't think the value of user has been obtained
var userid = $(this).data('userid');
you can try
var userid = $(this).data('id');
I want to send an Ajax request when clicking a button but it seems my request is never executed.
Here is my HTML code :
<!DOCTYPE html>
<html lang="en">
<head>
<title>User Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src = "./actions.js"></script>
</head>
<body>
<div id="badFrm" class="container">
<h2><br>User Registration</h2>
<form id="Form" method="post">
<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" placeholder="Enter Name" name="name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email" name="email">
</div>
<button id="submitBtn" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
i feel there is something wrong with my javascript code but i cant figure whats wrong ! i changed a lot of it based on the comments i got earlier . what i want is when i click on the update button it changes to " submit again " and i want to replace "list items" ( name and email ) with input fields and put whatever written in them to be saved in the database instead . and eventually return to the first page which is the register form. i need help in this part !! i know this part is buggy . i need to know how to reach each list item individually ( what attribute should i add/use )
and here is my javascript code :
$(document).ready(function() {
var i ;
$("#submitBtn").click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("http://localhost/MiniProject/connect.php",
{
name: name,
email: email
}, function () {
var element = document.getElementById("badFrm");
element.remove();
showTbl();
});
function showTbl() {
$.post("http://localhost/MiniProject/Select.php",
{
name: name,
email: email
}, function (res) {
// console.log(res);
res = JSON.parse(res);
var html = '<ul id="List">';
for (i = 0; i < res.length; i++) {
var j = i +1 ;
html += '<li class = "name" >' + res[i].name + '</li><li class = "email">' + res[i].email + '</li>'+ '<div>' + '<button onclick="removeUser(this)" class="btn btn-primary">Remove</button>' + '<button onclick="updateUser(this)" class="btn btn-primary">Update</button>' + '</div>';
}
html += '</ul>';
document.body.innerHTML = html;
});
}
});
});
function removeUser(element){
var ID = element.id;
var element2 = document.getElementById("List");
element2.remove();
$.post("http://localhost/MiniProject/Remove.php",{
id : ID
}, function (res) {
console.log(res);
document.write(res);
});
//alert(element.id);
}
function updateUser(element){
// code ...
$.post("http://localhost/MiniProject/Update.php",{
id : ID2,
}, function (res) {
console.log(res);
// document.write(res);
});
}
here is connect.php :
<?php
require 'Users.php';
$name = $_POST['name'];
$email = $_POST['email'];
$conn = new mysqli('localhost','root','','mydatabasename');
if($conn->connect_error){
die('Connection Failed : '.$conn->connect_error);
}else {
$user = new Users();
$user->Insert(['name' => $name, 'email' => $email]);
echo "name is : ".$name." and email is : ".$email;
}
this is Users.php :
<?php
require 'newDB.php';
class Users extends DatabaseClass{
public $table = 'Users';
}
and this is where i handle the database commands :
<?php
class DatabaseClass{
public $connection = null;
public $table = null;
// this function is called everytime this class is instantiated
public function __construct( $dbhost = "localhost", $dbname = "myDatabaseName", $username = "root", $password = ""){
try{
// $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->connection = new PDO("mysql:host=$dbhost;dbname=$dbname", $username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Insert a row/s in a Database Table
public function Insert($parameters = [] ){
try{
$fields = array_keys($parameters);
$fields_string = '`' . implode('`,`', $fields) . '`';
$values_string = ':' . implode(',:', $fields);
$sql = "INSERT INTO `{$this->table}`({$fields_string}) VALUES ( {$values_string} )";
$this->executeStatement( $sql , $parameters );
return $this->connection->lastInsertId();
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Select a row/s in a Database Table
public function Select( $parameters = [] ){
try{
$fields = array_values($parameters);
$fields_string=implode(' , ',$fields);
$sql = "SELECT {$fields_string} FROM {$this->table}";
$stmt = $this->executeStatement( $sql , $parameters );
return $stmt->fetchAll();
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Update a row/s in a Database Table
public function Update( $parameters = [] ){
try{
$fields = array_keys($parameters);
$fields_string = 'id = '.implode($fields);
$sql = "UPDATE {$this->table} SET {$fields_string} WHERE {$fields_string} ";
echo $sql; exit ;
$this->executeStatement( $sql , $parameters );
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// Remove a row/s in a Database Table
public function Remove( $parameters ){
try{
$fields_string = 'id = '.implode($parameters);
$sql = "DELETE FROM {$this->table} WHERE {$fields_string}";
$this->executeStatement( $sql , $parameters );
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
// execute statement
public function executeStatement( $statement = "" , $parameters = [] ){
try{
$stmt = $this->connection->prepare($statement);
$stmt->execute($parameters);
return $stmt;
}catch(Exception $e){
throw new Exception($e->getMessage());
}
}
}
and this is Update.php :
<?php
require 'Users.php';
$id = $_POST['id'];
$conn = new mysqli('localhost','root','','mydatabasename');
if($conn->connect_error){
die('Connection Failed : '.$conn->connect_error);
}else {
$user = new Users();
$result = $user->Update(['id'=>$id]);
// echo json_encode($result);
}
?>
i dont want the question to have a lot of code so hope this makes it better to understand.
I mentioned posting something without jQuery - here is a demo which does what I understand your requirement to be. There are comments below to explain what is going on.
<?php
error_reporting( E_ALL );
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
/*
This emulates ALL of the PHP endpoints used in the original code
-this is for demo purposes ONLY. The data returned is DEMO data
and should be ignored. All AJAX functions should be pointed at
their original endpoints... unless you adopt a similar approach
in which case include your various PHP classes here.
The ficticious sql in the below is for example only!
Obviously you would use `prepared statements`...
*/
switch( $_POST['action'] ){
case 'insert':
// do stuff...
// send response...
$data=sprintf('name is: %s and email is: %s',$_POST['name'],$_POST['email']);
break;
case 'remove':
header('Content-Type: application/json');
$data=json_encode(array(
'action' => $_POST['action'],
'name' => $_POST['name'],
'email' => $_POST['email'],
'sql' => sprintf('delete from `TABLE` where `email`="%s"', $_POST['email'] )
));
break;
case 'update':
header('Content-Type: application/json');
$data=json_encode(array(
'action' => $_POST['action'],
'name' => $_POST['name'],
'email' => $_POST['email'],
'sql' => sprintf('update `TABLE` set `col`=? where `email`="%s"', $_POST['email'] )
));
break;
}
exit( $data );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
.hidden{display:none}
</style>
<script>
document.addEventListener('DOMContentLoaded',()=>{
/*
I can see no benefit to having multiple endpoints to process
the different AJAX requests. You can structure a single script
to process each request rather like the above PHP code but
that is just an opinion. The following points ALL requests to
the same page for this demo.
The user's `email` address should be unique(?) so could be used
as the key in whatever sql query???
*/
const endpoints={
'insert':location.href, // 'MiniProject/connect.php'
'select':location.href, // 'MiniProject/Select.php'
'remove':location.href, // 'MiniProject/Remove.php'
'update':location.href // 'MiniProject/Update.php'
};
// Elements in the initial page/form
let cont=document.querySelector('div.container');
let form=document.forms.register;
let bttn=form.querySelector('button');
// the main callback - for the `Submit` button
const bttnclickhandler=function(e){
e.preventDefault();
let valid=true;
// check the form fields are not empty before continuing
let col=form.elements;
Array.from( col ).some( n => {
if( n.tagName=='INPUT' && n.value=='' ){
alert( '"' + n.name + '" cannot be empty' );
valid=false;
return true;
}
})
if( !valid )return false;
// Prepare the Payload to be sent, via AJAX POST, to the backend script/endpoint.
let fd=new FormData( form );
fd.append('action',this.dataset.action);
// Send the AJAX request
fetch( endpoints.insert, { method:'post', body:fd } )
.then( r=>r.text() )
.then( text=>{
// Hide the original form - do not remove it though... you want to reinstate this later
form.classList.add('hidden');
/*
create a clone of the template and then find the elements within
assign new values and bind event listeners.
*/
let oTmpl=document.querySelector('template#list-item').content.firstElementChild.cloneNode( true );
oTmpl.querySelector('[data-id="name"]').textContent=fd.get('name');
oTmpl.querySelector('[data-id="email"]').textContent=fd.get('email');
oTmpl.querySelectorAll('button[data-action]').forEach( n=>{
n.addEventListener('click',function(e){
let action=this.dataset.action;
let url=endpoints[ action ];
let fd=new FormData();
fd.append('action',action);
fd.append('name',e.target.parentNode.parentNode.querySelector('span[data-id="name"]').textContent);
fd.append('email',e.target.parentNode.parentNode.querySelector('span[data-id="email"]').textContent);
// send a new AJAX request
fetch( url, { method:'post', body:fd })
.then( r=>r.json() )
.then( json=>{
// the response...
console.log( json );
// show the original form and remove the clone
form.classList.remove('hidden');
cont.querySelector('ul#list').removeChild( oTmpl );
})
});
});
// Add the cloned template to the container
cont.querySelector('ul#list').appendChild( oTmpl )
})
};
// bind the event handler to the button.
bttn.addEventListener( 'click', bttnclickhandler );
});
</script>
</head>
<body>
<!--
All buttons below have dataset attributes
data-action='value' - this is used to decide
which piece of PHP code to process.
-->
<div class='container'>
<h2>User Registration</h2>
<form name='register' method='post'>
<div class='form-group'>
<label>
Name:
<input type='text' name='name' class='form-control' placeholder='Enter Name' />
</label>
</div>
<div class='form-group'>
<label>
Email:
<input type='email' name='email' class='form-control' placeholder='Enter Email' />
</label>
</div>
<button data-action='insert' class='btn btn-primary'>Submit</button>
</form>
<ul id='list'></ul>
</div>
<!--
The template will be called and populated
by ajax callback when the above `Submit`
button is clicked.
This will NOT appear in the DOM until
requested with Javascript.
The inner contents of this template
are cloned and inserted into the DOM.
-->
<template id='list-item'>
<li>
<span data-id='name'></span>
<span data-id='email'></span>
<div>
<button data-action='remove' class="btn btn-primary">Remove</button>
<button data-action='update' class="btn btn-primary">Update</button>
</div>
</li>
</template>
</body>
</html>
You say that you want to make an AJAX request (submit), but I don't see where are you doing it.
Also, it seems that you're submitting twice your form.
You should have something like this:
$.ajax({
data: $(this).serialize(),
type: "POST",
url: "http://localhost/MiniProject/connect.php",
success: function(data) {
//if it's successful, put all your code here to change names etc.
}
$(this).serialize() will work only if you change your button to a submit input:
<input type="submit" id="submitBtn" class="btn btn-primary">Submit</input>
you can also use a "button" but then you'll have to specify what data you're submitting, it's easier to use a submit input, if you ask me.
Also, if you already have an ID for name and email, it's a lot easier to change them using it's respective ID's, instead of trying to re-write the whole div element.
Anyway, I hope it helps
My HTML as follows, located in index.php
<div id="showDetails">
</div>
<div id="showList">
</div>
And my Ajax as follows, still in index.php
function funcReadRecord() {
var readrecord1 = "readrecord1";
var sometext = $('#SNOW_INC').val();
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { readrecord1 : readrecord1,
sometext : sometext } ,
success : function(data, status){
$('#showList').html(data);
}
});
}
Now, I can return my list and view the required list (shown as a list group) in index.php.
I have a button in index.php that when clicked, runs the function.
<div>
<button type="button" onclick="funcReadRecord()" class="btn btn-primary">Search SQL (LIKE)</button>
</div>
The code in findsql.php as follows
if(isset($_POST['readrecord1']) && isset($_POST['sometext'])){
$displaysql = "SELECT * from datadump where short_description LIKE '%".$_POST['sometext']."%'";
$result = mysqli_query($conn, $displaysql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$items[] = array(
"number" => $row['number'],
"priority" => $row['priority'],
"description" => $row['short_description']);
}
}
echo '<p class="lead">SEARCH SQL (LIKE)<p>';
echo '<div class="list-group">';
foreach($items as $result) {
?>
<a href="#" class="list-group-item list-group-item-action">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1"><?php echo $result['number']; ?></h5>
<small></small>
</div>
<p class="mb-1"><?php echo $result['description']; ?></p>
<small><?php echo $result['priority']; ?></small>
</a>
<?php
}
echo '</div>';
}
All I'm doing is getting the data from MySQL and assigning them to array and listing them. I know I could do it directly but I need the array in some other function.
The question is how do I make details from the array to show in showDetails div tag when I click the list? Right now, the HREF is #. I could assign a function, but not sure where to write them.
If I should write a function to return them, should I write in index.php or findsql.php?
Thanks in advance.
I understand that you need individual record information in #showDetails div right ! then
step1: assign new function while clicking the particular item as onclick="funcReadRecord(number)", this should at findsql.php file.
step2: write an ajax function in index.php which will send that particular unique id or in your case number
function funcReadRecord(number) {
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { id: number } ,
success : function(data, status){
$('#showDetails').html(data);
}
});
Step3: Write another function in findsql.php with else if block as checking id isset or not, change the query that takes the number or any key that gets only that particular record.
else if(isset($_POST['id'])){
$displaysql = "SELECT * from datadump where number = ".$_POST['id'].";
// remaining design code below
}
We can use the if-else statement to write multiple ajax calls as above.
Edited, Note: kindly ignore the syntax issue in the above code, concentrate on the process used to a single PHP file for multiple ajax calls using branching statements.
I have an html form with checkbox, textbox and radio buttons. When the save button is clicked the form data is to be inserted into to database. I am using an angularjs controller to get the form data and PHP to insert into mysql.
Question: How do I insert selected checkbox value in controller and PHP? Explain to me with code examples.
Below is my code:
html code :
<form class=rform align="center">
<b>Product Name:<input type="text" name="name" ng-model="newProduct.name" required=""/><br>
Product Category: <select name="catg" ng-model="newProduct.catg" ng-options="x for x in catg" ></select><br>
TAGS : <br>
<ul>
<li ng-repeat="tag in tags">
<input type="checkbox" name="tags" ng-model="newProduct.tags" value="tag" ng-true-value="tag"> {{tag}}
</li>
</ul>
<Status :<br><br>
<input type="radio" ng-model="newProduct.stat" value="Active">Active
<input type="radio" ng-model="newProduct.stat" value="Deactive">Deactive<br><br>
<input type="hidden" ng-model="newProduct.id" /></b>
<div class="btn"> <button type="submit" ng-disabled="rform.$invalid" ng-click="saveRecord(newProduct)">Save</button></div>
</form>
app.js
app.controller('ProductCtrl',function($scope,$http){
$scope.tags = ["Appliances","Electronics","Men&Women","Others"] ;
$scope.catg = ["mobile","Air Conditioner","Kitchen appliances","Footwear","SportsWear","clothes",
"watches","Lptops","Televisions","Camera","Furniture","Kitchen Dining","Music","Stationery"];
$scope.saveRecord = function (newProduct) {
$http.post("php/pinsert.php",{
'name' : $scope.newProduct.name,
'catg' : $scope.newProduct.catg,
'tags' : $scope.newProduct.tags,
'stat' : $scope.newProduct.stat
})
// data:$scope.products,
.success(function(data){
alert(data);
})
angular.forEach($scope.tags, function(tag){
if (tag.selected) $scope.albumNameArray.push(tag.name);
tag.selected= false ;
});
tag.selected= false ;
}
$http.get("php/pselect.php").then(function (response) {
$scope.myproducts = response.data.records;
});
});
PHP :
<?php
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
$p_name = mysqli_real_escape_string($connect, $data->name);
$p_catg = mysqli_real_escape_string($connect, $data->catg);
$tags = mysqli_real_escape_string($connect, $data->tags);
$status = mysqli_real_escape_string($connect, $data->stat);
$query = "INSERT INTO products(pname,pcatg,tag,status) VALUES ('$p_name','$p_catg','$tags','$status')";
$result = mysqli_query($connect, $query) ;
if($result == TRUE)
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
?>
I would restructure your tags array likewise. The selected property will be set to true if the checkbox is selected. The name is simply for display.
$scope.tags = [
{"selected":false, "name":"Appliances"},
{"selected": false, "name":"Electronics"},
{"selected":false, "name":"Men&Women"},
{"selected":false, "name":"Others"}
];
The markup for the checkboxes should also be restructured. Notice the ng-model is using the .selected property of $scope.newProduct.tags. This will set allow you to see which tags properties are selected when saving to the DB.
<li ng-repeat="tag.name for tag in tags">
<input type="checkbox" name="tags" ng-model="tag.selected" value="tag" ng-true-value="tag"> {{tag.name}}
</li>
When assigning newProduct to scope it is not necessary to pass it as a parameter in $scope.saveRecord(). You can also pass the entire object in the post body. The ajax call is written without the shorthand $http.post either way is fine but I find this easier to read.
$scope.saveRecord = function(){
$http({
url: "php/pinsert.php",
method: "POST",
data: $scope.newProduct
}).success(function(data){
// process returned data
});
}
On the backend the data will be structured the same your the $scope.newProduct object was structured. You will need to:
Loop through this data
Find the selected tags
Save the checked (selected.true) tag values into the table
I don't know the exact structure of your products table but the 3 steps above are a guide for saving complex data into the DB.
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
foreach($data['tags'] as $tag){
// Save only selected tags to products table
if($tag->selected){
$query = "
INSERT INTO products(tag)
VALUES('$p_name','$p_catg','$tags','$status')
";
$result = mysqli_query($connect, $query);
}
}
Hopefully this gets your started, cheers!
I've followed along with a tutorial video (112 videos in length) and so I'm quite ignorant in many aspects still when it comes to coding; although I've learned a tonne.
What I am having difficulty doing is just what the title says. In the admin panel, which I am currently working on, I have (for instance) assigned to a paragraph tag the jquery bootstrap helper class of "alert alert-success" as you can see here: http://i1379.photobucket.com/albums/...ps44962161.png.
The reason why it is working in the above example is because the SQL which runs upon hitting save (inserting and updating) do not require ajax.
The code being executed when INSERTING and UPDATING is in a file named "queries.php" in the config folder. It is as follows (the error handling portion of course):
case 'pages':
if (isset($_POST['submitted']) && $_POST['submitted'] == 1) {
// POST vars
$title = mysqli_real_escape_string($dbc, $_POST['title']);
$label = mysqli_real_escape_string($dbc, $_POST['label']);
$header = mysqli_real_escape_string($dbc, $_POST['header']);
$body = mysqli_real_escape_string($dbc, $_POST['body']);
if (isset($_POST['id']) AND $_POST['id'] != ''){
$action = "updated";
// UPDATE
$query = "UPDATE posts SET user = $_POST[user], slug = '$_POST[slug]', title = '$title', label = '$_POST[label]', header = '$header', body = '$body' WHERE id = $_GET[id]";
}else{
$action = "added";
// INSERT
$query = "INSERT INTO posts (type, user, slug, title, label, header, body) VALUES (1, $_POST[user], '$_POST[slug]', '$title','$label','$header','$body')";
}
$result = mysqli_query($dbc, $query);
//Error Handling
if ($result) {
$message = '<p class = "alert alert-success">Page was '.$action.'!</p>';
}else{
$message = '<p class = "alert alert-danger">Page could not be '.$action.' because: '.mysqli_error($dbc).'</p>';
$message .= '<p class = "alert alert-warning">Query: '.$query.'</p>';
}
}
if (isset($_GET['id'])) {$opened = data_post($dbc, $_GET['id']);}
break;
HOWEVER, I do not know how to get the $message variable to be echoed when DELETING a post. I'm using ajax so that the post immediately disappears from the list to the left.
Here's the Javascript:
$(".page-delete").on("click", function(){
var selected = $(this).attr("id");
var page_id = selected.split("del_").join("");
var confirmed = confirm("Are you sure you wanted to DELETE this page?");
if (confirmed == true) {
$.get("ajax/pages.php?id="+page_id);
$("#page_"+page_id).remove();
};
...and here's the ajax:
include '../../config/connection.php';
$id = $_GET['id'];
$query = "DELETE FROM posts WHERE id = $id";
$result = mysqli_query($dbc, $query);
if ($result) {
echo "Page Deleted.";
} else {
"There was an error...<br>";
echo $query.'<br>';
echo mysqli_error($dbc);
}
Here's where I'm trying to spit out the message:
</div> <!-- END col-md-3 -->
<div class="col-md-9">
<!--FORM-->
<form role="form" action="index.php?page=pages&id=<?php echo $opened['id']; ?>" method="post">
<?php if(isset($message)) { echo $message; } ?>
<!-- INPUT FIELD for title -->
<div class="form-group">
<label for="title">Page Title</label>
<input type="text" class="form-control" value="<?php echo $opened['title'];?>" name="title" id="title" placeholder="Page's Title" />
</div>
Thanks to anyone who can help, and I apologize for not knowing something so likely basic.
Again, thanks for reading. Peace!
You will need to have a callback on you ajax get.
$.get("ajax/pages.php?id="+page_id, function( data ) {
$( "#result" ).html( data ); // replaces the html in div#result
$("#page_"+page_id).remove();
})
And put your message in a html tag such as div so we can replace it with jquery
<div id="result"><?php if(isset($message)) { echo $message; } ?></div>
Your question is a bit all over the place and you may want to read some books on best practice.