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.
Related
I am trying to submit a form using ajax. In the backend part, i am trying to print the values of "fname", "location" and "image" in order to check if the data is reaching there or not
But when I am trying to do console.log to check for response, I get the following message
for dataString
filename=girl.jpgfname=johnlocation=Richmond, Virginia
for fname
Severity: Notice Message: Undefined index: fname
for image
No response
I am not able to fetch the data at the backend, can anyone please help me with this
Form
<form class="form-inline" id="form_add" enctype="multipart/form-data">
<input type="file" id="file-input" name="file-input" accept="image/*" >
<input type="text" class="form-control name" id="fname" placeholder="First Name" >
<select class="location" id="location" >
<option value="">Location</option>
<?php foreach($location as $loc): ?>
<option value="<?php echo $loc->city.', '.$loc->state;?>" ><?php echo $loc->city.', '.$loc->state;?></option>
<?php endforeach; ?>
</select>
<button type="submit" class="save_btn" id="submit" > <img src="save.png" class="Save"> </button>
</form>
Script
<script>
$("#submit").click(function()
{
event.preventDefault();
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '');
var fname = $("#fname").val();
var location = $("#location").val();
var dataString = 'filename='+ filename + 'fname='+ fname + 'location='+ location;
if(filename != "" || fname != "" || location != "")
{
$.ajax({
type: "POST",
url: "Data/add_data",
data: dataString,
cache: false,
success: function(result){
console.log(result);
console.log(dataString);
}});
}
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
On backend
$config['upload_path'] = './assets/client_img/.';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$data = $this->upload->data();
echo $img_name = $data['file-input'];
echo $_POST['fname'];
The selected values in the form was:
name of the file = girl.jpg
first name(fname) = John
value i had select from location dropdown = Richmond, Virginia
{
$.ajax({
type: "POST",
url: "Data/add_data",
data: {
filename : filename,
fname:fname,
location:location
},
cache: false,
success: function(result){
console.log(result);
console.log(dataString);
}});
}
for image only keep this
var filename = $('input[type=file]').val()
as codeignitor will show only the name in controller, no need to replace or ci wont be able to figure the path
the problem lies in your
dataString
you can do this:
var dataString='filename=' + filename + '|fname=' + fname + '|location=' + location;
so when you receive dataString in the backend (php) , you can split the dataString using:
$dataString=explode('|', $dataReceived);
so you can get each part by doing this:
$filename=$dataString[0];
$fname=$dataString[1];
$location=$dataString[2];
hope it helps
Your dataString must be a JavaScript Object.
var data = {filename: filename, fname: fname, location: location};
I'm creating a "real-time" checker which checks the input the user has given to check if it's already available on the database (e.g. username, phone number)
the input box:
<input type = "text" name = "user_username" placeholder="Username" onkeyup="chkstudidnumber(this.value)" autocomplete="off" required/><br/>
<div id = "msg"></div>
the javascript:
<script>
function chkstudidnumber(val)
{
$.ajax ({
type:"POST",
url:"check_username.php",
data:'username='+val,
success: function(data){
$("#msg").html(data);
}
});
}
</script>
and finally the php file:
<?php
include("dev_connection.php");
$g_username = htmlentities($_POST['username']);
$stud_username = mysqli_escape_string($con,$g_username);
$sql = "SELECT * FROM users WHERE username = '$stud_username' LIMIT 1 ";
$result = mysqli_query($con,$sql);
$count = mysqli_num_rows($result);
if($count==1) {
echo "<div id = 'msg_error'>";
echo "<img src = './img/img_error.png' style='height:20px;width:20px;vertical-align:middle;'> ";
echo " that username is already registered<br/>";
echo " if you forgot your password, please contact us";
echo "</div>";
} else {
echo "<div id = 'msg'>";
echo "<img src = './img/img_check2.png' style='height:10px;width:10px;'> ";
echo "username available";
echo "</div>";
}
?>
Now, I want to do this on my firstname and lastname input box
<input type = "text" name = "user_firstname" placeholder="Firstname"autocomplete="off" required/>
<input type = "text" name = "user_lastname" placeholder="Lastname"autocomplete="off" required/>
How can I apply the same javascript (or create a new one) to combine the two inputs into something like check_name.php?fname=samplename&lname=samplelastname
Change your function so that it can accept more then one params like:
function chkstudidnumber(val1, val2)
{
$.ajax ({
type:"POST",
url:"check_username.php",
data: {
'fname' : val1,
'lname' : val2
},
success: function(data){
$("#msg").html(data);
}
});
}
Simple use $('form').serialize() in ajax data function to get all the form input's on php page so that you can have all input's like username, first name, last name and all.
Try This:
<script>
function chkstudidnumber(val)
{
$.ajax ({
type:"POST",
url:"check_username.php",
data:$('form').serialize(),
success: function(data){
$("#msg").html(data);
}
});
}
</script>
If you have multiple form on the page then you can also provide class or id to the form and use that with serialize function to post that form data only.
<script>
function chkstudidnumber()
{
var firstName = $("input[name=user_firstname]").val();
var lastName = $("input[name=user_lastname]").val();
$.ajax ({
type:"POST",
url:"check_username.php",
data:'username='+firstName+'lastname='+lastName,
success: function(data){
$("#msg").html(data);
}
});
}
</script>
<input type = "text" name = "user_firstname" placeholder="Firstname"autocomplete="off" required/>
<input type = "text" name = "user_lastname" placeholder="Lastname"autocomplete="off" required onkeyup="chkstudidnumber()" />
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);
?>
I have a list of elements which are gotten from a xml file and I write them down in a table. In every row, I have a form which send the input field values to a jquery script, but it always pass the first value of the table, Does anyone knows how to pass the selected value?
This is my html and php code:
<?php
$licenseElement = "";
foreach ($xml->xpath("/Resultado/Registro") as $licenseElement):?>
<form>
<input type="hidden" id="desactivate" name="desactivate" value="" />
<input type="hidden" id="name" name="name" value="<?php echo $licenseElement->nombre; ?>" />
<input type='button' value='Desactivate' onclick='myCallDesactivate(desactivate,name);' />
</form>
<?php endforeach; ?>
And this is the jquery script:
<script>
function myCallDesactivate(desactivate,name) {
var val1 = $('#desactivate').val();
var val2 = $('#name').val();
var request = $.ajax({
url: "mypage.php",
data: { desactivate: val1, name: val2 },
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$("#mybox2").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
}
</script>
here's my code. I'm new to php. so sorry in advance.
I actually want to check my input in txtbarcode and if it is existing in my database I would like to populate the txtdescription but I don't know how to do it or is it even possible?
<?php
$barcode = $_POST['txtbarcode'];
$query = "SELECT * FROM product WHERE product_id = '$barcode'";
$query_exe = mysql_query($query);
$chk_query = mysql_num_rows($query_exe);
if($chk_query > 0)
{
$row = mysql_fetch_assoc($query_exe);
?>
<th class = "textbox"><input type = "text" name = "txtbarcode" value = "<?php echo $row['product_id']; ?>" style="width:80px"/></th>
<th class = "textbox"><input type = "text" name = "txtdescription" value = "<?php echo $row['product_name']; ?>" style="width:100px"/></th>
<?php
}
?>
You can do this using JQuery Ajax. Just using the change listener on the barcode field, it will send an ajax call to the check_barcode file - which will query the table and echo the data you want. The result will then be placed into the other textfield via JavaScript :).
The following is a separate PHP file.
<?php
//-----------------------------------
//check_barcode.php file
//-----------------------------------
if (isset($_POST['barcode'])) {
$query = mysql_query("SELECT * FROM product WHERE barcode = '".$_POST['barcode']."'");
$num_rows = mysql_num_rows($query);
if ($num_rows > 0) {
$row = mysql_fetch_assoc($query);
echo $row['product_name'];
}
}
?>
The following is your HTML and JavaScript code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#txtbarcode').change(function() {
var barcode = $(this).val();
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
success: function(result) {
$('#txtdescription').val(result);
}
});
});
});
</script>
<input type="text" name="txtbarcode" id="txtbarcode" />
<input type="text" name="txtdescription" id="txtdescription" />
UPDATE: Returning more data, and populating extra fields.
You'll need you echo a json array from the php script which contains both of the values.
For example:
echo json_encode(array('product_name' => $row['product_name'], 'unit_measure' => $row['product_name']));
and then within the JavaScript
<script>
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
dataType: 'json',
success: function(result) {
$('#txtdescription').val(result.product_name);
$('#unitofmeasure').val(result.unit_measure);
}
});
</script>