PHP and jQuery insert into MySQL - javascript

I am trying to insert data into mySQL using jQuery. The code does not return any error and no any result as well. Please help me to sort this out.
$(document).ready(function() {
$("#submit").click(function() {
var data;
var eid = 101;
data = "eid=" + eid;
for (i = 0; i <= 10; i++) {
data += "&Text_" + (i + 1) + "=" + $("#Text_" + (i + 1)).val();
data += "&Amount_" + (i + 1) + "=" + $("#Amount_" + (i + 1)).val();
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="Amount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="Amount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="Amount[]" id="Amount_3" /></td>
</tr>
I am adding the process.php snippet also in order to know where is the error.
process.php
$eid=$_POST['eid'];
$length = sizeof($_POST["Text"]);
$i=1;
while ($i<=$length){
if(!empty($_POST['Text'][$i])) {
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$msg = array('status' => !$error, 'msg' => 'Failed! updation-1');
if(!$error) {
$sql = "UPDATE TblCustom SET Text='" . $Text . "', Amount='" . $Amount ."' WHERE ID='$eid'";
$status = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$msg = array('error' => $error, 'msg' => 'Success! updation : '. $sql );
}
else {
$msg = array('error' => $error, 'msg' => 'Failed! updation-2 ');
}
}
echo json_encode($msg);
}
Thanks

You have 3 problems.
Problem number one and two are related. Firstly, you are specifying dataType: 'json', but you are passing your data in application/x-www-form-urlencoded format. Secondly, your php script expects data to be in the following format:
$_POST = [
'Text' => ['text_1', 'text_2', 'text_3'],
'Amount' => ['amount_1', 'amount_2', 'amount_3']
];
While your data looks something like this:
$_POST = [
'Text_1' => 'text_1',
'Text_2' => 'text_2'
// and so on
];
The single fix to this problem is as follows:
$(document).ready(function() {
$("#submit").click(function() {
const data = {
// we are grabbing all inputs with name=Text[]
// and mapping them to array containing their values.
// The `...` is a spread operator introduced
// with the new js standard (ES6),
// that converts jQuery object to regular javascript
// array of inputs.
// you can do all of this with a for loop, but the map way
// is prefered
Text: [...$('input[name="Text[]"]')].map(input => input.value),
Amount: [...$('input[name="Amount[]"]')].map(input => input.value)
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
The third problem is that have created an SQL Injection vulnerability. That means some bad guy can inject and SQL statement into Text variable, which then you are putting directly into your sql update, thus he can do whatever he wants (for example drop all database).
More on SQL Injection
The solution is simple: use PDO and bindValue method.
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$conn = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
// 500 means internal server error
// that's handy information for the client-side
http_send_status(500);
echo json_encode([
'error' => [
'message' => 'Unable to connect to database'
]
]);
exit;
}
$eid = $_POST['eid'];
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$sql = "UPDATE TblCustom SET Text = :text, Amount = :amount WHERE ID = :id";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':text', $Text);
$stmt->bindValue(':amount', $Amount);
$stmt->bindValue(':id', $eid);
if (!$stmt->execute()) {
// 400 means something went wrong when updating
// also a handy information for the client-side
http_send_status(400);
echo json_encode([
'error' => [
'message' => 'Unable to update'
]
]);
exit;
}
// 204 measn everything went okay, and we don't return anything
http_send_status(204);
exit;
Hint: if you are sending correct status codes the jQuery lets you handle errors like this:
$.ajax({
// ...
success: function(response) {
// this code will be executed
// only when status code == 2xx
},
error: function(response) {
// this code will be executed
// only when status code == 4xx | 5xx (if I remember correctly)
},
always: function(response) {
// this code will be executed no matter what
// as the name implies
},
});
So there is no need for additional if statements.

index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="form_signup" name="form_signup">
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="SAmount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="SAmount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="SAmount[]" id="Amount_3" /></td>
</tr>
<input type="submit" name="signup" value="Sign Up!"/>
</form>
<script>
$(document).ready(function() {
$("#form_signup").click(function() {
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: $(this).serialize(),
success: function(response) {
alert(response);
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
</script>
</body>
</html>
process.php
<?php
print_r($_POST);
?>

Related

Not getting input text value into php page

on save i am not getting input text value into the .php page. I am getting only file data but not getting post data.
Anyone have any idea, then let me know how eact do mistake from my side
View file as below:
$str .='<form name="ipsf_sukanya_form" id="ipsf_sukanya_form"><input type="hidden" name="login_access" id="login_access" value="'.$login_access.'">
<input type="hidden" name="emp_id" id="emp_id" value="'.$emp_id.'">
<input type="hidden" name="ipsf_main_id" id="ipsf_main_id" value="'.$main_id.'">
<input type="hidden" name="action" id="action" value="'.$action.'">
<input type="hidden" name="date_of_joining" id="date_of_joining" value="'.$date_of_joining.'">';
else if($action=='add'){
// for ($j = 0; $j <= $_POST['pro_ext_loc_count2_nsc']; $j++)
// {
$str .='<table class="table table-bordered">
<tr>
<tr>
<td>Investment in Sukanya Samriddhi Scheme-80C</td>
<td><input name="sukanya_amt_'.$sukanya.'" type="text" id="sukanya_amt_'.$sukanya.'" size="10" maxlength="14" class="form-control-date" onkeyup="Validate_number(this)"/>
<p id="sukanya_amt_error'.$sukanya.'"></p>
</td>
</tr>
</tr>
<tr>
<td>Attachment</td>
<td><input name="sukanya_doc_'.$sukanya.'" type="file" id="sukanya_doc_'.$sukanya.'" size="10" maxlength="14" class="form-control-date" onkeyup="Validate_number(this)"/>
<p id="sukanya_amt_error'.$sukanya.'"></p>
</td>
</tr>
<tr>
<td align="left">
<div id="table_div_nsc_'.$sukanya.'" style="margin:0;padding:0;"> </div>
<div id="ext_loc_count2">
<input type="hidden" name="pro_ext_loc_count2_nsc" id="pro_ext_loc_count2_nsc" value="'.$sukanya.'"/>
</div>
</td>
</tr>
</table></form>
';
// }
}
Below is the javascript validate function
function validate_sukanya(num)
{
var add = num+1;
var error = '';
if($("#sukanya_amt_"+num).val()!= null)
{
var sukanya_amt= $('#sukanya_amt_'+num).val();
console.log(sukanya_amt);
if(sukanya_amt == '')
{
error += '--Please Enter 3) Contribution to Certain Pension Funds (sec 80CCC) - Amount for row ';
// pf_amt.focus();
$("#sukanya_amt_error"+num).html('<span class="text-danger">Please Enter Amount</span>');
}
if(sukanya_amt != "")
{
var validNum = /^([0-9]+)[\.]{0,1}[0-9]{0,2}$/;
if (validNum.test(sukanya_amt) == false)
{
error += '--Please Enter Valid 3) Contribution to Certain Pension Funds (sec 80CCC) - Amount for row ';
// pf_amt.focus();
$("#sukanya_amt_error"+num).html('<span class="text-danger">Please Enter Valid Amount</span>');
}
}
if(error == '')
{
error += validate_sukanya(add);
// var sukanya_data = $('#ipsf_sukanya_form').serialize();
var form = $('#ipsf_sukanya_form')[0];
// Create an FormData object
var sukanya_data = new FormData(form);
sukanya_data.append('sukanya_file', $('input[type=file]')[0].files[0]);
console.log(sukanya_data);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "../emp_proof_ajax/ajax_insert_sukanya_info.php",
//data: dataString,
data : sukanya_data,
processData: false,
contentType: false,
cache: false,
success: function(result20){
//alert(result);
// console.log("ReS "+result);
$(".step20").css("display","block");
// $("#purchase_property_data").val(result20);
}
});
//}
return true;
}
else
{
alert(error);
}
}
else
{
alert(error);
}
}
and i am trying to fetch both input text and file data into php page but I am getting only file data but not getting input type text data.
php file as follows:
<?php
include('../includes/include.php');
//die("hii");
// echo '<pre>_POST '; print_r($_POST); echo '</pre>';exit;
$arr = $_POST['arr'];
// $s = 0;
echo "<pre>";
print_r($_POST);
echo "<br>";
print_r($_FILES);
die;
?>

post by input file and text in one form using ajax

im using ajax to post file and text in a form, When I use the file and the text input simultaneously, I get into trouble , this is my form:
<form action="insertbook.php" method="post" id="addBookForm" enctype="multipart/form-data">
<table >
<!-- 1- IMAGE -->
<tr>
<td>Image:</td>
<td>
<input accept="image/gif, image/png, image/jpeg, image/jpg"
type="file" name="img_data" id="img_data">
</td>
</tr>
<!-- 2- NAME-->
<tr>
<td>Book Name: </td>
<td >
<input type="text" name="title" id="title">
</td>
</tr>
<!-- 3- CATEGORY -->
<tr>
<td>Book Cat: </td>
<td>
<select id="cat_dropdown" onchange="selectionCatchange()">
<?php for ($i=0; $i< sizeof($cats); $i++ ) {
echo '<option value="'.$cats[$i]['id'].'" >'. $cats[$i]['cat_name'] .'</option>';
} ?>
</select>
<?php echo
'<input id="cat_id" name="cat_id" value="'. $cats[0]['id'] .'" type="hidden">' ;
?>
</td>
</tr>
<!-- SUBMIT -->
<tr>
<th colspan="2" >
<input id="insertbook" type="submit" name="submit" >
</th>
</tr>
</table>
</form>
In Javascript codes, We have:
$("#addBookForm").submit(function(e) {
/* Stop form from submitting normally */
e.preventDefault();
/* Get some values from elements on the page: */
var title = document.getElementById('title').value;
var img_data = $('#img_data').prop('files')[0];
var cat_id = document.getElementById('cat_id').value;
var submit = "submit";
$.ajax({
url: "insertbook.php",
type: "POST",
data: {'title':title,
'img_data':img_data,
'cat_id':cat_id,
'submit':submit
},
dataType:'html',
success: function(data){
console.log(data);
},
error:function(data){
alert(data);
}
});
});
But in PHP Code, following this:
<?php
$conn = mysqli_connect(****);
mysqli_set_charset($conn,"utf8");
if(
isset($_POST['title']) &&
isset($_POST['cat_id']) &&
isset($_POST['submit'])
&&
isset($_FILES['img_data'])
){
$title = $_POST['title'];
$cat_id = $_POST['cat_id'];
// THIS SECTION RELATE TO IMAGE UPLOAD
$name_img = basename($_FILES['img_data']['name']);
$type_img = strtolower($_FILES['img_data']['type']);
$data_img = file_get_contents($_FILES['img_data']['tmp_name']);
$uploadOk = 1;
// Check file size
if ($_FILES["img_data"]["size"] > 2097152) {
echo "Sorry, your file is too large > 2 Mb!";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your image file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (mysqli_query( $conn,"INSERT INTO `books`( `title`, `img`, `cat_id`, `created_at`) VALUES ('$title','".addslashes($data_img)."', '$cat_id', NOW())" )) {
echo "New record created successfully";
} else {
echo "Error: " . "<br>" . mysqli_error($conn);
}
}}else{echo "Please set all information...!!! ";}
?>
But in the end I get the following error every time:
Notice: Undefined index: img_data in \insertbook.php on line 6
Notice: Undefined index: img_data in \insertbook.php on line 22
Notice: Undefined index: img_data in *\insertbook.php on line 23
Notice: Undefined index: img_data in ***insertbook.php on line 24
Warning: file_get_contents(): Filename cannot be empty in *\insertbook.php on line 24
Notice: Undefined index: img_data in ***\insertbook.php on line 34New record created successfully
But in the end there is no file stored in the database and only one empty record is created, hopefully you can help guide me through the problem.
Thanks
You should try this
Remove action method and enctype attributes from from tag element.
Try with sending data using new FormData() in ajax.
$("#addBookForm").on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
formData.append('submit', 'submit');
$.ajax({
type: 'POST',
url: 'insertbook.php',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Some problem occurred, please try again.");
}
});
});
To check a file input if it is set or not is this.
Change this art in your if condition
isset($_FILES['img_data'])
To this
isset($_FILES['img_data']['name'])

AJAX not working (call php and get the result back)

I am trying to make a checkbox calls php code then get back the results to be printed in textarea.
Now, the problem is that the php file doesn't print the result on the textarea or maybe the Ajax not working. I am sure that there is nothing wrong with MySQL code.
this is form.php code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var checkbox = document.getElementById('subscribers').checked;
//Check if checkbox is checked
if (checkbox === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {'variable': dataPhp},
complete: function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
});
function doalert() {
//Check if checkbox is checked
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {'variable': dataPhp},
complete: function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
}
</script>
</head>
<body>
<fieldset style="width:50%;margin:auto" dir=ltr>
<form action="" method="POST">
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>Your Balance</td>
<td><input type="text" class="form-control" name="Balance" size="20" disabled="disabled" value="<?php
echo $Credits;
?>"></td>
</tr>
<tr>
<td>Mobile No.</td>
<td><textarea textarea class="form-control" id="to" name="Mobile" cols="30" rows="5"></textarea><br></td>
<td>
<div class="checkbox">
<label><input type="checkbox" value="subscribers" onchange="doalert()" id="subscribers" checked>Subscribers</label>
</div>
</td>
</tr>
<tr>
<td>Message</td>
<td><textarea class="form-control" name="Text" cols="30" rows="5" required></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Go" value="Send SMS" /></td>
</tr>
</table>
</form>
</fieldset>
</body>
</html>
and this is the readSubscriber.php
<?php
require_once('../db_functions.php');
// Connect to the database
$connection = db_connect();
//if connection fails, stop script execution
if (mysqli_connect_errno()) {
echo "Error: " . $sql . "Connect failed: " . mysqli_connect_error();
} else {
$query = "SELECT * FROM phoneSubscribers";
// Query the database
$result = db_isExist($query);
if ($result) {
$result = db_fetch($query);
echo json_encode($result);
} else {
echo "No result";
}
}
?>
Set value of the textArea (instead of innerHTML)
Change like this. It will works. You cannot replace variable ('variable') as value
And You need to declare variable with value.
<script>
function doalert() {
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
var dataPhp = '';
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {variable: dataPhp},
success : function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
}
</script>
It done as I want
in my form:
$(document).ready(function() {
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
var resp = $("#response");
$.ajax({
type: 'POST',
url: 'assets/php/readSubscriber.php',
success: function(data) {
document.getElementById('to').value = data;
}
});
} else {
document.getElementById("to").value = "";
}
});
function doalert() {
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
var resp = $("#response");
$.ajax({
type: 'POST',
url: 'assets/php/readSubscriber.php',
success: function(data) {
document.getElementById('to').value = data;
}
});
} else {
document.getElementById("to").value = "";
}
}
in the called php file:
<?php
require_once('db_functions.php');
// Connect to the database
$connection = db_connect();
//if connection fails, stop script execution
if (mysqli_connect_errno()) {
echo "Error: " . $sql . "Connect failed: " . mysqli_connect_error();
} else {
$query = "SELECT * FROM phoneSubscribers";
// Query the database
$result = db_isExist($query);
if ($result) {
$result = db_fetch($query);
$jsonData = array();
while ($row = $result->fetch_assoc()) {
$jsonData[] = $row['phone'];
}
array_walk_recursive($jsonData, function($key, $value)
{
echo $key . ', ';
});
} else {
}
}
?>

Edit button inside table row only works in consecutive order

I am using php and javascript in order to display data from mysql in a table where each row must have an update button.
It seems to be working fine but i'm getting a weird behavior: it works when i click the buttons in consecutive order (#1 then #2 then #3..) but when i click them randomly (starting with #2 or #3...) it does nothing, just reloads the page.
Can you help me find what am i doing wrong, here's my code so far...
Thanks!
list.php:
<?php
$q= "SELECT * FROM list WHERE id = $f ORDER BY id";
if ($query = mysqli_query($db_con, $q)) {
$y=1;
echo '<table>'.
'<tr>'.
'<th>#</th>'.
'<th>Name</th>'.
'<th>Edit</th>'.
'</tr>';
while ($reg= mysqli_fetch_row($query)){
echo '<tr>';
echo '<td>'.$y.'</td>';
echo '<td>'.$reg[0].'</td>';
echo '<td>
<form id="frm_data'.$y.'" method="post">
<input type="hidden" id="name" name="name" value="'.$reg[0].'" />
<input type="hidden" id="f" name="f" value="'.$f.'" />
<input type="hidden" id="a" name="a" value="'.$a.'" />
<input id="FormSubmit" type="submit" value="EDIT">
</form>
</td></tr>';
$y = $y +1;
}
echo '</table>';
}
?>
validate.js
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
e.preventDefault();
$("#FormSubmit").hide();
var myData = {
name: $("#name").val(),
a: $("#a").val(),
f: $("#f").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "update.php", //Where to make Ajax calls
dataType:"json", // Data type, HTML, json etc.
data:myData, //Form variables
success : function(data) {
if(data.status == 'success'){
alert("OK!");
} else if(data.status == 'error') {
alert("ERROR!");
}
},
error : function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
update.php
<?php
$f = $_POST["f"];
$name = $_POST["name"];
$q = "UPDATE list SET edited = '1' WHERE id = '$f' AND name = '$name' ";
$update_row = mysqli_query($db_con, $q);
if (!$update_row) {
$response_array['status'] = 'error';
} else {
$response_array['status'] = 'success';
}
?>

Passing javascript value to php and back

I am having some trouble with passing a javascript value to php and back.
The idea is that I have a form where a user fills out a postal code and is then (onBlur) presented with the correct street and city in two different input fields. The street and city are collected by POST method from an external php file (getAddress.php).
I know that the php script returns the correct values and the complete() function is called onBlur, but I don't know whether the value gets passed onto the php script and back.
Javascript
<script language="javascript">
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if(postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "html",
data: dataString,
success: function(results) {
var json = JSON.parse(results);
document.getElementById("street").value = json.street;
document.getElementById("city").value = json.city;
}
});
}
}
</script>
getAddress.php
<?php
$postalCode = $_POST['postalCode'];
$postalCode = substr_replace($postalCode, ' ', 4, 0);
$sql = 'SELECT * FROM postalCodes WHERE postalCode="'.$postalCode.'"';
$res = $con->query($sql);
$res->data_seek(0);
while($row = $res->fetch_assoc()) {
$ID = $row['ID'];
$street = $row['street'];
$city = $row['city'];
$results[] = array('ID' => $ID, 'street' => $street, 'city' => $city);
}
echo json_encode($results);
?>
HTML
<input name="postalCode" type="text" maxlength="6" onBlur="complete()" /><br />
<input name="street" id="street" type="text" disabled /><br />
<input name="number" type="text" maxlength="6" /><br />
<input name="city" id="city" type="text" disabled /><br />
Change dataType: "html", to dataType: "json", and your $results is array so you need to use index
Try this:
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if (postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "json",
data: dataString,
success: function(results) {
document.getElementById("street").value = results[0].street;
document.getElementById("city").value = results[0].city;
}
});
}
}
As you are getting 500 internal server error message one of the reason can be that
$con->query($sql) is failing, make sure $con is initialized and table and field name are correct.

Categories

Resources