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 :)
Related
I get category id by js and want to use it to get category description.
when i am passing this id using ajax into php variable its print correct output but when i try to put this id in get_description code ajax give 500 error and not return output why this happen please help me.
Below is my code.
<script type="text/javascript">
$(".-filter").click(function() {
var js_var = this.id;
$.ajax ({
type: "POST",
url: "<?php echo plugin_dir_url( __FILE__ ); ?>category.php",
data: { val : js_var },
success: function( result ) {
$("#update").html(result);
}
});
});
</script>
<div id="update">
<?php
$cat_id = $_POST['val'];
echo $cat_id;
//echo term_description($cat_id,'category');
?>`enter code here
</div>
Thanks,
After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?
Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});
Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.
So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.
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
I am trying to submit a form via ajax but it doesn't let me:
Ajax - samepage
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe'},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
HTML - same page
<form class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail" >
<input type="submit" id="ssub" value="Subscribe">
</form>
PHP - common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ($sname, $email, 0)");
echo "You have been subscribed";
}
?>
EDIT added dbconn
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
In the console I get nothing. After I click submit and check the console. I can see in red how is actioning common-functions.php but doesn't do anything. Please help.
TL;DR You need to do six things to fix the problems in the code you have provided. There are pitfalls with event propagation, scoping, and variable validation.
First, add this to your JavaScript: event.preventDefault(); event.stopPropagation();.
Second, submit your actual data.
Example showing these fixes:
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
Third, actually call subscribe().
Fourth, you have a scoping problem: $db is a global, but you don't refer to it as one. That's why I added global $db; below.
Fifth, check the existence of your POST values.
Sixth, put quotes around your database values and escape them first.
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($sname)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
NOTE: This just shows how to fix the code that you have posted. The code in the question, however, is wide open to SQL injection. You really should use prepared statements instead of relying on escaping of special characters.
You have to include the data youre accessing via Post in PHP in the data object in the $.ajax call:
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#name").val()
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
Also your PHP function subscribe doesnt get called just by setting action:"subscribe"
You have to check wheter $_POST["action"] is "subscribe":
if($_POST["action"]=="subscribe")
{
subscribe();
}