Insert into MySQL database with jQuery and PHP - 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.

Related

how to insert data to mysql database with Jquery ajax and php?

I am trying to learn Ajax. I am inserting some data to mysql database from a Html Form by php. It works nicely. But my ajax part does not work. I get the success message but data dont go to my php file. My html and js code:
<!DOCTYPE html>
<html>
<head>
<title>Insertion of data with Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
</head>
<body>
<form id="myForm" method="POST" action="ajax-save.php">
Title: <input type="text" name="title" id="title"><br /><br />
Description: <textarea name="description" id="description" rows="20" cols="40"></textarea><br /><br />
Url: <input type="text" name="url" id="url"><br /><br />
<input type="submit" id="submit" name="submit" value="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
url: 'ajax-save.php',
async: true,
cache: false,
data: $('#myForm').serialize() ,
type: 'POST',
success: function(){
alert("success");
clearForm();
}
});
return false;
});
});
</script>
</body>
</html>
My php codes are working properly. I have tested it without ajax. Here is my php code.
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('hospital');
if (isset($_POST['title'])) { $title = $_POST['title'];}
if (isset($_POST['description'])) { $description = $_POST['description'];}
if (isset($_POST['url'])) { $url = $_POST['url'];}
if(isset($_POST['submit'])){
if(mysql_query("insert into `wp_upload_video` (`id`, `title`, `description`, `url`) values (NULL, '$title', '$description', '$url')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
}
Please let me know where is my fault.
When you submit via ajax on a click of the submit button.... that condition is always true.
Checking if $_POST['submit'] is set in the PHP will always result in true because if it is not true the ajax never gets processed.
So... remove the if submit condition in the PHP and handle error notification in the ajax call.
Also, as pointed out by #NiettheDarkAbsol in comments, it's a good idea to add e.preventDefault() to the jquery as well to stop the submit button submitting the form as it normally would and allow the jquery to handle the submit (via ajax).

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.

Insert PHP PDO via AJAX

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();
}

Post result from a query via php in same page with Ajax

I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.

Fade in not working correctly

<script type="text/javascript">
$(document).ready(function($){
$.supersized({
//Background image
slides : [ { image : 'images/pendulumWeb.jpg' } ]
});
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var email = $('#email').attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: "email="+ email,
success: function(){
$('form#submit').hide(function() {
$('div.success').fadeIn();
});
}
});
return false;
});
});
</script>
<div id="contact">
<form id="submit" method="post">
<legend>Enter InformationEnter InformationEnter InformationEnter InformationEnter InformationEnter InformationEnter InformationEnter Information</legend>
<div id="submit">
<input id="email" name="email" value="Email Address" size="20" type="text" />
<button class="buttonPositive" type="submit">Submit</button>
</div>
</form>
<div class="success" style="display: none;">We will email you shortly.</div>
</div>
I am having a hard time figuring out why when I click my submit button why my text after my success (fadeIn) won't appear below the submit button. I am doing a console log of test but it stops going to the console right below $('form#submit').hide(function()..Maybe I am missing something simple here? Problem fixed! Thanks Adam
One more thing! My data is not getting to my db..here is my code..I am getting a primary id of 0 but no data.
// This is config.php //
$sql = mysql_connect("localhost","root","");
if (!$sql)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $sql);
//
include('config.php');
// CLIENT INFORMATION
$email = htmlspecialchars(trim($_POST['email']));
$addClient = "INSERT INTO clientEmails (Email) VALUES ('$email')";
mysql_query($addClient) or die(mysql_error());
Try removing the callback function to hide():
$('form#submit').hide();
$('div.success').fadeIn();
Also, you have a form and a div with the same id. I suggest you should change one of them, because that might be what was causing your success message not to show.
Ad#m
The hide() function in jQuery takes a function as the second argument. The first argument is the duration of the animation of hiding the element. If you just want to hide the submit button without animation, you don't need to use the callback, just call hide() and then fadeIn() your new element. If you do want an animation, specify the duration as the first argument.
The first argument of hide is a duration, second argument is the callback:
$('form#submit').hide(0, function() {
$('div.success').fadeIn();
});

Categories