Ajax stopped working after executing a query - php

I am trying to load comments from a php file using ajax.
index.php
<div id="commentsonpost" value="<?php echo $_GET['post'];?>">
</div>
<script type="text/javascript">
$(document).ready(function() {
var postid = $('#commentsonpost').attr("value");
alert(postid);
var dataString = 'getpostcomm=1&postid='+ postid;
$.ajax({
type: "get",
url: "getcomments.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
alert("re");
$("#commentsonpost").append(html);
}
});
return false;
});
</script>
getcomments.php
if(isset($_GET['getpostcomm'])){
$var=$_GET['postid']; // Adding this line causing problems
$querycomm = "select U.fname,U.lname,U.usernick,C.bcommentid,C.comment,C.date,C.visible from blogcomments as C natural join users as U where C.visible=1 and U.visible=1 and C.bpostid='{$var}' ORDER BY C.date ASC";
$resultcomm = mysql_query ( $querycomm, $connection );
echo "<div id='pcomments'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$_POST['post'].'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
}
Whenever i add that $var=$_GET['postid']; line in getcomments.php ajax script stop working. As soon as i remove $var=$_GET['postid']; from getcomments.php, excluding query part(obviously) form is displaying correctly.
Any ideas?

At ajax better set data fields as array values as:
$.ajax({
type: "get",
url: "getcomments.php",
data: {'getpostcomm':1,'postid':postid},
And at your PHP you have to sanitize your Id.. (if its int you may at least cast (int) )...
$var = (int) $_GET['postid'];
Also at your PHP add check if isset($_GET['postid'])...
if(isset($_GET['getpostcomm']) && isset($_GET['postid'])){

var dataString = 'getpostcomm=1&postid='+ toString(postid);

Related

TinyMCE and AJAX is not sending data to php in mysql server

<!-- Page containing form -->
Paragraph
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="//tinymce.cachefly.net/4.2/tinymce.min.js"></script>
<!-- Just be careful that you give correct path to your tinymce.min.js file, above is the default example -->
<script>tinymce.init({selector:'textarea'});</script>
</head>
-->
<div class="container">
<br />
<br />
<h2 align="center">Enter a new paragraph</h2>
<div class="form-group">
<form name="add_paragraph" id="add_paragraph">
<div class="table-responsive">
<table class="table table-bordered
id="dynamic_field">
<tr>
<textarea id = "paragraph" type="text" name="paragraph" placeholder="Enter paragraph text"></textarea>
</tr>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body> </html> <script> $(document).ready(function(){
$('#submit').click(function(){
$.ajax({
url:"form1_support.php",
method:"POST",
data:$('#add_paragraph').serialize(),
success:function(data)
{
alert(data);
$('#add_paragraph')[0].reset();
}
});
}); }); </script>
require 'db/connect.php';
$number = count($_POST["paragraph_name"]); //it said experience
before, maybe experience_list?
if($number > 0) {
for($i=0; $i<$number; $i++)
{
if(trim($_POST["paragraph_name"] != ''))
{
$paragraph_name = mysqli_real_escape_string($db, $_POST['paragraph_name']);
$paragraph_text = mysqli_real_escape_string($db, $_POST['paragraph']);
$sql = "INSERT INTO paragraph (paragraph_name, paragraph_text)
VALUES( '$paragraph_name', '$paragraph_text')";
mysqli_query($db, $sql);
}
}
echo "Data Inserted"; } else {
echo "Please Enter Your Paragraph."; } ?>
If you are replacing a textarea with TinyMCE then the actual textarea does not get updated automatically unless one of the following happens:
You perform a standard HTML form submission - in this scenario TinyMCE will automatically update the textarea at the start of the form submission process.
You use the triggerSave() API to force TinyMCE to update the textarea.
Try adding a triggerSave() call before you send the AJAX request.
https://www.tiny.cloud/docs/api/tinymce/root_tinymce/#triggersave
<textarea id="editor" name="editor" type="text"></textarea>
tinyMCE.triggerSave();
var content = $("textarea[name=editor]").val();
var formData = new FormData();
formData.append("content", content);
$.ajax({
url: '../boot/newBlog.php',
method: 'POST',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
switch (response){
}
}
});

Complete form submit action without reloading the page

I want the form-data to be sent to my php file after submitting it without loading the php file page. Then the data sent must fade in the feeds after processing. Can anyone help me? Here are my codings:
home.php:
<script>
$(document).ready(function(){
$('#content').load('feeds.php');
}, 1000
);
</script>
feeds.php:
<?php
//after connecting to my database and all
$sql = mysql_query("SELECT * FROM `posts` ORDER BY `post_id` DESC");
while($row = mysql_fetch_assoc($sql)) {
echo '<div id="post">' . $row['post'] . '</div><br />';
}
?>
Here's the form for submitting the post
<form id="post" action="post.php" method="POST">
<textarea name="post" width=300 height=150></textarea>
<input type="submit" value="Post" id="submit">
</form>
post.php:
//after connecting to the database
$post = $_POST['post'];
if($post != '') {
mysql_query("INSERT INTO `posts` (`post`) VALUE('$post')");
}
else {
echo 'Form is empty!';
}
#content:
<div id="content"></div>
nothing else.
Please help me by modifying this code! Thanks in return!
change this from
<form id="post" action="post.php" method="POST">
<textarea name="post" width=300 height=150></textarea>
<input type="submit" value="Post" id="submit">
</form>
to
<form id="form1">
<textarea id="post" width=300 height=150></textarea>
<input type="button" value="Post" id="submit">
</form>
And put this script on javascript area :
$('#submit').click(function(event) {
event.preventDefault(); /* Stops default form submit on click */
var post = $('#post').val();
$.ajax({
url: "post.php?",
data: 'post=' + post,
type: "POST",
success: function(data){
$('#content').empty();
$('#content').load('feeds.php');
}
});
});
I did not test it , but it should be something like this.
Hope this help.
The best solution should be JQuery along with AJAX. Send the data to any page using AJAX and based on the response you can fade the data.
Here is sample implementation:
jQuery(function($){
$("#post").submit(function(){
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(){
alert("data sent");
}
});
return false;
});

how to insert value in database using php, jquery and ajax

I am struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...this is a msg.php page when i have submit data sometimes post submit in database`
mostly not so i want to know that why it s happening i am new in this field
<?
php $id=$_GET['id'];
$id1=$_SESSION['id'];
?>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="<?php echo $id1;?>" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" onClick="sendChat()">
</div>
</form>
function sendChat()
{
$.ajax({
type: "POST",
url: "msg_save.php",
data: {
senderid:$('#senderid').val(),
rcvrid:$('#rcvrid').val(),
msg: $('#msg').val(),
},
dataType: "json",
success: function(data){
},
});
}
msg_save.php file
<?php
require_once('include/util.php');
$rcvrid=$_POST['rcvrid'];
$senderid=$_POST['senderid'];
$msg=$_POST['msg'];
$sql="insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysql_query($sql);
?>
$.ajax({
type: "POST",
url: "msg_save.php",
data: " senderid="+$('#senderid').val()+"rcvrid="+$('#rcvrid').val()+"msg="+$('#msg').val(),
dataType: "json",
success: function(data){
},
});
please try this code and send data ,and use post method in php to get data,it will work
if you are trying chat application check this, it is old but just for idea:
http://www.codeproject.com/Articles/649771/Chat-Application-in-PHP
use mysqli_query instead of mysql_query recommended
<?php
$id=$_GET['id'];
//$id1=$_SESSION['id']; COMMENTED THIS AS I AM NOT IN SESSION. HARDCODED IT IN THE FORM AS VALUE 5
?>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form method="post" class="msgfrm" id="msgfrm">
<input type="hidden" value="<?php echo $_GET['id']; ?>" name="rcvrid" id="rcvrid">
<input type="hidden" name="senderid" id="senderid" value="5" >
<div class="msgdiv" id="chatbox"></div>
<div class="textdiv">
<input type="text" name="msg" id="msg" class="textmsg">
<input type="submit" value="Send" >
</div>
</form>
<script>
$("#msgfrm").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "msg_save.php",
data: $(this).serialize(),
success: function(data) {
$("#chatbox").append(data+"<br/>");//instead this line here you can call some function to read database values and display
},
});
});
</script>
</body>
</html>
msg_save.php
<?php
//require_once('include/util.php');
$rcvrid = $_POST['rcvrid'];
$senderid = $_POST['senderid'];
$msg = $_POST['msg'];
echo $rcvrid.$senderid.$msg;
$con = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "insert into message(rcvrid,senderid,msg) values($rcvrid,$senderid,'$msg')";
mysqli_query($con,$sql);
mysqli_close($con);
echo "successful"
?>
check that whether you have inserted jquery file or not.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Then include your function sendChat() inside <script> tags.
On submit button
<button type="submit" id="button">SAVE</button>
<script>
$(document).ready(function(){
$("#button").click(function(){
var firstname=$("#firstname").val();
var lastname=$("#lastname").val();
var email=$("#email").val();
$.ajax({
url:'dbConfigAndInsertionQuery.php',
method:'POST',
data:{
firstname:firstname,
lastname:lastname,
email:email
},
success:function(data){
alert(data);
}
});
});
});
</script>

Form with PHP and AJAX Request

I have the following simple form:
Here is my code behind the form:
<form action="javascript:void(0);" method="post">
<fieldset>
<legend>ROOM EQUIPMENT</legend>
<div class="inline_inputs">
<div class="input_box">
<input type="checkbox" name="equipment" value="computer" id="computer">
<label for="computer">Computer</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="projector" id="projector">
<label for="projector">Projector</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="whiteboard" id="whiteboard">
<label for="whiteboard">Whiteboard</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="visualiser" id="visualiser">
<label for="visualiser">Visualiser</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="desk" id="desk">
<label for="desk">Desk</label>
</div><!-- .input_box -->
</div>
</fieldset>
<div class="buttons">
<input type="submit" class="reg_button" value="GET ROOMS" />
</div><!-- .buttons -->
And finally here is how I am making the AJAX request on the same page where this form sits:
<script>
$('form').submit(function(){
var str = $(this).serialize();
$.ajax({
url: "userLogic.php",
cache: false
}).done(function( html ) {
$("#rooms_wrap").append(html);
});
});
I am fairly new to PHP and I'm having an issue with the form submission. When I make a selection, my selection is not sent to the userLogic.php file. I get a print out of:
Sorry, You have not made a selection.
This is coming from the PHP code that sits inside the userLogic.php file which is this:
<?php
include("connect.php");
$items = array_key_exists('equipment', $_POST) ? $_POST['equipment'] : '';
if(!empty($items))
{
if ($_POST["equipment"] == "computer") {
echo "checked computer!";
} else if($_POST["equipment"] == "projector")
{
echo "checked projector!";
$sql = "SELECT room_name, day_avail, from_time, to_time, equip_name
FROM rooms
JOIN equipment ON (equipment.room_id = rooms.room_id)
JOIN room_availability ON (room_availability.room_id = rooms.room_id)
WHERE equip_name='Projector'
GROUP BY day_avail";
$myData = mysql_query($sql,$conn) or die(mysql_error());
} else if($_POST["equipment"] == "whiteboard")
{
echo "checked whiteboard!";
} else if($_POST["equipment"] == "visualiser")
{
echo "checked visualiser!";
} else if($_POST["equipment"] == "desk")
{
echo "checked desk!";
}
} else {
echo "> Sorry, You have not made a selection.";
}
?>
Look up the arguments for $.ajax. You're not POSTing... And you're not POSTing data, either.
type: "POST"
and
data: str
needs to be in:
$('form').submit(function(){
var str = $(this).serialize();
$.ajax({
url: "userLogic.php",
cache: false,
type: "POST",
data: str
}).done(function( html ) {
$("#rooms_wrap").append(html);
});
});
Doesn't seem you are posting your data..do it like this.
$.ajax({
url: "userLogic.php",
cache: false,
type: "POST",
data: str,
//rest of your code

issue sending a retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Try Changing Your Code A bit like Below .
Jquery part
success: function(d){
var output=d[0].data; // Will output only first record
$('#cuentas').html(output);
} // End of success function of ajax form
PHP PART
$centro = $_POST['centro'];
$output_string = array('data'=>$centro);
echo json_encode($output_string);
if still not works Check The Developer tool in chrome or firebug in firefox to monitor the Requests
Looking at your code:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
I miss an ending-tag for the div id="centro". Therefore the click-event for jQuery("#centro") will not trigger.
I suppose it should be like this: (Always set <form> and </form> inside OR outside of a div, do not mix and put <form> outside and </form> inside of a div. Some things wont work as expected when you do a mix like that.
<?php
$result = 'works';
?>
<div id="centro">
<form id="form">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
</div> ><!-- end of div centro -->
<div id="cuentas">
</div>
I solved it, now this works, plus I added a gif loader:
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
var result = $("input#centro").val();
$.ajax({
url: 'request.php',
type:'POST',
data: { 'dataString': result },
beforeSend: function(){
$("#loader").show();
},
success: function(output_string){
$("#loader").hide();
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
<div id="loader" style="display:none"><img src="ajax-loader.gif" width="20px" height="20px"></div>
Click here
<br>
<input type="hidden" name="centro" id="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP
<?php
$data = $_POST['dataString'];
$output_string = '';
$output_string = '<h3>'.$data.' '.'testing'.'</h3>';
echo $output_string;
?>
Output: "works testing"

Categories