I'm trying to insert data into a database using ajax and php , but this is not working. The connection with the database is working (tried it using only php). The ajax part of my code is posting and the values are valid (checked with firebug). I use postgresql for my data base
I don't know why it doesn't work.
When i press the comment button it works (i get no errors) , but the text in the fields doesn't go into the database
Here is the code:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(event) {
var name = $("#name").val();
var title= $('#title').val();
var comment= $('#comment').val();
$.post("comment.php", {name: name, title: title, comment: comment},
function (data) {
if (!data) {
$("#submit").append("Failed to reach server. Login Error.");
} else {
alert(data);
}
});
return false;
});
});
</script>
<div class='comments'>
<!--<form action="scripts/comment.php" method="POST"> -->
<form action="" method="POST">
<label>Name: </label><br /><input id="name"type="text" name="name" /><br /><br />
<label>Title: </label><br /><input id="title"type="text" name="title" /><br /><br />
<label>Comment: </label><br /><textarea id="comment" name="comment" cols="90" rows="7"> </textarea><br /><br /><br />
<input id="submit" type="submit" name="submit" value="Comment" /><br />
</form>
<hr width=auto size="5px" />
</div>
And the php for insertion:
<?php
if (isset($_POST['name'])) {
// attempt a connection
$conn_string = "host= port= dbname= user= password=";
$dbh = pg_connect($conn_string);
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
$name =pg_escape_string($_POST['name']);
$title= pg_escape_string($_POST['title']);
$comment =pg_escape_string($_POST['comment']);
$today=pg_escape_string(date('d-m-y'));
$sql = "INSERT INTO comments VALUES ('$name','$comment','$today','$title',nextval('comments_id_seq'::regclass))";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
pg_close($dbh);
// $page='../index.php';
//header('Location:'.$page);
}
?>
Any help would be appreciated :) . Thanks
Your $.post() call disregards the server's response which makes troubleshooting difficult. There are a few things you can to do correct this:
First, ensure that you have turned on PHP error reporting. If it is not turned on in your config, enable it near the beginning of your script like this:
error_reporting(E_ALL);
Next, find a way to see the output of your PHP script. You can modify your post call to receive and process the response, but an easier way is to temporarily post your HTML form directly to the script bypassing the AJAX call. See what output the script produces when you post the form directly to the script.
Related
i want to create a web service to check if the login
i create first an html form
<form action="webservice_ocl.php" method="post">
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
then i create a php file " webservice_ocl.php to do the traitement
<?php
session_start();
try {
$dbh = oci_connect('test', '123456', 'localhost/XE');
} catch (PDOException $e)
{
echo $e->getMessage();
}
if ($_POST['user'] != null and $_POST['user'] != "" and $_POST['password'] != null and $_POST['password'] != "")
{
$username = $_POST['user'];
$password = $_POST['password'];
$sth = oci_parse($dbh ,"SELECT * FROM utilisateur WHERE LOGIN='$username' and PASS='$password'");
oci_execute($sth);
if(oci_fetch($sth)){
echo "Nice";
}
else { echo "nono";}
}
?>
i want to konw , the php file " webservice_ocl.php " is a webservice ??
and how to call them in html using ajax ??
i want to use this on mobile developpement
I wouldn't really class webservice_ocl.php as a webservice as such, a webservice (in my opinion) is usually an SOAP/REST complaint API. See http://en.wikipedia.org/wiki/Web_service.
As for calling this with AJAX, I would personally look into jquery - namely the $.post function, I use this all the time and find it much easier than plain javascript.
Lastly, i would advise you look at how you have wrote your SQL statements - as pointed out by Quentin you are vulnerable for injection, which I have had done before (whoops) and believe me it is not nice!
Hope this helps.
Smithey.
Edit - If your looking at mobile apps, take a look at jquery mobile ;). I'm using it for a project im working on at the minute, its pretty cool!
====== in form.html change type="submit" to type="button" and delete action+mithod attr
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<form id="my-form" >
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
<div id=result >the result will display here</div>
<script type="text/javascript">
$("#btnSubmit").click({
$.post(
"webservice_ocl.php",
$("#my-form").serialize(),
function(data){ $("#result").html(data); }
);
});
</script>
I am working with jQuery autocomplete plugin and this is my index:
<script>
$(document).ready(function(){
$("#tag").autocomplete({source: "./search.php?q="+ $("#tag").val()});
});
</script>
<form action="search.php" method="post" class="form-inline search">
<input type="text" id="tag" name="tag">
<input type="submit" class="btn" value="Search" />
</form>
in search.php which is in the same folder as index.php is following:
include 'config.php';
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$sql="SELECT * FROM tags WHERE tag LIKE '%$my_data%'";
$result = mysql_query($sql) or die(mysql_error());
if($result)
{
while($row=mysql_fetch_array($result))
{
echo $row['tag']."\n";
}
}
When I start typing, autocomplete doesn't offer me any suggestions. Also no errors in JS console. In the code is just displayed No search results..
The paths are set up correctly, the database connection as well.
Thus, where could be a problem?
Thank you
You don't need to use a query string on the src url of autocomplete.
Just write your src file without query string:
$("#tag").autocomplete({source: "./search.php"});
And in your php file you have to capture the term parameter:
$q = $_GET['term'];
Solved this way - in PHP file must be data returned in JSON:
while($row=mysql_fetch_array($data))
{
$result[] = $row['tag'];
}
echo json_encode($result);
I want the user to fill it out. Submit it, have it store into the database and then use jquery to have it show up on the same page in front of them. Right now I can get it to send to the database but it opens up in another page (/data.php) on submit. Also I have it set to random because I don't know how to get the exact post just sent by the user back to display.
Here is my data.php file:
<?php
$con = mysql_connect("*****", "******", "******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("textwall", $con);
$sql="INSERT INTO textwalltable (story)
VALUES
('$_POST[story]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$sql = "SELECT * FROM textwalltable ORDER BY RAND() LIMIT 1;";
$query = mysql_query( $sql );
while($row = mysql_fetch_array($query)) {
echo $row['story'];
}
mysql_close($con);
?>
and my HTML page:
<html>
<head>
<title>testing</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js"><\/script>')</script>
<script type="text/javascript">
function loadData()
{
$("#txtHint").load("data.php");
}
</script>
</head>
<body>
<form action="data.php" method="post" onsubmit="loadData()">
<div>
<label for="comment">Type here:</label>
<textarea id="story" name="story" rows="2" cols="20">
</textarea>
<div id="txtHint"></div>
</div>
<div>
<div><input type="submit" value="Submit" class="submit"/></div>
</form>
</body>
Here is work flow:
1) User hits form submit.
2) You gather necessary information from DOM. You AJAX the information to a server-side script that enters that info into the database.
3) You use JQuery to insert the information however you want to display it into the DOM.
4) Remove whatever html you no longer need on the page if necessary.
In terms of code you are going to want to look at JQuery's ajax or post functions for the AJAX call.
You can use a javascript function (using jquery) to handle those events. This method does not use a button, so you will need to create your own button that will call the following function:
function postPage() {
$.post("post.php", $("#form_id").serialize(), function(){
$("#display_id").load('display.php');
});
}
You will need to have the post values processed in this case by "test.php", and then the contents of which you want to display back to the user after posting in display.php. The contents of display.php will be placed inside a div/container with the id of "display".
Here is another way, if you use the serialize function built into jquery along with the $.post you won't have to actually write much code.
html form and html displaying the messages:
<form action="data.php" method="post" class="commentForm">
<div>
<label for="comment">Type here:</label>
<textarea id="story" name="story" rows="2" cols="20">
</textarea>
<div id="txtHint"></div>
</div>
<div>
<div><input type="submit" value="Submit" class="submit"/></div>
</form>
<ul class="messages">
<li>Some old message</li>
<li>Some other old message</li>
</ul>
jquery to send the new messages to your server from the client and placing new message into the DOM and resetting the html form
//bind a click even to the submit
$('.commentForm input[type=submit]').click(function(){
$(this).closest('form').find('input[type=submit]').value('Submitting');
$.post(
$(this).closest('form').attr('action'),
$(this).closest('form').serialize(),
function(responseFromServer){
//get the message from the html form (don't need to send it back from the server)
var message = $(this).closest('form').find('textarea');
$('.messages').append('<li>'+message+'</li>');
//resetting the html form
$(this).closest('form').find('textarea').html('');
$(this).closest('form').find('input[type=submit]').value('Submit');
}
);
//prevent the form from actually sending in the standard fashion by returning false
return false;
});
php
//get the post variable and make it safe for inputting into the db
$message = mysql_real_escape_string(html_entities($_POST['story']));
if(!empty($message)){
//assuming you have a db connection
$insert_query = mysql_query("INSERT INTO textwalltable VALUES($message)");
echo 'message entered';
} else {
echo 'no message';
}
I have a php form that saves the info to my database and sends an email upon completion. however it will not validate the fields to see if they are null, instead it prints both the set and not set options. Any ideas as to why this could be happening? It worked perfectly before i added the form field validation to it.
As a side note it works in FF and Chrome due to the html 5 aria-required, but not in IE
html
<form id="contact" name="contact" action="register1.php" method="post">
<label for='Cname'>Camper Name</label>
<input type="text" name="Cname" maxlength="50" value="" required aria-required=true />
<input type="hidden" id="action" name="action" value="submitform" />
<input type="submit" id="submit" name="submit" value="Continue to Camp Selction"/>
</form>
php
<?php
//include the connection file
require_once('connection.php');
//save the data on the DB and send the email
if(isset($_POST['action']) && $_POST['action'] == 'submitform')
{
//recieve the variables
$Cname = $_POST['Cname'];
//form validation (this is where it all breaks)
if (isset($Cname)) {
echo "This var is set so I will print.";
}
else {
echo '<script type="text/javascript">alert("please enter the required fields");</script>';
}
//save the data on the DB (this part works fine)
<?php
$Cname = isset($_POST['Cname']) ? $_POST['Cname'] : null;
if (isset($Cname)) {
echo "This var is set so I will print.";
}
// OR
if (isset($_POST['Cname'])) {
// Perform your database action here...
}
?>
Consider using PHP's empty function
PHP.Net Manual Empty()
You can update your code to the following:
if(!empty($Cname)) {
echo "This var is set so I will print.";
}
Do you just need an "exit()" in the else?
I need to use AJAX to save user input comments instantly to the database.
This is the comment box.
<div class="comment">
<form action="comment.php">
<textarea cols="35" name="comments"> Give us comment </textarea>
<input type="button" value="comment" onclick="ajaxFunction()">
</form>
</div>
This is the php code
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$comments = $_POST['comments'];
if($comments == "")
echo "Please type your comment";
else
{
$query = "insert into comment(comment) values('$comments') ";
mysql_query($query);
}
return;
?>
I need to know how this should be changed.
Thank You
I would chnage your HTML like this
<textarea cols="35" id="comments"> Give us comment </textarea>
<input type="button" value="comment" id="btnSave" />
And the script
$(function(){
$("#btnSave").click(function(e){
e.preventDefault();
$.post("yourphpfile.php", { comments : $("#comments").val() } ,function(data){
alert(data);
});
});
});
The above script will send an ajax request to yourphpfile.php with the value present in the textarea with id comment. Then once it gets some data back from the server page. it justs alerts it ( you may show this in a seperate div if you want ). You should echo the response from your php file after saving the data to database.
As bracketworks already mentioned, you should be careful about SQL injections while saving data which is being read from the querystring value. do proper sanitization before putting it in a query. Sorry i am not a php guy. so not sure how to do that.
Don't forget to include the jQuery library to your page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
You may use firebug console for debugging your script error if you run into any.