GET Data from page disappears when using AJAX - php

Kind of a newbie in using PHP/Ajax/SQL.
I am currently working in a small project where in we're asked to create a Facebook-esque website using the languages above. I am trying to create pages wherein the user can view the individual posts and the comments in each post. The user can also post comments on the same page. I also have a database to store the different details needed for the project (posts, user details, comments, etc.)
The data acquired from the page displaying the posts is passed through a GET method. There is also an ajax function for inserting the comment data into my database. The problem is, every time I try to insert the data into the database (through AJAX), the following error appears:
Notice: Undefined index: blog_title in C:\xampp\htdocs\postpage.php on line 24
I also noticed that the data I passed through the GET method disappears when I try to call the AJAX function. What can I do to solve the error?
Post data is acquired through here(line 24):
$blog_title = $_GET['blog_title'];
HTML:
<!DOCTYPE html>
<html>
<head>
<title><?=$blog_title?></title>
</head>
<body>
<div class = "details">
<h2><?=$row['title']?></h2>
<h3>Published by: <a link href = "<?=$location?>"><?=$row['author_name']?></a></h3>
<h4>Date Posted: <?=$row['date']?> at <?=$row['time']?></h4>
</div>
<br>
<p>
<?=$row['content']?>
</p><br><br>
<div class = "commentarea">
<form>
<label>Commenting as: <?=$my_username?></label><br>
<textarea rows = "10" cols = "20" id = "comment" required></textarea>
<button name = "comment" id = "post" onclick="Comment($('#comment').val(), <?=$my_username?>, <?=$blog_title?>)">Submit Comment</button>
</form>
<div>
AJAX Function:
<script src = "js/jquery.js"></script>
<script>
function Comment(comment, username, title){
//alert(search + " " + filter);
$.ajax({
method:"POST",
url:"comment.php",
data:{
"comment":comment,
"commenter_name":username,
"commented_post":title,
},
dataType = "json",
success: function(result){
alert("Comment posted.");
$("#record").html(result);
}
});
}
</script>
Thank you in advance!

In your Ajax call, you are specifying the method as POST. But in your PHP page, you are trying to get the request using $_GET['blog_title'] and that is why you are getting undefined variable error.
Instead of $_GET you should either use $_POST or $_REQUEST. That is, replace
$blog_title = $_GET['blog_title'];
with
$blog_title = $_POST['blog_title'];
or
$blog_title = $_REQUEST['blog_title'];
Read more about $_REQUEST and $_POST in the docs.
OR
you can change your ajax request as below.
$.ajax({
method:"GET", //changed method to GET
url:"comment.php",
data:{
"comment":comment,
"commenter_name":username,
"commented_post":title,
},
dataType = "json",
success: function(result){
alert("Comment posted.");
$("#record").html(result);
}
});

Like Lal answer, you first need to convert to the GET method, then you need to declare the blog_title parameter.
<script src = "js/jquery.js"></script>
<script>
function Comment(comment, username, title){
//alert(search + " " + filter);
$.ajax({
method:"GET", // Changed method to GET
url:"comment.php",
data:{
"comment":comment,
"commenter_name":username,
"commented_post":title,
"blog_title":title //You must declare the blog_title parameter here
},
dataType = "json",
success: function(result){
alert("Comment posted.");
$("#record").html(result);
}
});
}
</script>

Related

Getting jQuery variable to PHP in the same file without refreshing the page

Thanks for reading. I have tried the answers in other similar questions but none have worked so far. I'm trying to UPDATE values inside a Table that is inside a form, so in the first part of the file is the isset "saveImport" which is the name of the a tag that I'm using to send the id thru the URL:
if (isset($_POST['saveImport'])) {
$id = $_POST['id'];
}
a tag:
<a name="saveImport" href="./?id=<?= $row['id']; ?>" class="saveImport btn btn-success col-xs">Save</a>
I do get the ID value in the URL but since is been updated in the same file I'm assuming it refreshes the page before the variable gets post thru AJAX:
<script type="text/javascript">
$(document).ready(function() {
$('.saveImport').click(function() {
var imp_id = id.id;
var imp_href = $(id).attr('href');
alert(imp_href);
$.ajax({
url: "./",
data: {id : imp_id},
type: "POST",
success: function(data){
alert(id);//send this ID to the PHP variable without
//refreshing the file
}
});
});
});
I'm getting the class .saveImport because it's inside a Table which is displaying values from a Database so it's inside a while loop and if I use an ID it will cause conflict as the ID will repeat itself.
I already created the PHP function to UPDATE the Values which executes if the ISSET is true, so my real problem will be to execute the ISSET and inside grab the ID that was posted with AJAX so I can use the ID in the UPDATE function. Right now, if I click on the a tag, it sends the ID thru URL, the page refreshes but the value of the ID is not getting in the $id = $_POST['id];
I appreciate your time.
This should work.
Change the ajax url to your php file name (mine was t.php).
Replace 99 with your data from php. (id is used. href is not used)
<?php
if (isset($_POST['saveImport'])) {
print_r( $_POST );
exit;
}
?>
<a name="saveImport" id='99' href="./?id=99" class="saveImport btn btn-success col-xs"'>Save</a>
<script type="text/javascript">
$('.saveImport').click(function(event) {
var imp_id = this.id;
$.ajax({
url: "t.php",
data: {id : imp_id, saveImport: 1},
type: "POST",
success: function(data){
alert( data );//send this ID to the PHP variable without
//refreshing the file
}
});
event.preventDefault();
});
</script>
.preventDefault() will prevent the link from loading the target page... And then, ajax will proceed.
$('.saveImport').click(function(event) {
event.preventDefault();

How to pass ajax sucess result to another php page

In my code below I want display $("#searchresults").html(data) this result to other page.
$.ajax({
type: "POST",
url: base_url + 'front/searchresult',
data: data,
success: function(data) {
alert("test");
var val = $("#searchresults").html(data);
window.location.assign("<?php echo base_url()?>front/search/" + val);
}
});
what exactly is in the data variable you receive from your post? is it a json object? is it plain text?
if it is html, I think you should consider placing the result in a div on the current page, and hide items you don't want to see after searching
relocating after ajax requests is not the way to go. Is it an option in your case, to use a form and change the action attribute of the form to your new location?
<form action="front/search/">
<input type="text" name="data">
</form>

How to submit a form to the same page and refresh content without reloading entire page

Basically what I'm trying to do is post comments to a page without having to refresh the entire page. Just the Comments DIV so it looks like it posted and refreshed smoothly.
The form submits to the same page it's on. Everything I've found shows me how to refresh content constantly using intervals. I just want the comments DIV to refresh when someone posts a comment.
I can't find the correct ajax code to do this the way I want.
Here is my code:
var submit_button = $('#submit_button');
submit_button.click(function() {
var commentSubmitted= $('commentSubmitted').val();
var update_div = $('#update_div');
$.ajax({
type: 'POST',
url: '/blog/',
data: data,
success:function(html){
update_div.html(html);
}
});
});
in the same PHP file, I have the post to DB:
if($_POST[commentSubmitted])
{
$query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
mysql_query($query);
}
The HTML is for the form:
<form id="flow" method='post' action='/blog/'>
<textarea name='commentSubmitted' ></textarea>
<input type='submit' value='Post'/>
The DIV containing all comments looks like so:
<DIV id='AllComments'>
// comments displayed here
</DIV>
So after submitting the form, I would like the 'AllComments' DIV to reload.
The best would be to use jQuery to make the ajax call to the server and retrieve the data you want.
You have two ways of retrieving the data. Either retrieve the additional comments to show in a json array and handle it with javascript, or create the html on the server side and append/replace the html in the comments section.
Using Json
$.ajax({
url: "the_ajax_url_here",
type: "post",
data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
dataType: "json"
success: function(response) {
// handle the response
}
});
Retrieving Html
$.ajax({
url: "the_ajax_url_here",
type: "post",
data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
dataType: "html"
success: function(response) {
// set the html of comments section to the newly retrieved html
$("comments_section_selector").html(response);
}
});
What I would do is retrieve the newly added comment in a json array and then using javascript append it to the comments section.
edit:
After seeing your code I have some comments that might help you.
I would personally prefer the code that handles the ajax request in a separate file.
In that file you can store the new comment and create the html to display that comment.
Then in the success function just append the new html to the comment section like so:
success: function(response) {
$('#AllComments').append(response);
}
You can also make new comment appear on top using prepend
$('#AllComments').prepend(response);
Simple as that hope you are upto it
submit_button.click(function() {
var commentSubmitted= $('commentSubmitted').val();
var update_div = $('#update_div');
$.ajax({
type: 'POST',
url: '/blog/',
data: data,
success:function(html){
update_div.html(html);
}
});
});
Then you go to insert data
if($_POST[commentSubmitted])
{
$query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
mysql_query($query);
//After Inserting data retrieve back all the comments from db
$sql = "select * from comments";//any query and execute it
$query = mysql_query($sql);
while($data = mysql_fetch_array($query)){
echo $data["comments"];//Echo your commenets here
}
exit;
}
Thats it

How to pass multiple parameters by jQuery.ajax() to PHP?

I have a simple load more style script that works fine on the index page, where only one parameter is sent via ajax
$(function() {//When the Dom is ready
$('.load_more').live("click",function() {//If user clicks on hyperlink with class name = load_more
var last_msg_id = $(this).attr("id");//Get the id of this hyperlink this id indicate the row id in the database
if(last_msg_id!='end'){//if the hyperlink id is not equal to "end"
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: "lastmsg="+ last_msg_id,
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
With this HTML/PHP
<div id="more">
<a id="<?php echo $msg_id; ?>" class="load_more" href="#">more</a>
</div>
However, I want to add another php variable so that it can also work with particular categories, I have no problems writing the HTML and PHP but I am new to Jquery and struggling to edit the script to include the additional parameter if it is set. This is the HTML that I am thinking of using, just struggling with editing the JQuery
<div id="more"class="<?php echo $cat_id;?>">
<a id="<?php echo $msg_id;?>" class="load_more2" href="#">more</a>
</div>
As always any help is much appreciated!
You can set
data = {onevar:'oneval', twovar:'twoval'}
And both key/value pairs will be sent.
See Jquery ajax docs
If you look under the data section, you can see that you can pass a query string like you are, an array, or an object. If you were to use the same method you already are using then your data value would be like "lastmsg="+ last_msg_id + "&otherthing=" + otherthing,
You can pass multiple URL params in the data portion of your ajax call.
data: "lastmsg="+ last_msg_id +"&otherparam="+ other_param
On the PHP side, you'd just process these as you already are.
You can use this code:
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: {var1: "value1", var2: "value2"},
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
Try It:
data: JSON.stringify({ lastmsg: last_msg_id, secondparam: second_param_value});
You can add more parameters separating them by comma (,).

ajax POST not working, can't figure why

I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.

Categories