I want to store comments from users in my databse. When a user submits I don't want to redirect them to a new page.
I have the following code but it's not working.
My HTML code:
<form id="formA" action="test.php" method="post" enctype="multipart/form-data">
<input id="commentData" name="commentData" type="text" >'
<input type="submit" value="toDb" id="toDB" name="toDB" /></form>
Javascript:
var frm = $('#formA');
$(document).submit(function(e) {
e.preventDefault();
$.ajax({
url: frm.attr('action'),
type: frm.attr('method'),
data: frm.serialize(),
success: function(html) {
alert('ok');
}
});
});
Here is my PHP file:
//Connect to database server
mysql_connect("localhost", "user", "") or die (mysql_error ());
mysql_select_db("test") or die(mysql_error());
$strSQL = "SELECT * FROM comments order by RAND() LIMIT 5";
$rs = mysql_query($strSQL);
if (!$rs) {
echo 'Could not run query ' . mysql_error();
exit;
}
$dt1=date("Y-m-d");
if(isset($_POST['toDB'])){
$dataA = $_POST['commentData'];
$sql = "INSERT INTO comments(id, comment, datum)VALUES(DEFAULT,'$dataA', '$dt1')";
$result=mysql_query($sql);
}
mysql_close();
When I click on the submit button it will stay on the same page and show the alert but the data of the input field is not inserted in my database. When I remove the e.preventDefault() the data goes into the database but the page redirects to test.php
Tried different things but can't figure it out.
Can someone help me out?
Thanks in advance!
The form submits and does not stay on the same page because of the action attribute on the form, and the normal submit button.
Which leads to your .submit() method including .preventDefault() probably not being interpreted after the html is loaded either.
You could do something along the lines of this:
<html>
...
<body>
...
<form id="formA" action="test.php" method="post" enctype="multipart/form-data">
<input id="commentData" name="commentData" type="text" />
<input type="submit" value="toDb" id="toDB" name="toDB" />
</form>
...
</body>
<script>
...script here...
</script>
</html>
And the javascript could be something along the lines of:
( function( $ )
{
var submit = $( 'input[id=toDB]' );
$( submit ).on
(
'click',
function( event )
{
event.preventDefault();
var form = $( this ).parent();
// Get form fields
var data = $( form ).serializeArray(), obj = {}, j = 0;
for( var i = 0; i < data.length; i++ )
{
if( data[i].name in obj )
{
var key = data[i].name + '_' + j;
obj[key] = data[i].value;
j++;
}
else
{
obj[data[i].name] = data[i].value;
}
};
// Make AJAX request
$.ajax
(
{
url: $( form ).attr( 'action' ),
type: 'POST',
data: 'toDB=' + JSON.stringify( obj ),
success: function( data, textStatus, xhr )
{
// Do something with data?
...
alert( 'ok' );
}
}
);
}
);
}( jQuery )
);
See the jsfiddle for yourself.
You can tell it is working because you get a console error that the request destination is not found - 404 - though the page does not refresh, you stay right where you are...with a proper page to submit to it works fully.
EDIT
I modified the setting of 'data' in the ajax() call so that the form fields are set as a json string to a POST variable [toDB].
So in your PHP you would do:
$datas = json_decode( $_POST['toDB'], true );
And now your $datas variable is an associative array containing all your form fields names and values. I'm not 100% on this next statement, but you may need to use PHP's stripslashes() method on the POSTED data prior to using json_decode()
i.e.:
//Connect to database server
mysql_connect( "localhost", "user", "" ) or die ( mysql_error() );
mysql_select_db( "test" ) or die( mysql_error() );
$strSQL = "SELECT * FROM comments order by RAND() LIMIT 5";
$rs = mysql_query( $strSQL );
if( !$rs )
{
echo 'Could not run query ' . mysql_error();
exit;
}
$dt1=date("Y-m-d");
if( isset( $_POST['toDB'] ) )
{
$datas = json_decode( stripslashes( $_POST['toDB'] ), true );
$dataA = $datas['commentData'];
$sql = "INSERT INTO comments( id, comment, datum )VALUES( DEFAULT, '" . $dataA . "', '" . $dt1 . "' );";
$result=mysql_query( $sql );
}
mysql_close();
Hope that helps
Do it via form submit event
var frm = $('#formA');
frm.submit(function(e) {
//....
//....
e.preventDefault();
});
And yes, sanitize DB inserts with mysql_real_escape_string($dataA) to prevent SQL injections.
EDIT
sorry, incomplete answer (still you need to use submit on form, not on document)
EDIT2 :) wrong usage of $(this) :)
$('#formA').submit(function(e) {
var formAction = $(this).attr('action');
var formData = $(this).serialize();
$.ajax({
url: formAction,
type: 'POST', // try uppercase, 'post' !== 'POST', dont know if this must be uppercase or can be lowercase
data: formData, // or try $(this).serializeArray()
success: function(html) {
alert('ok');
})
});
e.preventDefault();
});
EDIT2.5: there can be problems with enctype="multipart/form-data"
you need to make some modifications:
var formData = new FormData(this);
and add some options to AJAX call
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false
found this page with example
http://hayageek.com/jquery-ajax-form-submit/
try that UPPERCASE / lowercase POST, and then try to remove multipart/form-data if you dont need it (file upload etc...)
EDIT3
with multipart form, maybe you should use this in PHP in some cases to access your post data $GLOBALS['HTTP_RAW_POST_DATA']
Add return false at the end of the script to prevent redirecting
Related
I am building a basic commenting system for a website: Comments can be made and users can reply on every comment. I am using ajax for submitting and retrieving/displaying the comments and replies. I have successfully coded the comments part, but need assistance on the replies part.
Every comment stored in the database has a unique id (comment_id) associated with it. And I use that id to associate replies to each respective comment.
The form for the comments, which is in index.php:
<div id="showComments"></div> <!--div where comments are inserted by AJAX-->
<div style="text-align:center;">
<form action="" method="post" id="commentForm">
<textarea name="comment" id="comment" rows="1"></textarea><BR>
<button type="submit" name="new_comment" onClick="submitComment()">Comment</button>
</form>
<div id="message"></div> <!--div where a status (comment submitted successfully or failed) is inserted by AJAX-->
</div>
The JavaScript for submitting the comment and displaying the comments, also in index.php.
<script>
$(document).ready(function() {
showComments();
});
function submitComment(){
var commentText = document.getElementById('comment').value;
var commentString = 'comment=' + commentText;
event.preventDefault();
$.ajax({
url: "insert_com.php",
method: "POST",
data: commentString,
dataType: "JSON",
success: function(response) {
if (!response.error) {
$("#commentForm")[0].reset();
$("#message").html(response.message);
showComments();
} else if (response.error) {
$("#message").html(response.message);
}
}
});
}
function showComments() {
$.ajax({
url: "get_com.php",
method: "POST",
success: function(response) {
$("#showComments").html(response);
}
});
}
</script>
The file insert_com.php, which submits the comment to the database, to where AJAX posts in the submitComment() function:
<?php
if(!empty($_POST["comment"])){
$new_com_date = date('Y-m-d H:i:s');
$insertComment = "INSERT INTO comments (text, date) VALUES ('".$_POST["comment"]."', '".$new_com_date."')";
mysqli_query($connect, $insertComment) or die("database error: ". mysqli_error($connect));
$message = '<label>Comment posted Successfully.</label>';
$status = array(
'error' => 0,
'message' => $message
);
} else {
$message = '<label>Error: Comment not posted.</label>';
$status = array(
'error' => 1,
'message' => $message
);
}
echo json_encode($status);
?>
And the file get_com.php, which retrieves and displays the comments but also retrieves the replies and contains the form for submitting the replies
<?php
require 'php/connect.php';
$comment = mysqli_query($connect, "SELECT * FROM `comments` ORDER BY `date` DESC");
$string ="";
foreach($comment as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$comment = $item['text'];
$comment_id = $item['id'];
$string .= '<div style="text-align:center;">'
.'<div id="'.$comment_id.'" style="text-align:center;">'
.'<span><b>'.$comment.'</b></span> '
.'<span><b>'.$date.'</b></span> '
.'<span><b>'.$comment_id.'</b></span>'
.'</div>';
$reply = mysqli_query($connect, "SELECT * FROM `replies` WHERE `comment_id`='$comment_id' ORDER BY `date` DESC");
foreach($reply as $com) {
$reply_date = new dateTime($com['date']);
$reply_date = date_format($reply_date, 'M j, Y | H:i:s');
$reply_com = $com['text'];
$com_id = $com['comment_id'];
$string.= '<div>'
.'<span>'.$reply_com.'</span> '
.'<span class="time">'.$reply_date.'</span> '
.'<span><b>'.$com_id.'</b></span>'
.'</div>';
}
$string .=
'<div>'
.'<form action="" method="post" id="replyForm">'
.'<textarea name="new-reply" id="new-reply" rows="1"></textarea>'
.'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
.'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
.'<span><b>'.$comment_id.'</b></span>'
.'</form>'
.'<span id="replymessage"></span>'
.'</div>'
.'</div>'
.'<hr style="width:300px;">';
}
echo $string;
?>
Now, here is where the problem comes in. I want to use AJAX to submit a reply to a particular comment with an id $comment_id. I want to get this id from the hidden input contained in the reply form (The form with id replyForm.
I wrote the following JavaScript to retrieve the id belonging to a particular comment:
<script>
function submitReply(){
var replyText = document.getElementById('new-reply').value; console.log(replyText);
var commId = document.getElementById('com_id').value; console.log(commId);
event.preventDefault();
...
</script>
As you can see, I log the form text (the reply) and the comment id to the console to see whether I am capturing the correct data, but it always returns the id of the last comment submitted. (i.e the reply form works for the last comment. The JavaScript logs the correct text and comment id for a reply on the last comment, but for all other replies it returns the text of the reply on the last comment and the id of the last comment.
I know it's quite a lot of code, so if anyone more experience could assist me it would certainly be appreciated.
You have more than one element with id="com_id". id should be unique. What you can do is when you are generating the DOM in get_com.php, instead of
'<input type="hidden" id="com_id" name="com_id" value="'.$comment_id.'"/>'
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply()">Reply</button> '
You can call submitReply() with the right ID, like so:
'<button type="submit" id="form-reply" name="new_reply" onClick="submitReply('.$comment_id.')">Reply</button> '
Then, the comment ID would be the argument of your submitReply method and you wouldn't need to read it from the input field.
<script>
function submitReply(commId){
var replyText = document.getElementById('new-reply').value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
Your <textarea> has the same issue as well.
I suggest to assign a unique ID to your <textarea> as well, something like "reply-'.$comment_id.'". Then, when submitReply(comment_id) gets called, you know which comment ID is the call for, so you can construct the unique ID for the exact same textarea, and get the value of the desired element.
<script>
function submitReply(commId){
var replyText = document.getElementById('reply-' + commId).value;
console.log(replyText);
console.log(commId);
event.preventDefault();
...
</script>
I would like to know how a button submit can interact with AJAX to SELECT FROM data as a MySQL query without refreshing the page . I already have a text box interacting with AJAX so that the page does not refresh when the user inputs the text and presses enter but have no idea how to make the button do it my code below shows how im getting the text box to insert data without refreshing
Here is my script for the textbox
<div id="container">
About me<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
Here is the action
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$name = $_POST['name'];
$name= mysqli_real_escape_string($con, $name);
$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_COOKIE[$cookie_name]."'");
while($row = mysqli_fetch_assoc($q)){
//echo $row['id'];
$id = $row['id'];
}
$result=$con ->query=("REPLACE INTO about_user (about_me,number) VALUES ('".$name."','".$id."')");
$insert = $con->query($result);
echo "About Me Updated";
}
?>
Now all I need to do is have the below example of a button do something similar but instead of INSERTING just SELECT , how can i change the above script to allow a button to handle the action please?
<form
action="action_mail_view.php" method="post">
<input type="submit" class="button" name='msubmit' value="View Mail"/>
</form>
function callServer() {
$('#mail-button').on('click', function() {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {
name: info
},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
});
}
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
$('#mail-button').trigger('click');
};
});
});
<form action="action_mail_view.php" method="post">
<input type="submit" class="button" id="mail-button" name='msubmit' value="View Mail" />
</form>
You haven't showed us how you tried to make your button work so how can we give you feedback? Basically you want a similar ajax call that calls action_mail_view.php using the GET method
Ajax
$.ajax({
method: "GET",
url: "action_mail_view.php",
data: {},
success: function(results) {
var userinfo = JSON.parse(results);
//Todo: do what you want with the user's info
}
});
On the PHP side, you should first authenticate the user (not shown here), then SELECT her info from the DB and return it
action_mail_view.php
//Todo: authenticate
//this works with your setup, but it's a bad idea to trust
//a cookie value or anything else coming from the
//browser without verification
$username= mysqli_real_escape_string($con, $_COOKIE[$cookie_name]);
//get the user's info from your DB. By using a JOIN, we can execute
//just one query instead of two.
$sql = "SELECT t2.* FROM tbl1 as t1 "
."LEFT JOIN about_user as t2 "
."ON t1.id = t2.number"
."WHERE t1.username = $username";
//Todo: execute query. see what results you get and refine
// the SELECT clause to get just what you want
if($q = mysqli_query($con,$sql)):
$userinfo = mysqli_fetch_assoc($q);
//tell the browser to expect JSON, and return result
header('Content-Type: application/json');
echo json_encode($userinfo);
else:
//Todo: error handling
endif;
I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with
I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.
i try to update the status of a messae in my pm's by only clicking the read button on my page. so i found some solution here on this site, but it doesn't really work for me.
i use this ajax before the html button:
<script type="text/javascript">
function setRead(){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { name: $("select[name='gelesen']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
</script>
the button is styled css and uses it's own javascript to toggle the content (open/close)
so i want to update the status by opening the message
<span class="toggleOpen" onclick="setRead()"><input type="hidden" method="post" name="gelesen" value="<?php echo $row['id']; ?>">lesen</span>
the included site is
<?php
ini_set('include_path', 'inc');
require("connect.php");
{
$id = $_POST['id'];
$sql = "UPDATE
PMS
SET
gelesen = 'yes'
WHERE id = '".mysql_real_escape_string($id)."' AND gelesen = 'no'";
mysql_query($sql) OR die("<pre>\n".$sql."</pre>\n".mysql_error());
}
but i get always the notice of the undefined variable 'id'.
how can i give this variable to the included site?
because i have to wait 8 hours before i can reply i edit my post:
thanks for the answer but i still get the message of a undefined index: name
so the variable is not postet to my update_pm_staus.php
ihave updated my script to this:
<script type="text/javascript">
function setRead(){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { id: $(this).children("[name='gelesen']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
and the update_pm_status.php to this:
ini_set('include_path', 'inc');
require("connect.php");
$id = $_POST['name'];
$sql = "UPDATE
PMS
SET
gelesen = 'yes'
WHERE id = '".mysql_real_escape_string($id)."' AND gelesen = 'no'";
mysql_query($sql) OR die("<pre>\n".$sql."</pre>\n".mysql_error());
i also changed my html like this in hope to bring it to work.
<span class="toggleOpen" onclick="setRead()" input type="hidden" method="post" name="gelesen" value="<?php echo $row['id']; ?>">lesen</span>
It looks as though you are sending the id correctly, but you are sending it as name. You'd want to update your JavaScript to pass the key:value pair that you're expecting, with the key name that you expect in your PHP.
<script type="text/javascript">
function setRead(){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { id: $(this).children("[name='gelesen']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
</script>
You'll notice that in the data: {} block of the AJAX request, I've updated your key:value pair to be named id, rather than name. If you do what your key to be named name when POST'ing, then you'd want to update your PHP to look for that:
$id = $_POST['name'];
sorry for the late response. i got the to work. i use
<script type="text/javascript">
function setRead($id){
$.ajax({
type: "POST",
url: "update_pm_status.php",
data: { id: $id}
}); }
and the html like this
onclick="setRead(this.id);
thanks for to all helping me out :)