I am creating a commenting system. As of now, I am trying to return a comment posted, but only the new posted comment, using AJAX, with setInterval and parsing JSON data. I am not sure what I am doing wrong, but I am getting a synatax error: unexpected end of JSON input.
Does anyone see what I am doing wrong or if there is a better way of doing this?
HTML
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
AJAX
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
var array = JSON.parse(data);
$(array).each(function($value) {
if($('#comment-container').find('#comment-' + $value.id).length == 0) {
$('#comment-container').prepend($value.html);
}
});
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 3000);
PHP
$user = new User();
//Get the last insert id
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
$html = "";
$html .= '<div class="comment-post-box">';
$html .= $commenter_img;
$html .= '<div class="comment-post-username">'.$comment_username. '</div>';
$html .= '<div>'.$comment_date. '</div>';
$html .= '<div class="comment-post-text">'.$home_comments. '</div>';
$html .= '</div>';
array('id' => $comment_id, 'html' => $html);
}
}
}
Edit: image
Related
I am using php and javascript in order to display data from mysql in a table where each row must have an update button.
It seems to be working fine but i'm getting a weird behavior: it works when i click the buttons in consecutive order (#1 then #2 then #3..) but when i click them randomly (starting with #2 or #3...) it does nothing, just reloads the page.
Can you help me find what am i doing wrong, here's my code so far...
Thanks!
list.php:
<?php
$q= "SELECT * FROM list WHERE id = $f ORDER BY id";
if ($query = mysqli_query($db_con, $q)) {
$y=1;
echo '<table>'.
'<tr>'.
'<th>#</th>'.
'<th>Name</th>'.
'<th>Edit</th>'.
'</tr>';
while ($reg= mysqli_fetch_row($query)){
echo '<tr>';
echo '<td>'.$y.'</td>';
echo '<td>'.$reg[0].'</td>';
echo '<td>
<form id="frm_data'.$y.'" method="post">
<input type="hidden" id="name" name="name" value="'.$reg[0].'" />
<input type="hidden" id="f" name="f" value="'.$f.'" />
<input type="hidden" id="a" name="a" value="'.$a.'" />
<input id="FormSubmit" type="submit" value="EDIT">
</form>
</td></tr>';
$y = $y +1;
}
echo '</table>';
}
?>
validate.js
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
$("#FormSubmit").hide();
var myData = {
name: $("#name").val(),
a: $("#a").val(),
f: $("#f").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "update.php", //Where to make Ajax calls
dataType:"json", // Data type, HTML, json etc.
data:myData, //Form variables
success : function(data) {
if(data.status == 'success'){
alert("OK!");
} else if(data.status == 'error') {
alert("ERROR!");
}
},
error : function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
update.php
<?php
$f = $_POST["f"];
$name = $_POST["name"];
$q = "UPDATE list SET edited = '1' WHERE id = '$f' AND name = '$name' ";
$update_row = mysqli_query($db_con, $q);
if (!$update_row) {
$response_array['status'] = 'error';
} else {
$response_array['status'] = 'success';
}
?>
I am an angular newbie using the multiselect directive from isteven.
I wrote a test case, which works fine from the HTML in the root folder, but when I incorporated it into my app, none of the drop-downs are visible.
There are no console.log error messages.
I bundled the HTML and controller into the same file.
The "myApp.controller('MainCtrl', function ($scope, $http)" does not get executed although the "var myApp = angular.module( "myApp", [ "isteven-multi-select" ]);" does.
<html data-ng-app="myApp" id="myApp" lang="en">
<head>
<title>Writer's Tryst - Enablers Form</title>
<link type="text/css" href="css/enablers.css" rel="stylesheet" />
<link rel="stylesheet" href="css/isteven-multi-select.css">
</head>
<body data-ng-controller="MainCtrl">
<div class="container center_div">
<!--<form id="form-writers" class="form-horizontal well">-->
<img id="img-enablers" src="#" alt="images" />
<form id = "form-enablers" class="form-horizontal well">
<h1>Enablers</h1>
<label for="work-type" class="fixed50">Type:</label>
<p id="work-type"
data-isteven-multi-select
data-input-model="worktype"
data-output-model="outputWorktype"
data-button-label="icon name"
data-item-label="icon name"
data-tick-property="ticked"
></p>
<label for="form-type" class="fixed50">Form:</label>
<p id="form-type"
data-isteven-multi-select
data-input-model="formtype"
data-output-model="outputFormtype"
data-button-label="name"
data-item-label="name"
data-tick-property="ticked"
></p>
<p>For an explanation of the genres s hown here, see <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_genres">List of genres</a><br/></p>
<label for="genres" class="fixed50">Genres:</label>
<p id="genres"
data-isteven-multi-select
data-input-model="genres"
data-output-model="outputGenres"
data-button-label="name"
data-item-label="name"
data-tick-property="ticked"
></p>
<label for="accepted-media" class="fixed50">Accepted Media:</label>
<p id="accepted-media"
data-isteven-multi-select
data-input-model="acceptedMedia"
data-output-model="outputMedia"
data-button-label="icon name"
data-item-label="icon name"
data-tick-property="ticked"
></p>
<p> <label for="special-instructions" class="fixed50">Special Instructions</label>
<textarea id ="special-instructions" name="special-instructions">
</textarea>
</p>
<p>For a limited time, enablers can use this site for <span style="color: #f00; font-weight:bold">FREE</span>. We reserve the right to change this policy without notice.</p>
<div id="recaptcha-elements"></div>
<div class="form-group">
<button type="submit" id="enablers-search" class="btn btn-default glyphicon glyphicon-search"> Search</button>
</div>
<input id="userid" name="userid" type="hidden" />
</form>
</div>
<form id="writers-list">
<p>To request a manuscript, click the checkbox beneath the thumbs-up icon.</p>
<div id="table-list"></div>
</form>
<script src="js/isteven-multi-select.js"></script>
<script src="js/enablers.js"></script>
<script src="js/recaptcha.js"></script>
<script>
var myApp = angular.module( "myApp", [ "isteven-multi-select" ]);
myApp.controller('MainCtrl', function ($scope, $http) {
alert("got here");
$scope.worktype = [
{ icon: "<img src=img/icons/smile-mask.png />", name: "Fiction", ticked: false },
{ icon: "<img src=img/icons/frown-mask.png />", name: "Non-Fiction", ticked: false }
];
$scope.formtype = [];
var data = {};
data.action = 'multiselect-forms';
ajax('post', 'php/enablers.php', data, formsSuccess, 'Error retrieving multiselect forms data: ');
function formsSuccess(data) {
console.log(data);
$scope.formtype = eval(data);
}
$scope.genres = [];
data.action = 'multiselect-genres';
ajax('post', 'php/enablers.php', data, genresSuccess, 'Error retrieving multiselect forms data: ');
function genresSuccess(data) {
console.log(data);
$scope.genres = eval(data);
}
$scope.acceptedMedia = [
{ icon: "<img src=img/icons/email.png />", name: "Mail", ticked: false },
{ icon: "<img src=img/icons/pdf.png />", name: "PDF File", ticked: false }
];
/*
$http({
method: "POST",
url: "php/enablers.php",
params: data,
contentType: 'text'
}).then(function mySucces(response) {
console.log(response.data);
// $scope.formtype = response.data;
}, function myError(response) {
$scope.FORMTYPE = response.statusText;
});
*/
})
</script>
</body> s
</html>
Notice, I resorted to using jQuery Ajax because angular kept insiting on JSON, even though the header from the PHP interace specified content-type of text/plain as well as the http call specifiing contentType = 'text'
PHP
<?php
require_once 'dbconnect.php';
function isEmpty($str) {
return strlen(trim($str)) == 0;
}
function buildInStmt($array)
{
if (is_array($array)) {
$in = implode(',', $array);
} else $in = "'" . $array . "'";
return $in;
}
function multiselectGenres()
{
try {
$dbh = connect2DB();
$stmt = $dbh->prepare("SELECT ID, Genre FROM Genres ORDER BY Genre");
if (!$stmt->execute()) {
echo "\nPDOStatement::errorCode(): ";
print $stmt->errorCode();
print_r($dbh->errorInfo());
} else {
$select = "[";
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$genre = $row['Genre'];
$id = $row["ID"];
$select .= "{";
$select .= 'name: ';
$select .= '"' . $genre . '",';
$select .= 'ticked: false},';
}
$select = substr($select, 0, -1) . "]";
}
header("Content-Type: text/plain");
echo $select;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function multiselectForms() {
try {
$dbh = connect2DB();
$stmt = $dbh->prepare("SELECT ID, Form FROM Forms ORDER BY Form");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$select = "[";
foreach ($rows as $row) {
$id = $row['ID'];
$form = $row['Form'];
$select .= "{";
$select .= 'name: ';
$select .= '"' . $form . '",';
$select .= 'ticked: false},';
}
$select = substr($select, 0, -1) . "]";
header("Content-Type: text/plain");
echo $select;
} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General failure: ' . $e->getMessage();
}
}
function search() {
try{
/*
if (!isset($_REQUEST["work-type"]) || isEmpty($_REQUEST["work-type"]))
throw new Exception('You must select a type of work.');
else {
$worktype = filter_var(trim($_REQUEST["work-type"]), FILTER_SANITIZE_STRING);
$worktype = htmlspecialchars_decode($worktype, ENT_QUOTES);
}
*/
manageEnablerData();
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
throw new Exception('A user-id must be supplied.');
}
$userid = $_REQUEST["userid"];
if (!isset($_REQUEST["form-type"]) || empty($_REQUEST["form-type"])) {
throw new Exception('You must select a form type.');
}
$forms = buildInStmt($_REQUEST["form-type"]);
if (!isset($_REQUEST["genre"]) || empty($_REQUEST["genre"])) {
throw new Exception('You must select a genre.');
}
$genres = buildInStmt($_REQUEST["genre"]);
/*
if (!isset($_REQUEST["sub-genre"]) || isEmpty($_REQUEST["sub-genre"]))
throw new Exception('You must select a sub-genre.');
else {
$subgenre = filter_var(trim($_REQUEST["sub-genre"]), FILTER_SANITIZE_STRING);
$subgenre = htmlspecialchars_decode($subgenre, ENT_QUOTES);
}
*/
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT a.ID, a.Email, a.Name, w.Title, w.Filename FROM Writers w JOIN Accounts a ON a.ID = w.fkAccounts WHERE a.ID = :userid AND FormType IN($forms) AND Genre IN($genres)");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
$table = '<table><tr><th>Author</th><th>Title</th><th>Synopsis</th><th><img src="img/Thumb-up-icon.png" width="32" alt="thumbs-up" </th></tr>';
foreach ($rows as $row) {
$table .= "<tr><td>" . $row['Name'] . "</td><td>" . $row['Title'] . "</td><td>" . "<a href='uploads/" . $row['Filename'] . "' target=_blank>synposis file</a>" . "</td><td><input type='checkbox' id='request-manuscript' name='request-manuscript'" . "</td><td class='hidden'>" . $row['ID'] . "</td><td class='hidden'>" . $row['Email'] . "</td></tr>";
}
$table .= "</table>";
echo $table;
} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General error: ' . $e->getMessage();
}
}
function manageEnablerData()
{ $si = ""; //special-instructions
if (isset($_REQUEST["special-instructions"]) && !isEmpty($_REQUEST["special-instructions"])) {
$si = filter_var(trim($_REQUEST["special-instructions"]), FILTER_SANITIZE_STRING);
$si = htmlspecialchars_decode($si, ENT_QUOTES);
}
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
throw new Exception('A user-id must be supplied.');
}
$userid = $_REQUEST["userid"];
/*
if (!isset($_REQUEST["accepted-media"]) || empty($_REQUEST["accepted-media"])) {
throw new Exception('An accepted media must be entered.');
}
$acceptedMedia = buildInStmt($_REQUEST["accepted-media"]);
*/
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT Enablers(fkAccounts, SpecialInstructions) VALUES(:fka, :si) ON DUPLICATE KEY UPDATE fkAccounts=VALUES(fkAccounts), SpecialInstructions=VALUES(SpecialInstructions)");
$stmt->bindParam(':fka', $userid, PDO::PARAM_INT);
$stmt->bindParam(':si', $si, PDO::PARAM_STR);
$stmt->execute();
//need to handle AcceptedMedia
}
//var_dump($_REQUEST);exit();
if (!isset($_REQUEST['action']) || isEmpty($_REQUEST['action']))
throw new Exception('Programmer error: action not posted.');
else {
$action = $_REQUEST['action'];
switch($action) {
case 'search':
search();
break;
case 'select':
select();
break;
case 'multiselect-genres':
multiselectGenres();
break;
case 'multiselect-forms':
multiselectForms();
break;
default:
throw new Exception("Unknown action: " . $action);
break;
}
}
?>
If you decide I deserve a downvote, please help me to understand what I am doing wrong so that I may learn from my mistakes.
1. Why not work:
a). In your test case, you've put <body data-ng-controller="MainCtrl"> in your html, and this will call MainCtrl function.
b). In your app, you also have a MainCtrl, but you neither call in from html nor $routeProvider.when
Solutions:
1). The easiest way: do <body data-ng-controller="MainCtrl"> in your app, the same as your test case.
2). Put codes inside of MainCtrl into enablersController.If just need this select input model in page #/enablers.
Both are guesses, try and if any problems let me know.
I want to insert a "remove" button in each of these divs, so that the database's row and the div can be deleted using the remove button.
Number of divs vary according to the number of rows in the database.
It should appear as follows,
Showing data works just fine. But, delete (remove button) doesn't work.
PHP
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM users_table ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['user_id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
</div>';
if (isset($_GET['removeButton'])) {
deleteUser($connection, $userID);
}
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
As the discussion from the comment, The following codes given.
Updated HTML:
<input type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
$.post("page.php", { userID : userID}, function(result){
if(result == "Success") window.location.href = "main.php";
else alert(result);
});
});
page.php
//need the database connection
$userID = $_POST['userID'];
$sql2 = "DELETE FROM users_table WHERE user_id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
echo 'Success';
} else {
echo "Error! ";
}
If you want to remove the total div as well with the database field then use:
Javascript:
var userID = "<?php echo $userID;?>";
$(".removeBtn").on("click", function(){
var __this = $(this);
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
If you want to pass your $userID in each input then use:
<input data-userid = <?php echo $userID;?> type="button" name="removeButton" value="Remove" class="removeBtn">
Javascript
$(".removeBtn").on("click", function(){
var __this = $(this);
var userID = __this.attr("data-userid");
$.post("page.php", { userID : userID}, function(result){
if(result == "Success"){
__this.closest("div").remove();
window.location.href = "main.php";
}
else alert(result);
});
});
This is just an answer of your question, but you have to use this as you want. This may help you, try and let me know what happens.
The remove button doesnt work because you never get into deleteUser() method.
You cant just write
<input type = "button" name = "removeButton" value = "Remove" method = "GET">
as it was inside a form. For it to trigger, write it like this:
<form method="GET">
<input type = "submit" name = "removeButton" value = "<?php echo $userID;?>">
</form>
Then, when calling
deleteUser($connection, $_GET['removeButton']);
Hope this helps.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function deleteUser($connection, $userID){ // this function calls within the "currentUsers" Function
$sql2 = "DELETE FROM users_table WHERE id = '$userID' ";
if (mysqli_query($connection, $sql2)) {
header("Location: main.php");
} else {
echo "Error! ";
}
}
function currentUsers($connection){
$sql1 = "SELECT * FROM maps ";
$result1 = mysqli_query($connection, $sql1);
if(mysqli_num_rows($result1) > 0){
while($row = mysqli_fetch_assoc($result1)) {
$userID = $row['id'];
$name = $row['name'];
$country = $row['country'];
echo '<div>
<h3>'. $userID. " ". $name. " ". $country. '</h3>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
if (isset($_GET['removeButton']))
{
deleteUser($connection, $_GET['removeButton']);
}
currentUsers($connection);
?>
In this below code i have 2 dropdown in one dropdown i get course code from course subject table and in another drop relevant subject code for selected course code from course subject table should be displayed. But i cant get the dependent dropdown subject code .Pls any one help me.
Controller:student_site
function search_by_course()
{
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
$html_string .= "</select>";
echo json_encode(array('html_string'=>$html_string));
}
model:student_model
function subject_list($id)
{
//echo "exam_name inside get_subject_records".$exam_name;
//$this->db->select('course_code,subject_code');
//$this->db->where('exam_name',$exam_name);
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
view:student_detail_view
<td >
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<div class="subject"></div>
</td>
<script>
$(function(){
$("#course_code_id").live("change keypress",function(){
var id = 0;
id = $(this).val();
if( $(this).val() !==''){
$.post('<?php echo site_url('student_site/search_by_course') ?>',
{
subject_id: id
},function(data){
$(".subject").html( data['html_string']);
},"JSON"
);
}
});
});
</script>
Changes to do:
In view:
<div class="subject">
<select id="subject_code_id"></select>
</div>
<script>
$(function(){
$("#course_code_id").live("change", function(){
var id = $(this).val();
if( id != ''){
$.ajax({
url : '<?=base_url('student_site/search_by_course')?>',
type : 'POST',
data : { 'subject_id' : id },
success : function(resp){
if( resp != "" ){
$("#subject_code_id").html('resp');
}else{
alert("No response!");
}
},
error : function(resp){
alert("Error!");
}
});
}
});
});
</script>
In controller:
function search_by_course(){
$this->load->model('subject_model');
$id = $this->input->post('subject_id');
//get your data from model
$res_subject = $this->subject_model->subject_list($id);
$html_string = "";
//$html_string .= "<select id='subject_code_id'>";
for($x=0;$x<count($res_subject);$x++)
{
$html .= "<option id=".$res_subject[$x]->subject_id.">".$res_subject[$x]->subject_name."</option>";
}
//$html_string .= "</select>";
//echo json_encode(array('html_string'=>$html_string));
echo $html_string;
}
can jQuery or plain JavaScript check how the value of input field was changed? Maybe something similar to that:
$('input').change(function(e){
e.preventDefault();
console.log(e.changedFunction.name);
});
I know given code doesn't work and doesn't do what I want. But is this even possible somehow?
Why do I need that? I have a dialog box where I have multiple forms (each form changes one thing). When I submit form, the value resets back to value which was there previously. e.g. In the form there's a word 'Hello', when I change it to 'Hello, World!', it successfully sends the data to $.post, but then resets the value to 'Hello'. I can't seem to find any function, neither php, nor javascript that changes the input. That's why I need to check what or who changes my input value back.
EDIT:
Including sample code.
editblock.php
} else if ($_POST['what'] == 'email') {
$sql = mysql_query("SELECT id, email, loggedin FROM users WHERE id = " . mres($_POST['id']) . " LIMIT 1");
$edit = mysql_fetch_array($sql);
$output .= '<div id="block-' . $_POST['what'] . '"><form method="post" id="form-' . $_POST['what'] . '">';
$output .= '<input type="hidden" name="id" value="' . mres($_POST['id']) .'" />';
$output .= '<input type="text" name="value" value="' . $edit['email'] .'" /> ';
$output .= '<input type="hidden" name="what" value="' . mres($_POST['what']) .'" />';
$output .= '<input type="submit" name="submit" value="OK" />';
$output .= '</form></div>';
$output .= '<script>
$("#form-' . $_POST['what'] . '").submit(function(event) {
event.preventDefault();
var $form = $( this ),
doval = $form.find( "input[name=\"value\"]" ).val(),
doid = $form.find( "input[name=\"id\"]" ).val(),
dowhat = $form.find( "input[name=\"what\"]" ).val();
$.post("/pages/profilis/doedit.php", { do: doval, id: doid, what: dowhat },
function( data ) {
$("#block-' . $_POST['what'] . '").empty().append( data );
$form.find("input[name=\"value\"]").val(doval);
}
);
});
</script>
';
}
doedit.php
else if ($_POST['what'] == 'email') {
if (empty($_POST['do'])) {
$error[] = 'err';
} else {
if ( ! preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $_POST['do'])) {
$error[] = "err";
}
$sql = mysql_query("SELECT `id` FROM `users` WHERE `email` = '" . mres($_POST['do']) . "' LIMIT 1");
if (mysql_num_rows($sql) == 1) {
$error[] = "err";
}
if ($edit['loggedin'] > 0) {
$error[] = "err";
}
if (sizeof($error) >= 1) {
echo join($error, '<br/>');
} else {
$sql = mysql_query("UPDATE users SET
email = '" . mres($_POST['do']) . "'
WHERE id = " .(int)$edit['id'] . "
LIMIT 1");
if ($sql) {
echo 'OK';
$logmsg = 'Changed email';
} else {
echo 'Error';
}
}
}
}
PHP function mres() escapes all the characters (for database injection protection - not really important here).
According to the situation which you explained. I would prefer you to use jqueryajax
in this Once the Post function is done you can change the value with the changed value
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg ); // portion where you can change the field value to the updated one.
});
Thanks and Regards,
Philemon Philip Kunjumon