Not able to submit form using ajax, php and jquery - javascript

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

Related

Ajax is not sending data to PHP

I'm new at ajax and i am confused becouse i think my ajax file is not sending data to php file or php is not getting it, IDK, Help me please
This is the form
<form id="register-form" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="text" name="email" id="email" tabindex="1" class="form-control" placeholder="Email Address" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" name="confirm-password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
This is the .js
$(document).ready(function(){
$("#register-submit").click(function(){
var email = $("#email").val();
var username = $("username").val();
var password = $("password").val();
$.ajax({
type: "POST",
url: "register.php",
data: "email="+email+"&username="+username+"&password="+password,
success:function(data){
alert("succes");
}
});
});
});
This is the .php
<?php
require_once("functions.php");
$email = $_POST["email"];
$username $_POST["username"];
$password $_POST["username"];
mysqli_query($connection, "INSERT INTO users(email, username, password) VALUES('$email', '$username', '$password')");?>
First of all:
var username = $("username").val();
var password = $("password").val();
Should be:
var username = $("#username").val();
var password = $("#password").val();
data: "email="+email+"&username="+username+"&password="+password
Should be:
data: {email: email, "username": username, password: password}
And
$username $_POST["username"];
$password $_POST["username"];
Should be:
$username = $_POST["username"];
$password = $_POST["password"];
You have to send the data in JSON format like:
var data = { "email": email, "username": username, "password": password };
so pass data var in data Ajax function!
1st: instead of using submit input click event you can use form submit event
$("#register-form").on('submit',function(){
and while you use a submit sure you need to prevent the page from default reload .. I think you problem is this point .. so you need to prevent the form by using e.preventDefault(); you can use it like
$("#register-form").on('submit',function(e){
e.preventDefault();
// rest of code here
$(document).ready(function(){
$("#submit").click(function(event) {
event.preventDefault();
var inputEmail = $("#email").val();
var inputUsername = $("#username").val();
var inputPassword = $("#password").val();
$.ajax({
type: "POST",
url: "register.php",
data: ({ email: inputEmail, password: inputPassword, username: inputUsername}),
success: function(data){
var obj = jQuery.parseJSON(data);
alert("Success " + obj.username + " " + obj.password + " "+ obj.email);
}
});
});
});
Here in .js file I put at the top in .click(function(event) { event.preventDefault(); }
preventDefault();
this function prevent the page from realoding when you press the submit button
data: ({ email: inputEmail, password: inputPassword, username: inputUsername})
Here i send the data data: ({nameOfTheVarieableYouWantToReadWithPHP: nameOfTheVariableFromJs})
Here is the .php file
require_once("database.php"); //require the connection to dabase
$email = protect($_POST['email']); //This will read the variables
$username = protect($_POST['username']); //sent from the .js file
$password = protect($_POST['password']); //
$result = array(); //This variable will be sent back to .js file
//check if the variables are emtpy
if(!empty($email) && !empty($username) && !empty($password)){
//db_query is my function from database.php but you can use mysqli_query($connectionVariable, $sqlString);
db_query("INSERT INTO users (email, username, password) VALUES ('$email','$username','$password')"); //Here insert data to database
//we will set array variables
$result['username'] = $username; //Here we set the username variable fron the array to username variable from js
$result['password'] = $password; // the password same as the username
$result['email'] = $email; //the email same as the username and password
}else{ // if the variables are empty set the array to this string
$result = "bad";
}
echo json_encode($result); //transform the result variable to json
In the .js file
success: function(data){
var obj = jQuery.parseJSON(data); //create a variable and parse the json from the php file
//You can set the variables get from the json
var usernameFromPhp = obj.username;
var passwordFromPhp = obj.password;
var emailFromPhp = obj.email;
alert("Success " + usernameFromPhp + " " + passwordFromPhp + " "+ emailFromPhp);//
}

Get two value inputs in javascript

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()" />

Get selected value in jquery script

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>

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.

is there a way to populate other textbox when onchange?

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>

Categories

Resources