I made a blogging platform and I have an ajax updated page where I can select which article to display and his comments and add comments. When I leave a comment it takes the logged user info, the article on which the comment has been made but the comment value is not taken to store it in the database. This is the code :
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
<?php
$comnou = $_POST['comentariu'];
$comuser = $_SESSION['user'];
$conadaugacom = mysqli_connect("localhost", "root", "", "blog");
$sqladaugacom = "insert into comentarii (continut_comentarii,
user_comentarii, articol_comentarii) values ('$comnou', '$comuser', '$ta')";
mysqli_query($conadaugacom, $sqladaugacom);
mysqli_close($conadaugacom);
?>
AJAX Code ->
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
}
Make sure that before POST request serialize the data from form.
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
Jquery
<script>
$('input').submit(function(e){
e.preventDefault();
var data = $('form').serialize();
$.ajax({
url: 'your_url_to_post.php',
data: data,
success: function(response){
},
type: 'POST'
});
});
</script>
php file
add this line to check comentariu not empty
if(isset($_POST['comentariu'])){
$comentariu = $_POST['comentariu];
}
Related
I am trying to create a page whereby you can submit some text and then retrieve it on button press, I have managed to get it to submit to my server, however on retrieval I keep getting the error "unexpected end of JSON input" and have no idea what to do about it, my knowledge of PHP/JSON is very limited, any criticism / pointers are greatly appreciated.
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("DataSubmitted");
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var data = JSON.parse(this.responseText);
alert(data);
}
}
xxhttp.open("GET", "gethint2.php", true);
xxhttp.send();
}
PHP/HTML:
<php? session_start(); ?>
<html>
<script type="text/javascript" src="main.js"></script>
<head>
</head>
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
</html>
Sending Data:
<?
$_SESSION["input_data"] = $_POST;
echo $_POST["input"];
?>
Retrieving Data:
<?php
$_SESSION["input_data"] = json_encode($_POST);
?>
So generally I have a form whose action is a link that verifies the user's username and password (can't post the link does not belong to me) and if it's correct it gives me an "ok" or else a "no"
How can I make it in a way that if yes it directs me to my index page and if no gives an error or reloads the page or something. Is their a way to do that
the general html appearance is:
<form method="post" action="https://***************/login">
<label for="book">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter username">
<label for="course">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter password">
<input type="submit" value="Log in">
</form>
so if I were to change it into the way I want it then the action should change into something like verify.php which would have the appearance of
<?php
# how do I use an if for a link using the info that was input
if($_POST["https://***************/login"]){
#load index.html
?>
<script type="text/javascript">
window.location.href = 'index.html';
</script>
<?php
else{
#load the page again
?>
<script type="text/javascript">
window.location.href = 'login.php';
</script>
<?php
}
?>
I'm a bit new to php.
So please help
There is a header to redirect, you have to put it in your php script :
header('Location: yoururl.com');
To record error from your script, you can set it in $_SESSION variables :
session_start(); // at the beginning of your script
$_SESSION['error'] = 'Password incorrect, please try again';
And so, in your other page, you can use something like :
if($_SESSION['error']) {
echo $_SESSION['error']; // display error
$_SESSION['error'] = ''; // delete it
}
Being unable to edit the login verification file, I think your best option is to submit the form via ajax and handle its response with javascript, having your form like
<form method="post" action="" onsubmit="return false;">
<label for="book">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter username">
<label for="course">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter password">
<input type="submit" value="Log in" onclick="btnAuthenticateUser();">
</form>
then, in plain javascript something like
<script type="text/javascript">
var xmlHttp;
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function btnAuthenticateUser() {
try {
var username = document.getElementById('username');
var pwd = document.getElementById('password');
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
var url = 'https://***************/login?username=' + username.value + '&password=' + pwd.value;
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
if (xmlHttp.responseText == "ok") {
window.location = "index.html";
} else {
location.reload();
}
}
if (xmlHttp.readyState == 4) {
// LoadingPage
}
}
}
xmlHttp.open("POST", url, true);
xmlHttp.send(null);
if (xmlHttp.readyState == 1) {
//LoadingPage
}
} catch (e) {
alert(e.Message);
}
}
</script>
or if you're using jQuery
function btnAuthenticateUser() {
$.ajax({
async: true,
type: 'POST',
url: 'https://***************/login',
data: { username: $('#username').val(), password: $('#password').val()}
})
.done(function (data) {
if (data == "ok") {
window.location = "index.html";
}else{
location.reload();
}
})
.fail(function (jqxhr, textStatus, error) {
GriterError(Global.FailTryAgain);
});
}
You can perform the action you need on your verification script and then throw in a redirect using the headers in PHP.
After the verification action you can choose which page to go to through an if/then statement
for example:
if ([the action you wanted succeeded]) {
header('Location: index.php');
}
else {
header('Location: login.php');
}
I know this has been mentioned many times in this thread but I still couldn't figure out how to solve my problem. I'm having difficulty on how to send and fetch my data from the comment.php to the insert.php
Here is my code for my comment.php:
(Notice the comments in javascript the method part [there's three of them], I've tried experimenting with them so that I could insert my data to the database but to no avail they didn't work. I'm still learning after all).Could someone help me. I'm still a beginner so I might find it difficult to understand an advance but i'll do my best.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Comment</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="bootstrap.min" />
<script type = "text/javascript" >
<!-- method 1-->
//$(document).ready( function() {
// $('#submit').click( function() {
//
// $('#getResponse').html('<img src="bootstrap/images /loading.gif">');
// $.post( 'insert.php', function(sendRequest) {
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"&web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
// $('#getResponse').html(sendRequest);
// });
// });
//});
<!-- -->
<!-- method 2-->
//function sendRequest() (
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
//)
<!-- -->
<!-- method 3-->
// function sendRequest()
//{
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,false);
// xmlhttp.send(null);
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
//}
<!-- -->
</script>
</head>
<body>
<form method = "post" action="">
<div id="main">
<div class="comment" style="display: block;">
<div class="avatar">
<img src="img/default_avatar.gif">
</div>
<div class="name">Avatar</div>
<div class="date" title="Added at 02:24 on 20 Feb 2015">20 Feb 2015</div>
<p>Avatar</p>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="Get" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name">
<label for="email">Your Email</label>
<input type="text" name="email" id="email">
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url">
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"> </textarea>
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<div id = "getResponse"></div>
</div>
</div>
</form>
</body>
</html>
Here is my code for the insert.php my php file where I perform the insertion of data to my database.
<?php
mysql_connect("localhost","root");
mysql_select_db("comment");
$name = $_GET['name'];
$email = $_GET['email'];
$web = $_GET['web'];
$comment = $_GET['comment'];
mysql_query("INSERT INTO demo (c_name,c_email,c_web,c_comment) VALUES ('$name','$email','$web','$comment')");
echo "Inserted Successfully";
?>
In your comment.php file , use Button,not submit.
And on click event of that button , call jQuery ajax
$('#button_id').click(function(){
//Get values of input fields from DOM structure
var params,name,email,url,body;
name=$("#name").val();
email=$("#email").val();
url=$("#url").val();
body=$("#body").val();
params = {'name':name,'email':email,'web':url,'comment':body};
$.ajax({
url:'insert.php',
data:params,
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
Update
I dont know whether you used button or submit. So I am specifying for you.
<input type="button" name="submit" id="button_id" value="Submit" >
you can use this to submit the record to insert.php action in the form should be action = "insert.php"
$('form#addCommentForm').on('submit', function(){
$("#response").show();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value ){
$('#response').html('<img src="images/loadingbar.gif"> loading...');
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$(".ajax")[0].reset();
$("#response").hide();
}
});
return false;
});
form the db connection script use this
<?php
$connect_error = 'sorry we\'re experiencing connection problems';
mysql_connect('localhost', 'root', '') or die($connect_error) ;
mysql_select_db('comment') or die($connect_error);
?>
you can also use the form serialize function, its good approach.
$('#addCommentForm').submit(function(form){
$.ajax({
url:'insert.php',
data: $(form).serialize(),
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
I have a form post.php where the user inputs data and receivepost.php where the data entered is transferred through Ajax post. I want to achieve the following in the receivepost.php:
if (button save is pressed) {
save to database
} else if (button retrieve is pressed) {
retrieve from database
}
I tried using isset($_POST['submit']) on the reveivepost.php but it does not detect the button which is pressed. The Ajax post is working and all the data is available on the receivepost page. I have another solution that is to create 2 different PHP files and run them according to the button pressed but I think there is a better solution to it.
Here is my ajax call :
$("document").ready(function () {
$("#submit").click(function () {
var xmlhttp;
// test browsers
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// get the values of textboxes
var desc_text = $("#desc").val();
var speed_text = $("#speed").val();
var tarea_text = $("#tarea").val();
// variable to hold value of textboxes
var content = "desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
// open the request
xmlhttp.open("POST", "receivepost.php", true);
// set header
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// check xmlhttp state and status and display text in div
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('para').innerHTML = xmlhttp.responseText;
}
}
// send the content of the textboxes
xmlhttp.send(content);
});
});
Here is my post.php form:
<form id="myform">
<label for="description">Description:</label>
<input type="text" id="desc" name="desc" /><br/>
<label for="speed">Speed: </label>
<input type="text" id="speed" name="speed" /><br/>
<textarea id="tarea" cols="10" rows="10" name="tarea"></textarea><br/>
<input type="button" id="submit" name = "submit" value="Save">
<input type="button" id="retrieve" name="retrieve" value="Retrieve">
</form>
<div id="para"></div>
Try to add to the content an extra parameter called button-pressed which you can later use in receivepost.php as below:
if($_POST['button-pressed']=="save"){
//savetodb code
}
else if($_POST['button-pressed']=="retrieve"){
//retreivefromdb code
}
Perhaps you have two JavaScript functions, one on each button:
$("#submit").click(function () {
var content = "button-pressed=save" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
$("#retrieve").click(function () {
var content = "button-pressed=retrieve" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
Hope this helps?
<input type="button" id="submit" name ="submit" value="save" onClick="fnc(this.id)">
<input type="button" id="retrieve" name="retrieve" value="retrieve" onClick="fnc(this.id)">
<script type="text/javascript">
function fnc(myid) {
var val=document.getElementById(myid).value;
alert(val);
}
</script>
I seem to have no luck with these darn AJAX MySQL queries...
I'm trying to query the database when a selection from a drop-down menu is made, and fill a div with the results from the script. I've tried two different ways, with no luck either time.
METHOD 1
Javascript
var ajaxRequest;
var create_url = "create_script.php";
var process_url = "process.php";
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
}
}
}
function races(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('race_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=race&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
function classes(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('class_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=classes&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
the page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="races('.$row['race_id'].');" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="classes('.$row['race_id'].');" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<br />
<div id="race_info"></div>
<br />
<hr />
<br />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
METHOD 2
AJAX
$(document).ready(function() {
$("#race_select").change(function() {
var race = $("#race").val();
$.ajax({
url: 'create_script.php',
data: 'mode=race&id=' + race,
dataType: 'json',
success: function(data)
{
$("#race_info").html(data);
}
});
});
$("#class_select").change(function() {
var class = $("#class").val();
$.post("create_script.php", { mode: "class", id: class }, function(data) {
$("#class_info").html(data);
});
});
});
The page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="race" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="class" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<div id="race_info"></div>
<hr />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
None of the attempts have worked at all. I'm not sure what I'm doing wrong. There's not even a POST request being made on the select option change, according to firebug.
well for starters, in method two, all of your select options have the same ids. therefore, when querying:
var race = $("#race").val();
you will always get the first option.
instead, within the change function, this will refer to the selected element. so:
var race = $(this).val();
will get what you want
EDIT
Here is a simplified example using your code demonstrating your desired behavior in jsfiddle form: http://jsfiddle.net/7Xtqv/1/
hope that helps
In your jQuery AJAX request, you're setting dataType to JSON. So jQuery attempts to parse the JSON once received. If it fails, nothing happens. Not even the request shown in Firebug.
If you're using html in your AJAX return, you should set the dataType to HTML.
EDIT
Oh and in the second request in your jQuery file, you're doing var class = $("#class").val();. You might want to avoid naming your vars with reserved names: http://www.quackit.com/javascript/javascript_reserved_words.cfm
EDIT2
As #pthurlow noticed, there's a big fail with your IDs names. You're trying to get #race select, but there's no race ID in your HTML. There's a #race_select but it's different from #race.
It also fails with your #class stuff.