submitting form from jquery to php - php

I'm going crazy! I'm trying to submit a form from jquery to php and insert a record in my database. I'm getting no error, but no record is being submitted. All works fine when I just go to the php page and put variables in the URL. But it doesn't work when I submit the variables via the jquery page. Can anyone help me out, please?
HTML:
<form id="tellusForm" >
<div class="formHead">Tell us your story</div>
<div id="thank">Thank you.</div>
<table cellpadding="5">
<tr><td>Name:</td><td><input id="tellName" type="text"/></td></tr>
<tr><td>Country of origin:</td><td><select id="tellCountry"></select></td></tr>
<tr><td>Age:</td><td><input type="text" id="tellAge"/></td></tr>
<tr><td>Occupation:</td><td><input type="text" id="tellOccupation"/></td></tr>
<tr><td>Email address:</td><td><input type="text" id="tellEmail"/></td></tr>
<tr><td>Phone number:</td><td><input type="text" id="tellPhone"/></td></tr>
<tr><td>A bit about you:</td><td><textarea id="tellAbout" style="width: 100%;"></textarea></td></tr>
<tr><td></td><td><input type="submit" value="Send" class="submit"/></td></tr>
</table>
</form>
jquery:
$('.submit').click(function(){
$.get('tellus.php', { name: "laura"}, function(data){
eval(data);
});
});
tellus.php:
<?php
require_once ('../constants_test.php');
$name = $_GET['name'];
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
$q = "Insert into tellus(`Name`) values ('" . $name . "')";
if ($db->query($q)) {
echo "console.log('you got it')";
};
$db->close();
?>

Thanks everyone who tried to help me! I ended up having to do it this way:
$.post("./tellus.php", {tellName:name}, function(data){
alert(data)
});
The ajax call must have had something that wasn't working.

Use serialize():
$("#tellusForm").on("submit", function() {
event.preventDefault();
$.ajax({
url: 'tellus.php',
data: $(this).serialize()
}).done(function(data) {
$(html).append(data);
});
});
Also make sure to have names on your form elements:
<input type="text" name="tellAge" id="tellAge" />
This topic is very common here so try searching for other posts - e.g. Submit form using AJAX and jQuery could work too.

The ajax call wasn't working because you are using $.serialize to serialize your form objects, which will return ;
{key:'tellName', value='name'} // <input name="tellName" value="name" />
whereas you are expecting a key:value pair. In order to get the data to send what you expecting, you should modify the object using this jQuery function:
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
}
And call it whenever you're submitting form. It will structure your form to have the key:value pair.
<form id="register">
<input type="text name="username" />
<input type="text" name="email" />
<input type="submit value="Register!" />
</form>
and the javascript (remember to include the serializeObject function)
$('#register').on('submit', function(){
var data = $(this).serializeObject()
// data will return {username: value, email:value}
$.post('process.php', data, function(response){
try{
var r = JSON.parse(response) // Check if the response is an object
console.log(JSON.stringify(r))
}
catch(e){
console.log(response) // The response is a string
}
})
})
Cheers!

I suggest you should use POST for actions which include insert/delete/update of data in database. It keeps the data safe.
If you want to still use GET and test out something. I suggest do not use jquery in the middle to handle the get. Submit button on click submits the form anyway, so the jquery $.get is unnecessary.
To your form element add
<form name='' action='tellus.php'>...</form>
This should fix the problem.

How about this one
jquery
$("#submit").click(function() {
formData = {
name: "abc"
}
$.ajax({
type: 'GET',
contentType: 'application/json',
url: "http://yourpage/tellus.php",
dataType: "json",
data: formData,
success: function(data) {
console.log(data.message);
},
error: function(data) {
console.log(data.message);
}
});
});
php
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_GET['name'])) {
$name = $_GET['name'];
// include db connect class
require_once ('../constants_test.php');
// connecting to db
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
// mysqli inserting a new row
$q = "INSERT INTO tellus('Name') values ('" . $name . "')";
// check if row inserted or not
if ($db->query($q)) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "you got it";
// echoing JSON response
echo json_encode($response);
$db->close();
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
$db->close();
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Related

jQuery validation submitHandler not working in $.ajax post form data

I am using the jquery validate plugin to send data from form to mysql database. the validation works well but after the button is clicked, the data isnt submitted to the database. but no response or error is generated. i think the error is in ajax part.
The below file is db_connect.php, it executes .both echo are working
<?php
echo "hello";
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "upscfpyl_test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
echo "hi";
//exit();
}
else{
echo "hi2";
}
?>
index.html - some code given below the div error is displayed but the content in it is hi2. I dont know why it has the content hi2. I had used echo "hi2"; in db_connect.php [code given at the end] but did not return it to ajax.
<div id="error"></div>
<form id="signupForm" method="post" action="#">
<input type="submit" class="btn btn-primary" value="Sign Up" id="button1" name="btn-save">
</form>
Ajax part :
$.ajax({
type: 'POST',
dataType: 'text',
url: 'js/php/register.php',
data: {
name1: name,
email1: email,
mobile1: mobile,
gender1: gender,
password1: passwords
},
beforeSend: function() {
$("#error").fadeOut();
document.getElementById("button1").disabled = true; // this works
},
success : function(response) {
if(response==1)
{
$("#error").fadeIn(1000, function()
{
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
document.getElementById("button1").disabled = false;
});
}
else if(response=="registered")
{
window.location = "dashboard.html";
}
else {
$("#error").fadeIn(1000, function()
{
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
document.getElementById("button1").disabled = false;
});
}
}
});
register.php - to submit to database
<?php
include_once("db_connect.php");
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name=test_input($_POST['name1']); // Fetching Values from URL.
$email=test_input($_POST['email1']);
$gender=test_input($_POST['gender1']);
$mobile=test_input($_POST['mobile1']);
$password= test_input(sha1($_POST['password1'])); // Password Encryption, If you like you can also leave sha1.
echo "pranav"; // these dont work
echo $name+$email+$gender; // this also doesnt work
// Check if e-mail address syntax is valid or not
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo $email;
}
else{
$result = mysql_query("SELECT * FROM users WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
$query = mysql_query("insert into users(name, email, password, gender, mobile) values ('$name', '$email', '$password', '$gender', '$mobile')"); // Insert query
if($query){
echo "registered";
}
else
{
echo "Error....!!";
}
}
else
{
echo "1";
}
}
}
?>
You can open your browser console for checking logs.
if the dataType is JSON, it means that your server is returning a json. But this is not the case see https://api.jquery.com/jQuery.ajax/
Try this code for your data serialization:
$("#your_form_id").submit(function(e){
e.preventDefault();
var datas = $(this).serialize();
$.ajax({
data: datas,
// Or this
data: 'key1=' + value1 + '&key2=' + value2 + '&key3=' + value3,
// to match your server response
dataType: "text"
// Error warning
.fail(function() {
alert( "error" );
})
});
});
With the validation code of the form, we could better help you

Anyone know why I'm getting an undefined index error with PHP?

So, I'm new to using PHP but want to add whatever a user enters into this form into a database.
However, I'm getting an error for each index of name, role, and wage. It seems that it isn't picking that up.
HTML:
<form id="input" name="input" action="employees.php" method="post">
<div id="boxes">
<input type="text" name="name" placeholder="Input" class="name" required><br/>
<input type="text" name="role" placeholder="Role" class="role" required><br/>
<input type="number" step="any" name="wage" placeholder="Wage" class="wage" required>
<br />
<br />
</div>
<button type="submit" onsubmit="return ajaxFunction()" class="button">Submit</button>
<button type="reset" class="button">Reset</button>
</form>
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employees";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br/>";
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
if (mysql_query("INSERT INTO employees VALUES ('$name2', '$role2', '$wage2')"))
echo "Successfully inserted";
else
echo "Insertion failed";
$conn->close();
?>
I also have some javascript set up to catch the values of each field and to send them to the PHP file. I'm probably doing something very wrong... but anyway here's the JS:
function ajaxFunction() {
var name = $('.name').val();
var role = $('.role').val();
var wage = $('.wage').val();
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
$.post('employees.php', {name1:name, role1:role, wage1:wage}, function(data){
$('#main').html(data);
});
if (name == '' || role == '' || wage == '') {
alert("Please fill in all fields.");
} else {
$.ajax({
type: "POST",
url: "employees.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
In your Ajax dataString is
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
But in your PHP
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
Should be
$name2 = $_POST['name1'];
$role2 = $_POST['role1'];
$wage2 = $_POST['wage1'];
The undefined error means that your data is not found, this is happening because your php is looking for a POST index of "name" whereas javascript is sending "name1".
There are a few issues with the setup that can be greatly improved here.
Firstly the onsubmit needs moved into the form tag.
<form onsubmit="return isFormValid()" id="input" name="input" action="employees.php" method="post">
Secondly you don't actually need to actually make an ajax request from Javascript because the return on submit is saying if the returned value of the js function is true submit the form otherwise don't. Therefore we just need to return a true or false based on form validation.
Here is the updated JS function.
function isFormValid(){
var name = $('.name').val(),
role = $('.role').val(),
wage = $('.wage').val(),
data = [name, role, wage],
isValid = true;
data.forEach(function(el){
if( isValid && !el.trim() ){
alert("Please fill in all fields.");
isValid = false;
}
});
return isValid;
}
There are also some security concerns regarding MySQL injection from how the form data is being entered into the database without being escaped.
A quick solution is to add a basic PHP method to escape the strings before hitting the database.
// add at the top of your php file
function escape($value){
return mysql_real_escape_string($value);
}
// then update your variables
$name2 = escape($_POST['name']);
$role2 = escape($_POST['role']);
$wage2 = escape($_POST['wage']);
You can read more about mysql injection and how to prevent it here:
http://php.net/manual/en/function.mysql-real-escape-string.php
EDIT ---------------------------
I've simplified the JS and removed the token issue you were having. If you add more input fields you can simply add a new variable to store it's value and add that variable name to the data array.
I've also updated the function name in both the JS and the html as it relates more to the purpose of the task.
Here is a working example:
http://codepen.io/davidbattersby/pen/LVabQe
obviously the php file doesn't exist so will point to a blank page if submission passes validation, it will alert and not send if invalid.

HTML Button not Submitting Every Time

Everything works perfectly except the submit button typically takes three to four times before it works. So I'll have the necessary cid number, plug it into the form, and hit submit. It might work the first time, but it also might take me seven attempts. I've got a bit of a deadline on this thing, and I have no idea how to even go about troubleshooting this so any help at all would be hugely appreciated!
So I've got this form:
<form action="" onsubmit="redirect()">
<input type="text" name="val1" id="val1" placeholder="CID (ten digits)">
<br>
<input type="submit" value="Submit" id="submit">
</form>
Which triggers this javascript function:
function redirect() {
var userID = document.getElementById("val1").value;
var userID = userID.replace(/-/g, "");
//alert(userID);
//var userID = "9183179265";
$.ajax({
type: "POST",
url: './getNetworkType.php',
data: "userID=" + userID,
success: function(data) {
//alert(data);
if(data.indexOf("Search") > -1) {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_search.php?cid=" + data.substr(data.length - 10);
}
else {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_report.php?cid=" + data.substr(data.length - 10);
}
}
});
}
Which executes this script:
<?php
$val1 = $_POST['userID'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql3 = "SELECT * FROM account_type WHERE cid ='" . $val1 . "'";
$result3 = $mysqli->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
echo $row3["network"];
}
}
?>
I think the problem is in your function onsubmit.
You should try something like this.
Set ID to form to example "myForm". Remove onsubmit from Form.
And add this code. This should send data successfull and avoid the submit that you don't won't.
$("#myForm").submit(function() {
redirect();
return false; // this avoid submit.
});

Autocomplete show an undefined list

I've been working with jQuery UI Autocomplete to make an suggestion from database and autocomplete the rest of field.
Here is my code.
HTML :
<form action="#" method="post">
<p><label for="kdbr">KDBR</label><br />
<input type="text" name="kdbr" id="kdbr" value="" /></p>
<p><label for="nmbr">NMBR</label><br />
<input type="text" name="nmbr" id="nmbr" value="" /></p>
</form>
Javascript :
$(function() {
//clear values on refresh
$('#nmbr').val("");
$("#kdbr").autocomplete({
source: "<?php echo base_url();?>js/coba3.php",
minLength: 3,
select: function(event, ui) {
$('#nmbr').val(ui.item.nmbr);
}
});
});
PHP :
<?php
$dbhost = 'HOST';
$dbuser = 'USERNAME';
$dbpass = 'PASSWORD';
$dbname = 'TBNAME';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
$return_arr = array();
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("SELECT * FROM tb_master_barang where kdbr like '%" .mysql_real_escape_string($_GET['term']) . "%'");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['kdbr'] = htmlentities(stripslashes($row['kdbr']));
$row_array['nmbr'] = $row['nmbr'];
array_push($return_arr,$row_array);
}
}
mysql_close($conn);
echo json_encode($return_arr);
?>
The dropdown list show a list of undefined instead value from kdbr . I have run the php separately and it returns this value :
[{"kdbr":"950.00.0002","nmbr":"PAKAIAN DINAS KS"},{"kdbr":"950.01.0000","nmbr":"BARANG SCURITY LSNG.PAKAI"},{"kdbr":"950.01.0001","nmbr":"PECI"},{"kdbr":"950.01.0002","nmbr":"KOPEL REM HITAM"},{"kdbr":"950.01.0003","nmbr":"SEPATU PDH"},{"kdbr":"950.01.0005","nmbr":"ROMPI SATPAM"},{"kdbr":"950.01.0006","nmbr":"SEPATU PDL"},{"kdbr":"950.01.0007","nmbr":"TALI KOOR & PLUIT"},{"kdbr":"950.01.0008","nmbr":"PAKAIAN TAHAN API"},{"kdbr":"950.01.0009","nmbr":"HELM TAHAN API"},{"kdbr":"950.02.0001","nmbr":"KAOS SCURITI PNJG\/BED\/LOG DLL"}]
can someone tell me where i doing wrong?
Your source field is used in a wrong manner. You need to pass array with data or a anonymous function which will load the data. See the documentation
Something like this should work:
$("#kdbr").autocomplete({
source: function (request, {
var ajax_url = "<?php echo base_url();?>js/coba3.php?term=" + request.term;
$.ajax({
url: ajax_url,
success: function (response) {
// assuming valid json
var data = $.parseJSON(response);
response($.map(data, function (obj) {
return {
label: obj.name + ': ' + obj.description,
value: obj.name,
id: obj.name
};
}));
}
});
},
minLength: 3,
select: function (event, ui) {
$('#nmbr').val(ui.item.nmbr);
}
});
try this,
select: function(event, ui) {
jQuery.get(ui.item.nmbr);
}

Authenicating user using jQuery AJAX not working

I'm trying to authenticate a user using AJAX wrapped with jQuery to call a PHP script that queries a MySQL database. I'm NOT familiar with any of those technologies but I (sorta) managed to get them working individually, but I can't get the jQuery, AJAX and HTML to work properly.
[Edit:] I followed Trinh Hoang Nhu's advice and added a return false; statement to disable the Submit button. All previous errors fixed, I can't get the object returned by the AJAX right.
HTML
Here's the HTML snippet I use:
<form id="form" method='post'>
<label>Username:</label>
<input id="user" name="user" type="text" maxlength="30" required /> <br />
<label>Password:</label>
<input id="pass" name="pass" type="password" maxlength="30" required /> <br />
<input id="url" name="url" type="text" value="<?php echo $_GET['url'] ?>" hidden />
<input name="submit" type="submit" value="I'm done">
</form>
jQuery/AJAX
Here's my jquery code for using AJAX to authenticate a user (sorry if the indenting is messed up because of the tabs):
function changeMessage(message) {
document.getElementById("message").innerHTML = message; }
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass: $("#pass").val(), url: $("#url") },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val(""); }
//if authenticated
else {
changeMessage("Authenticated");
window.location.href = result; }
} );
//to disable the submit button
return false;
} );
} )
PHP
And here's my PHP script that gets called:
<?php
ob_start();
session_start();
$user = $_POST['user'];
$pass = md5($_POST['pass']);
mysql_connect('localhost', 'root', '');
mysql_select_db('stufftothink');
$query = "select * from users where user = '$user' and pass = '$pass'";
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_array($result)) {
$i = 1; }
if ($i == 1) {
$_SESSION['user'] = $user;
$invalid_urls = array('register.php', 'login.php');
$url = $_REQUEST['url']; //not sure whether _GET or _POST
if (in_array($url, $invalid_urls)) {
echo '/stufftothink/profile.php'; }
else {
echo '/stufftothink/'.$url; }
}
else {
echo 'false'; }
mysql_close();
?>
Edit
I've been getting a lot of downvotes on this question. I had accidentally submitted the question without the explanation filled in. I went back to edit it, but when I came back, there were already 4 downvotes. It had barely been a couple of minutes. Am I doing something wrong, or were the first 5 minutes the problem?
First if you want to submit form using ajax, you must return false from your submit function. Otherwise your browser will handle it and redirect you to another page.
If you want to return an object from PHP, you must convert it to json using json_encode,
for example:
//PHP
$return = array("url" => "http://www.google.com");
echo json_encode($return);
//would echo something like {"url":"http://www.google.com"}
//JS
$.post(url, data, function(data){
alert(data.url);
});
You have no ending ;'s on functions.
Should be:
function changeMessage(message) {
document.getElementById("message").innerHTML = message;
};
$(document).ready(function() {
$("#form").submit(function() {
changeMessage("Checking");
//check the username exists or not from ajax
$.post("/stufftothink/php/AJAX/login.php",
{user: $("#user").val(), pass:$("#pass").val() },
function(result) {
//if failed
if (result === 'false') {
changeMessage("Invalid username or password. Check for typos and try again");
$("#pass").val("");
}
//if authenticated
else {
changeMessage("Authenticatred");
window.location.href = "/stufftothink/" + result;
}
});
});
});
Not sure if that'll fix it, but it's the only thing that jumps out at me.

Categories