AJAX to database sending null to PHP script - php

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.

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).

Can't add content to mysql via jquery ajax

Hi there am a beginner in php and ajax, was trying to create a simple admin page which only submit a message and the message get stored in a mysql database. (via ajax ) however it seems that the no data is being parse through when I hit the submit button(I coded it so that when the submit button is pressed, the message would be send without the page refreshing).
Could someone check to see where my error could be? thank you
admin.php
<!DOCTYPE html>
<html>
<head> <!--inseart script here -->
<script type= "text/javascript" src="js/jquery.js"></script>
</head>
<body>
Message: <input type="text" name="message" id= "message_form"><br>
<input type="submit" id= "submit_form" onclick = "submit_msg()">
<script type= "text/javascript" src="js/func_submit_msg.js"> </script>
</body>
</html>
I have created a separate function file called func_submit_msg.js
//this is a function file to submit message to database
$(document).ready(function submit_msg(){
alert('worked');
$.ajax({
type: "POST",
url: "submit_data.php"
data: { message: message_form},
})
}
a connect.php file is created to connect to mysql database
<?php
$host = "localhost";
$user = "root";
$pass = ""; // phpMyAdmin mysql password is blank ? i believe
$database_name = "test"; //
$table_name = "test_table_1"; //table that will be accessing
//connect to mysql database
$db = new mysqli($host, $user, $pass, $database_name);
//check connection?
if ($db -> connect_error) {
die("error mysql database not connected: " . $db -> connect_error);
}
else {
echo "connected successfully" ;
}
?>
a submit_data.php file is created to submit to database
<?php
include "connect.php";
$insert_data=$db-> query ("INSERT INTO test_table_1(message) VALUES ('$message_form')");
if ($db->query($insert_data === TRUE) ){
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
error checking code to check whether database was inserted correctly doesn't even echo out whether it is successful or not.
Updated
submit_data.php as per # Maximus2012 suggestion
<?php
include "connect.php";
$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ($_POST['message_form'])");
if ($insert_data === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
No error display but there isn't any data being recorded in the database still.
You should start by adding your success callback to your Ajax: (if you havent already)
$(document).ready(function(){
$('#submit_form').on('click', function(e){
e.preventDefault();
message_form = $('#message_form').val();
$.ajax({
type: "POST",
url: "submit_data.php",
data: {message: message_form},
success: function(data) {
$('#result').html(data);
},
error:function(err){
//handle your error
alert('did not work');
}
});
});
});
Here we use .on() as the preferred method of attaching an
event handler function
We then use .val() to get the value of the message input field
and store it in a variable to be used for POSTing to the submit_data.php script
e.preventDefault() is used so that the default event is cancelled
when click the submit button
In your html, add an element that the result can be returned to: (#result)
<html>
<head>
<script type= "text/javascript" src="js/jquery.js"></script>
<script type= "text/javascript" src="js/func_submit_msg.js"></script>
</head>
<body>
<form action="" method="POST">
Message: <input type="text" name="message" id="message_form"><br>
<input type="submit" id="submit_form">
</form>
<div id="result"></div>
</body>
</html>
Here we wrap your input in a form with the method and action
properties to ensure that the name attributes are able to be used in
POST requests
In your PHP (submit_data.php) you need to assign a value to $message_form before using it:
<?php
include "connect.php";
$message_form = $_POST['message'];
$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ('$message_form')");
if ($insert_data === TRUE ){
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
If all goes well, you should get some kind of result from this.

Hiding a form upon click of the submission button

<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/

AJAX - Sending data to my php file does not seem to work [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
I'm still new to JQuery, AJAX and PHP.
I was wondering what I could be doing wrong here. I am taking in information about a customer and trying to return a confirmation message on the same page.
So the problems I am having:
1) Clicking on the submit button refreshes my page? Why?
2) I have a underneath my submit button. How would I be able to change the text of that with the results of addCustomer.php?
3) Is it okay to have my javascript and php code in the same file under customer.php?
Edit: Also I am using Firefox's Tamper Data Addon - when I click submit, no data is sent for some reason.
Customer.php
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'addCustomer.php',
dataType : 'json',
data:{
add_LN : $('#add_LN').val(),
add_FN : $('#add_FN').val(),
add_PN : $('#add_PN').val(),
add_DOB : $('#add_DOB').val()
},
success : function(data){
//I want to change the "confirmMsg" to the string given back from addCustomer.php
}
}
}
}
</script>
<p> </p>
<p>Add New Customer:</p>
<div align="center">
<form>
<table width="396" border="1">
<tr>
<td width="133"><p>Last Name:</p>
<p>First Name:</p>
<p>Phone Number:</p>
<p>Date of Birth:</p></td>
<td width="144"><p>
<input type="text" name="add_LN" id="add_LN" />
</p>
<p>
<input type="text" name="add_FN" id="add_FN" />
</p>
<p>
<input type="text" name="add_PN" id="add_PN" />
</p>
<p>
<input type="text" name="add_DOB" id="add_DOB" />
</p> </td>
<td width="97"><input type="submit" name="submit" id="submit" value="Add Customer" /></td>
<div id="confirmMsg"/>
</tr>
</table>
</form>
</div>
<p> </p>
</div>
</div>
addCustomer.php
<?php
$username="******";
$password="******";
$database="******";
if (isset ($_POST['add_LN']))
$lastName=$_POST['add_LN'];
else
die("Last Name not passed in POST");
if (isset ($_POST['add_FN']))
$firstName=$_POST['add_FN'];
else
die ("First Name not passed in POST");
if (isset ( $_POST['add_PN']))
$phone=$_POST['add_PN'];
else
die("Phone Number not passed in POST");
if (isset ($_POST['add_DOB']))
$dob=$_POST['add_DOB'];
else
die("Date of Birth not passed in Post");
//$membership==$_POST['membership'];
mysql_connect("dbs4.cpsc.u.ca",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO customer (last_name, first_name, phone_no, date_of_birth, membership) VALUES ('$lastName', '$firstName', '$phone', '$dob', 'T')";
if (mysql_query($query)){
echo "Thanks";
} else
{
echo "Failed to insert customer into database";
}
mysql_close();
?>
Thanks so much for the help!
Ok, to answer your questions in order:
You should be able to check from Firebug (you are using Firebug, right?) in the Console tab to see that addCustomer.php is the endpoint being called by your Ajax request. Failing that, you can add the following code into your scripts:
$('#confirmMsg').ajaxComplete(function(e, xhr, settings) {
$(this).text('The response from your page is ' + xhr.responseHTML);
});
I'm assuming that your question here is "I have a div underneath my submit button...". Try the following command (which is a shortened version of the full Ajax method):
$.post('addCustomer.php', {
add_LN : $('#add_LN').val(),
add_FN : $('#add_FN').val(),
add_PN : $('#add_PN').val(),
add_DOB : $('#add_DOB').val()
}, function(data){
$('#confirmMsg').text(data);
});
Finally, yes - it is ok to have your script and PHP code on the same page. The PHP code is executed on the server before being rendered to your browser and the JavaScript works on the client side, executing once the page is delivered.
1) you can use the "preventDefault" on the click function.
2) you can add a success message by just displaying the "confirmMsg" div (hide it first with css)
3) if thats works for you it's oke. but i self try to keep all the code just on one place eg. "main.js"
See the code: ^my changes^ "just remove the ^ to make it work :)"
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(^e^) {
^e.preventDefault();^
$.ajax({
type : 'POST',
url : 'addCustomer.php',
^data: $('form').serializeArray(),^
success : function(data){
^$('#confirmMsg').show();^
}
}
}
}
</script>
I think this should do the trick :)
I've added the serializeArray function to make it more dynamic because if you have more input fields you don't have to change the js code again. http://api.jquery.com/serializeArray/
You can see what the form sends to first open firebug and reload the page then field the fields then submit it. You will see in the "console" tab some change ;)
I hope this will help you out.
I suggest you change dataType: 'json' to dataType: 'text', that might be what's tripping jQuery up.
And change your success handler to
success: function(data){
$("#confirmMsg").html(data);
}
Problem was the was not in the head of that file. It fixed all my problems but not sure why. Thanks to everyone who contributed
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(e) {
$.ajax({
type : 'POST',
url : 'addCustomer.php',
dataType : 'json',
data:{
lastName : $('#add_LN').val(),
firstName : $('#add_FN').val(),
phone : $('#add_PN').val(),
dob : $('#add_DOB').val()
},
success : function(data){
if (data.error === true){
alert("there was an error in the post layer");
} else {
$('#confirmMsg').html(data);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
return false;
});
});
</script>

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