Insert PHP PDO via AJAX - php

I'm hittin' the wall for some days already, and can't seem to resolve this simple problem.
I want to make a simple insert via ajax. As i'm new to PHP, I've seen many examples, read the POST stuff for http and php, read te jquery.ajax documentation, and I'm aware of the PDO documentation aswell.
Still, can't find why it's not working.
Here goes the codes, really simple:
Index
<body>
<form id="myForm" method="post" action="" >
Nome:
<input type="text" name="nome" required />
<br/>
Tipo:
<input type="text" name="tipo" required />
<br/>
<input type="submit" name="submit" value="save" id="sub"/>
</form>
<script src="script/jquery-2.1.0.js" type="text/javascript"></script>
<script src="script/ajaxInclude.js" type="text/javascript"></script>
</body>
Ajax call
$(document).ready(function(){
$('#myForm').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "DAO/insert.php",
type: "POST",
data: data,
success: function( data )
{
alert( data );
},
error: function(){
alert('ERRO');
}
});
return false;
});
});
Config :
<?php
define('HOST', '127.0.0.1');
define('DB_NAME','test');
define('PORT', '3306');
define('USER','root');
define('PASS','');
$dsn = 'mysql:host='.HOST.'; port='.PORT.'; dbname='.DB_NAME;
try {
$bd = new PDO($dsn, USER, PASS);
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Houve algum erro no Banco de Dados';
}
?>
Insert:
<?php
require_once('config.php');
if(isset($_POST['submit'])){
$nome = $_POST['nome'];
$tipo = $_POST['tipo'];
$sql = 'INSERT INTO produto(id, nome, tipo, criado_em) ';
$sql .= ' VALUES (NULL, :nome, :tipo, NOW())';
try {
$query = $bd->prepare($sql);
$query->bindValue(':nome', $nome, PDO::PARAM_STR);
$query->bindValue(':tipo', $tipo, PDO::PARAM_STR);
if($query->execute()){
echo "Dados inseridos com sucesso";
}else{
echo "Falha na inser��o de dados";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
I've changed it a million times, and still, I can't even get the returns from the insert, I just get the alert from the sucess from ajax.
Sorry for so simple question, but I'm having some bad time with it. I'm trying to do all with the best practices I've found, and haven't found a solid example of this.

var data = $_POST['#myForm'].serialize();
should probably be
var data = $(this).serialize();
Additionally, you should check for all required parameteres if they're set, submit will never be set, because your submit-input doesn't have a name attribute:
if(isset($_POST['nome'], $_POST['tipo'])) {
// your stuff here...
}
And leaving "php mode" in this way can result in blank lines and you have no idea where they come from later:
?>
<?php

1st as mentioned by Kelunik you have php mixed in with your javascript:
var data = $_POST['#myForm'].serialize();
$_POST is a php array. This should be:
var data = $(this).serialize();
Second (and the reason you see an empty alert), you dont have a name attribute on your submit button, so the if(isset($_POST['submit'])) conditional check in php fails.
Change:
<input type="submit" value="save" id="sub"/>
to:
<input type="submit" name="submit" value="save" id="sub"/>
Lastly, if this php file produces other output (as your comments suggest) make sure you stop execution after returning your responce:
if(isset($_POST['submit'])){
//your sql code and responces here
//then stop script
die();
}

Related

Want to run PHP query when submit button submitted using AJAX

I want to run insert.php query if button name with "addUser" is submitted i don't know how to pass addUser name parameter using AJAX to insert.php file where it check if button is submitted or not .
if i remove if statement in insert.php file this is inserting users to database but if directly visit insert.php its inserting empty records in table
i want to prevent entry of empty records in table if i visit insert.php directly .
index.html
<form method="post" id="addForm">
Username :<input type="text" name="username" id="userName" />
Passkey :<input type="password" name="passkey" id="passKey"/>
<br/>
<input type="submit" name="addUser" id="submitBtn" value="Inser New User"/>
</form>
<script>
$("#addForm").submit(function(e){
let userNameZ = $("#userName").val();
let passKeyZ = $("#passKey").val();
$.ajax({
url:'insert.php',
type:'POST',
data: {userName:userNameZ,passKey:passKeyZ},
success: function(resp) {
if(resp == "inserted") {
$("#addForm").trigger("reset");
alert("New user inserted");
} else {
alert("Something went wrong");
}
}
});
});
</script>
insert.php
<?php
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
if(isset($_POST['addUser'])){
$userName = trim($_POST['userName']);
$passKey = trim($_POST['passKey']);
$query = "INSERT INTO users (username,passkey) VALUES (:userName,:passKey)";
$stmt = $conn->prepare($query);
$stmt->execute(array(':userName'=>$userName, ':passKey'=>$passKey));
if($stmt) {
echo "inserted";
} else {
echo "not inserted";
}
}
?>
Change this if(isset($_POST['addUser'])){
to
if(isset($_POST['userName']) && isset($_POST['passKey'])){
OR in ajax, change
data: {userName:userNameZ,passKey:passKeyZ,addUser:1},
Notice: ,addUser:1
Adding answer to your comment
what if i have more than 10 values to be submit
.
You can use $("#addForm").serialize() and pass directly to data. Like
data: $("#addForm").serialize(),

AJAX to database sending null to PHP script

I'm trying to use ajax to insert using a simple form into my database(using insert.php) to practice. Below the var_dump($email) is hitting null. The script runs through to here:
echo "Data for $name inserted successfully!";
The problem is the variables are null as stated.
So we make it to there, but the output is an empty variable field like below:
Data for inserted successfully!
Am I missing something here?
index.php
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- The ajax/jquery stuff -->
<script type="text/javascript">
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
$("#insert").click(function(){
//Get values of the input fields and store it into the variables.
var name=$("#name").val();
var email=$("#email").val();
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('insert.php', {name: name, email: email},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(1500); //Fade in the data given by the insert.php file
});
return false;
});
});
</script>
</head>
<body>
<form>
<label>Name: </label> <input id="name" type="text" />
<label>E-Mail: </label> <input id="email" type="text" />
</form>
<a id="insert" title="Insert Data" href="#">Push into mysql</a>
<!-- For displaying a message -->
<div id="message"></div>
</body>
</html>
insert.php
<?php
//Configure and Connect to the Databse
include "db_conx.php";
if (!$db_conx) {
die('Could not connect: ' . mysqli_error());
}
//Pull data from home.php front-end page
$name=$_POST['name'];
$email=$_POST['email'];
echo "<pre>";
var_dump($email);
echo "</pre><br>";
//Insert Data into mysql INSERT INTO best_rate (name,email)
$query= "INSERT INTO best_rate(name,email) VALUES('$name','$email')";
$result = mysqli_query($db_conx,$query);
if($query){
echo "Data for $name inserted successfully!";
}
else{ echo "An error occurred!"; }
?>
UPDATE PHP #2
<?php
//Configure and Connect to the Databse
include "db_conx.php";
if (!$db_conx) {
die('Could not connect: ' . mysqli_error());
}
//Pull data from home.php front-end page
$name=$_POST['myname'];
$email=$_POST['myemail'];
echo "<pre>";
var_dump($email);
echo "</pre><br>";
//Insert Data into mysql INSERT INTO best_rate (name,email)
$query= "INSERT INTO best_rate(name,email) VALUES('$name','$email')";
$result = mysqli_query($db_conx,$query);
if($query){
echo "Data for $name inserted successfully!";
}
else{ echo "An error occurred!"; }
?>
HTML #2
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- The ajax/jquery stuff -->
<script type="text/javascript">
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
$("#insert").click(function(){
//Get values of the input fields and store it into the variables.
var name=$("#name").val();
var email=$("#email").val();
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('insert.php', {myname: name, myemail: email},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(1500); //Fade in the data given by the insert.php file
});
return false;
});
});
</script>
</head>
<body>
<form>
<label>Name: </label> <input id="name" type="text" name="myname"/>
<label>E-Mail: </label><input id="email" type="text" name="myemail"/>
</form>
<a id="insert" title="Insert Data" href="#">Push into mysql</a>
<!-- For displaying a message -->
<div id="message"></div>
</body>
</html>
Table Structure
===============================================
id | name | email
db_conx.php
<?php
$db_conx = mysqli_connect("localhost", "user", "pass", "database");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
you havent gave name attribut to your feilds
<input id="name" type="text" />
use instead
<input id="name" type="text" name="myname"/>
and then used like this in your php file
$name=$_POST['myname'];
I can see you are having post method issue so we can use $.get instead of $.post and receive the data on $_GET["name"]
I think this is correct solution for now.
Thanks
I have checked your code and working correctly, as I can see there might be some issue with database connection or something mysql related. Your code working correct no need to give name or any other parameter in HTML as you have posted and given variable in jquery.
If you want more details you need to provide mysql related config file and table structure so I can check correctly.
Thanks
It sounds to me that the values from the inputs aren't getting passed to the php script to insert them.
I have noticed in your code that you pass an oject that contains these values:
$.post('insert.php', {myname: name, myemail: email},
I beleive that you are setting the name of the property (ie. myname) incorrectly. From my understanding, the javascript is interpriting myname as a variable rather than a name. The correct code would be:
$.post('insert.php', {'myname': name, 'myemail': email},
This would then properly set the POST variables to use in your php code.

How to submit HTML form using TinyMCE, jQuery and PDO? (full code)

The $_POST['reply'] variable contains html tags like <p>text goes here</p> but I can not insert it into the database. For the reply I use the TinyMCE and when I do not use it (the input as no tags) like text goes here then it is inserted correctly.
What am I missing here?
try {
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("INSERT INTO replies(article_id, comment) VALUES (:article_id, :comment)");
$stmt->bindParam(':article_id', $article_id, PDO::PARAM_INT);
$stmt->bindParam(':comment', $_POST['reply'], PDO::PARAM_STR);
if($stmt->execute()) {
echo 'success';
}
$db = null;
} catch(PDOException $e) {
trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}
Here is the form code:
<form class="comment-form">
<div class="form-input">
<input type="hidden" name="post_id" value="<?= $row['id']; ?>" />
</div>
<div class="form-input">
<textarea name="reply" id="elm1" rows="8" placeholder="Your comment here" ></textarea>
</div>
<div class="form-input">
<input type="Submit" class="btn btn-primary" id="submit" value="SEND" />
</div>
</form>
<script type="text/javascript">
$(function(){
$(".comment-form").submit(function(event){
event.preventDefault();
$("#results")
.show();
$.post('add-it.php', $(".comment-form").serialize(), function(data) {
$('#submit')
.hide();
$('#results')
.html(data)
.fadeIn('slow');
});
});
});
</script>
Since you use AJAX, you need to manually trigger saving function in TinyMCE. And that needs to be done, before you send a request.
$("#results").show();
tinyMCE.triggerSave(); // <--- Add this here
$.post('add-it.php'....
And this absolutely has nothing to do with PDO. You could simply do print_r($_POST) to see if data comes, before inserting a record to a table.
You can use
$pdo->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);
instead of bindParam this should insert your html code.
And you should set post as method to your form
<form action="#" method="post" class="comment-form">
</form>
And the next one that you should remove your javascript code and test it without and with a normal form to test your problem.
Then main problem is that you $_POST variable is empty its not a PDO problem.
And the last one if your send your request with Ajax you have to call the
tinyMCE.triggerSave();
http://www.tinymce.com/wiki.php/API3:method.tinymce.triggerSave
function ins TinyMCE otherwise your post variable is empty.
I think your issue is that TinyMCE doesn't bind it's changes to the textarea automatically. You need to call tinyMCE.triggerSave() in your submit handler. See When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database.
I have attached a full code sample, which I can confirm works.
<?php
define('DB_DRIVER', 'mysql');
define('DB_DATABASE', 'test');
define('DB_SERVER', '127.0.0.1');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
try {
$db = new PDO(
DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER,
DB_USER,
DB_PASSWORD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("
INSERT INTO replies(article_id, comment)
VALUES (:article_id, :comment)");
$stmt->bindValue(':article_id', $_POST['article_id'], PDO::PARAM_INT);
$stmt->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);
if ($stmt->execute()) {
echo 'success';
}
$db = null;
} catch (PDOException $e) {
trigger_error('Error occurred while trying to insert into the DB:'
. $e->getMessage(), E_USER_ERROR);
}
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>tinymce.init({selector: 'textarea'});</script>
<form class="comment-form">
<div class="form-input">
<input type="hidden" name="article_id" value="1"/>
</div>
<div class="form-input">
<textarea name="reply" id="elm1"></textarea>
</div>
<div class="form-input">
<input type="Submit" class="btn btn-primary" id="submit" value="SEND"/>
</div>
</form>
<div id="results">
Results
</div>
<script type="text/javascript">
$(function () {
$(".comment-form").submit(function (event) {
event.preventDefault();
$("#results").show();
tinyMCE.triggerSave();
$.post('add-it.php', $(".comment-form").serialize(),
function (data) {
$('#submit').hide();
$('#results').html(data).fadeIn('slow');
});
});
});
</script>
CREATE TABLE `replies` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`article_id` int(11) DEFAULT NULL,
`comment` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
I have taken your code and played with it quite a bit and I think I have been able to sort it for you hopefully, I have changed the $(".comment-form").serialize() for adding the data manually. I have also added tinymce.get('elm1').getContent() as this will retrieve the data thats inside the TinyMCE textarea.
<script type="text/javascript">
$(function(){
$(".comment-form").submit(function(event){
event.preventDefault();
$("#results")
.show();
$.post('add-it.php', {
post_id: $( '.post_id' ).val(),
reply: tinymce.get('elm1').getContent()
}, function(data) {
$('#submit')
.hide();
$('#results')
.html(data)
.fadeIn('slow');
});
});
});
</script>
I think an idea for a solution is provided in this question HTML Tags stripped using tinyMCE. Try to use a simple textarea and check if html is posted correctly and saved to the database. This way you will have another clue if this is a fault server-side or client-side. Also try this http://jsfiddle.net/PGtPa/172/ to check your serialized output.
textarea_value -> <p>do this do that</p>
serialized_value -> %3Cp%3Edo+this+do+that%3C%2Fp%3E
jQuery serialize is url-encoding output so check if there is conflict with tinymce settings regarding that part. Also if mod_security is giving you issues you could try to base64 encode textarea value with javascript before posting and base64 decode server-side to get your real value back. For base64 and javascript check this https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding which have a nice example if you use utf8.

How to figure out where this database insertion and retrieval is breaking?

Problem solved...variable undefined. I will add full answer when stackoverflow allows me to answer own question
update, firebug is telling me that the variable barrister is undefined in plugin.php but I do define that variable (or at least I try to)
this is the line where it's supposedly undefined: if(barrister.attr("value"))
this is the line where I try to define it: var barrister = $('input:radio[name=barrister]:checked').val();
I'm using a form with a radio button to submit data. The file plugin.php is supposed to get the data using javascript/ajax and then send it to results.php so that it can be inserted into the database. Information's also retrieved from the database and is supposed to be inserted into the html. I can't figure out where it's breaking down, but I do know the database connection itself works. Any idea how I might find out the broken link? When I test it and check the database, there's no data in it.
The form
<form method="post" id="form">
<table>
<tr>
<td><label>Barrister's Exam</label></td>
<td><input type="radio" id="barrister" name="barrister" value="1" /> Pass</td>
<td><input type="radio" id="barrister" name="barrister" value="0" /> Fail</td>
</tr>
<tr>
<td>Submit</td>
<td><input id="send" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
Getting the form data with plugin.php
function my_function() { ?>
<script type="text/javascript">
$(document).ready(function(){
//global vars
var barrister = $('input:radio[name=barrister]:checked').val();
var loading = $("#loading");
var messageList = $(".content > ul");
//functions
function updateShoutbox(){
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=update",
complete: function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000);
}
});
}
//check if all fields are filled
function checkForm(){
if(barrister.attr("value"))
return true;
else
return false;
}
//Load for the first time the shoutbox data
updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){
var barrister = barrister.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to results.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
});
</script>
<?php
}
add_action('wp_head', 'my_function');
putting the data into "results" table of the database "year" with results.php I know the database connection works
<?php
define("HOST", "host");
define("USER", "user");
define("PASSWORD", "password");
define("DB", "year");
/************************
FUNCTIONS
/************************/
function connect($db, $user, $password){
$link = #mysql_connect($db, $user, $password);
if (!$link)
die("Could not connect: ".mysql_error());
else{
$db = mysql_select_db(DB);
if(!$db)
die("Could not select database: ".mysql_error());
else return $link;
}
}
function getContent($link, $num){
$res = #mysql_query("SELECT barrister FROM results ORDER BY date DESC LIMIT ".$num, $link);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
function insertMessage($barrister){
$query = sprintf("INSERT INTO results(barrister) VALUES('%s');", mysql_real_escape_string(strip_tags($barrister))
));
$res = #mysql_query($query);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
/******************************
MANAGE REQUESTS
/******************************/
if(!$_POST['action']){
//We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php
header ("Location: index.html");
}
else{
$link = connect(HOST, USER, PASSWORD);
switch($_POST['action']){
case "update":
$res = getContent($link, 100);
while($row = mysql_fetch_array($res)){
$result .= "<li><strong>".$row['user']."</strong><img src=\"http://eslangel.com/wp-content/plugins/myplugin/CSS/images/bullet.gif\" alt=\"-\" />".$row['message']." </li>";
}
echo $result;
break;
case "insert":
echo insertMessage($_POST['barrister']);
break;
}
mysql_close($link);
}
?>
The html where the data is returned to when retrieved from the database
<div id="container">
<ul class="menu">
<li></li>
</ul>
<span class="clear"></span>
<div class="content">
<div id="loading"><img src="http:///></div>
<ul>
<ul>
</div>
</div>
The first error I notice is that all of your radio buttons have the same ID. An ID attribute should be unique on the page. Besides this, the best tool for debugging javascript is the console.
Javascript Debugging for beginners
EDIT
Here's an example of an ajax form submit using your markup http://jsfiddle.net/UADu5/
$(function(){
// Submit form via ajax
$('#check').click(function(){
var barrister = null
$.each($("input[name='barrister']:checked"), function(){
if($(this).val() == 1)
barrister = $(this).attr('value');
});
if(barrister){
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php",
data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
} else {
alert('Please fill all fields!')
}
})
})
<form method="post" id="form">
<fieldset>
<legend>Grade Exams</legend>
<ul>
<li>
<p>Barrister's Exam</p>
<label>
<input type="radio" name="barrister" value="1" /> Pass
</label>
<label>
<input type="radio" name="barrister" value="0" /> Fail
</label>
</li>
<li class="submit">
<input type="button" id="check" value="Test">
</li>
</ul>
</fieldset>
</form>
I strongly recommend using Firebug, as it will show you all the requests being made and all the request/response header info so you can see if and where the AJAX is going wrong. It's also great for debugging HTML/CSS stuff!
Firebug practically changed my life when it comes to JavaScript and CSS.
I think you have error in insert statement:
//remove extra bracket and semicolon
sprintf("INSERT INTO results(barrister) VALUES('%s')", mysql_real_escape_string(strip_tags($barrister))
);
Hope it helps
Change
var barrister = $('input:radio[name=barrister]:checked').val();
to
barrister = $('input:radio[name=barrister]:checked');
should help.

Insert into MySQL database with jQuery and PHP

I'm experiencing some kind of a problem here, I have no idea what's wrong with this code. I'm pretty sure it's client sided since I am not getting any PHP errors, but I may be wrong.
I'm trying to get a form, once submitted, to insert the information contained in a text field into a MySQL database via an AJAX request to a PHP file.
Here's where I'm at:
/* index.php */
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="scripts/ajax.js"></script>
//...
<div class="success" id="success"></div>
<div class="err" id="err"></div>
<!--Create Form-->
<form action="" method="post" name="create" id="createForm" onsubmit="createNew(document.create.create2.value); return false;">
<h5>Create New File</h5>
<p><input name="create2" type="text" maxlength="32" /></p>
<input type="submit" name="submit" value="Create" />
</form>
/* ajax.js */
function createNew(name)
{
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "../utilities/process.php",
data: 'name='+name,
datatype: "html",
success: function(msg){
if(parseInt(msg)!=5)
{
$('#success').html('Successfully added ' + name + ' into database.');
$('#loading').css('visibility','hidden');
alert('success');//testing purposes
}
else
{
$('#err').html('Failed to add ' + name + ' into database.');
$('#loading').css('visibility','hidden');
alert('fail');//testing purposes
}
}
})
}
/* process.php */
<?
include('db_connect.php');
if($_POST['name'])
{
$name = $_POST['name'];
$name = mysql_escape_string($name);
$query = "INSERT INTO tz_navbar (name) VALUES (".$name.")";
$result = mysql_query("$query") or die ("5");
}
?>
Here's my problem:
After I submit my form with something, it reports that is succeeds but nothing gets added to my database.
Thank you all in advance for taking your time to help me.
Looking at your query, I suspect you need it to be:
$query = "INSERT INTO tz_navbar (name) VALUES ('".$name."')";
If that doesn't fix it, you need to log the value of $_REQUEST
error_log(print_r($_REQUEST,true));
to ensure that you are getting the right values on the server side.
You have $_POST['name'] , but in your form you have, input type = text name = "create"
Which should be $_POST['create'] . That is why your $_POST['name'] does not have any value when it's passed.
Check your query.
$query = "INSERT INTO tz_navbar (name) VALUES ('$name');
Also, you could try testing process.php without javascript. Just so you could see the mysql error message. Use die() or something.

Categories