$.post variables not passing to php getting undefined index error - javascript

This code almost works, it inserts into the db and it is giving feedback on the page to say it has updated. However I am getting undefined index between lines 5-8 in the insert_message.php and my database is filling with blank entries (except the date).
Apologies for being new to jquery and AJAX. Need some help.
form
<form enctype='multipart/form-data' action='insert_message.php' method='POST' id='contact_form'>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='email'>Email:</label>
<input class='form-control' type='email' id='email' name='email' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='subject'>Subject:</label>
<input class='form-control' type='text' id='subject' name='subject' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="form-group">
<label for='message'>Message:</label>
<textarea class="form-control" placeholder="Message" id='message' required="required"></textarea>
</div>
<input type="hidden" name="reciever" id='receiver' value="Admin">
<input class='btn btn-primary' id='submit' type='submit' value='submit' >
</form>
<span id="result"></span>
jquery
<script>
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
var message1 = $('message').val();
var sender1 = $('sender').val();
var receiver1 = $('receiver').val();
var subject1 = $('subject').val();
$.post("insert_message.php", {message:message1, sender:sender1, receiver:receiver1, subject:subject1}, function(info) { $("#result").html(info);
});
clearInput();
});
$("#contact_form").submit( function() {
return false;
});
function clearInput() {
$("#contact_form :input").each( function() {
$(this).val('');
});
}
});
</script>
insert_message.php
<?php
include("connections/conn.php");
$getsubject = mysqli_escape_string($conn,$_POST["subject1"]);
$getmessage = mysqli_escape_string($conn,$_POST["message1"]);
$getsender = mysqli_escape_string($conn,$_POST["sender1"]);
$getreceiver = mysqli_escape_string($conn,$_POST["receiver1"]);
$date = date("Y-m-d");
$insertmessage = "INSERT INTO messages (id,subject,message,date,sender,receiver) VALUES (NULL,'$getsubject','$getmessage','$date','$getsender','$getreceiver')";
$insert = mysqli_query($conn, $insertmessage) ;
if($insert){
echo "Message Sent";
}else{
echo "Message did not send";
}
UPDATE
attempted alternative way but I still get the undefined index in the inser_message.php
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
$.ajax({
url: "insert_message.php",
type: "POST",
data: $("#contact_form").serialize(),
success: function(result){
$("#result").html(result);
}
});
});
});

You have several problems in both JS and PHP.
Adjust typo in input hidden where actually name="reciever" instead of name="receiver";
In your $("#submit").click() function you're trying to selecting elements with an invalid selector (e.g. $('message').val() instead of $("#message").val());
Adjust $_POST keys by removing 1 at end. If you have any doubt, print the whole array print_r($_POST);
This is not an error but a suggestion. Since you require conn.php to do your job, I would use require instead of include.

Remove the $conn and the 1's from your 'get' block and, for example:
$getsubject = mysqli_escape_string($_POST["subject"]);
$getmessage = mysqli_escape_string($_POST["message"]);
$getsender = mysqli_escape_string($_POST["sender"]);
$getreceiver = mysqli_escape_string($_POST["receiver"]);

Related

Multiple file upload using jquery serialization works only at the second call

I experience a strange problem:
Form ajax call with multiple files and form values works perfect, but only on the second call. First call ends up the the success: function(result) "else" condition. Second call works perfect and sends all data to the php. So I hit the submit button once and it shows up an empty error box and I hit the submit button again and everything works perfect.
How is that possible and how to solve that?
UPDATE #1: Found workaround, but not the solution. It works when I put if (result==="") { $(".form-application").submit(); } below the success function. But thats very dirty! ... and it upload all files twice! :-(
PROBLEM SOLVED David Knipe provided the solution!! Thank you so much!!
JQUERY:
$(".form-application").submit(function(e) {
e.preventDefault();
$("#btnSubmit2").text("Please wait...");
$("#btnSubmit2").attr("disabled", true);
var files = $('#files')[0].files;
var form = $(this);
var error='';
var formData = new FormData(this);
grecaptcha.ready(function() {
grecaptcha.execute('6Le4Qb0UAAAAAHUPcsmVYIk7zc4XCsiBnf6oE-fP', {action: 'create_comment'}).then(function(token) {
$('<input>').attr({
type: 'hidden',
value: token,
name: 'token'
}).appendTo('form');
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
formData.append("files[]", document.getElementById('files').files[count]);
}
}
if(error == '')
{
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: formData,
processData: false,
contentType: false,
success: function(result) {
if (result == "0") {
$("#btnSubmit2").text("Thank you!");
$("#btnSubmit2").attr("disabled", true);
$(".output_message").text("");
$(':input','.form-application')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
$(".output_message").append("<div class='alert alert-success alert-dismissible fade show' role='alert'>We have received your application!</div>");
} else {
$(".output_message").text("");
$(".output_message").append("<div class='alert alert-danger alert-dismissible fade show' role='alert'>"+result+"</div>");
$("#btnSubmit2").attr("disabled", false);
$("#btnSubmit2").text("try again");
}
}
});
}
else
{
alert(error);
}
});
});
return false;
});
HTML:
<form class="form-application" id="applicationform" method="post" action="https://<?PHP echo $_SERVER['HTTP_HOST']; ?>/include/process-application.php" enctype="multipart/form-data">
<input type="hidden" name="crsf" value="<?=$_SESSION['crsf']?>"/>
<input type="hidden" name="crsf-expire" value="<?=$_SESSION['crsf-expire']?>"/>
<div class="space40"></div>
<h6>Name</h6>
<input name="name" type="text" class="form-control" placeholder="Your Name">
<div class="space30"></div>
<h6>Email</h6>
<input name="email" type="text" class="form-control" placeholder="Your Email Address">
<div class="space30"></div>
<h6>Instagram Name</h6>
<input name="instagram" type="text" class="form-control" placeholder="Your Instagram Name">
<div class="space30"></div>
<h6>City & Country</h6>
<input name="from" type="text" class="form-control" placeholder="Where do you live?">
<div class="space30"></div>
<h6>Tell us more about you</h6>
<textarea name="message" class="form-control" rows="3" placeholder="Write some details about you, so we know you better."></textarea>
<div class="space30"></div>
<h6>Upload some photos of yourself</h6>
<div class="file-field">
<div class="btn btn-aqua">
<input name="files" id="files" type="file" accepts="image/*" multiple>
</div>
<div class="file-path-wrapper">
</div>
<div class="space20"></div>
</div>
</div>
<div class="col-12 text-center">
<button id="btnSubmit2" type="submit" class="btn btn-full-rounded btn-aqua">Submit Application</button>
<div class="space10"></div>
<span class="output_message"></span>
</div>
</form>
PHP Script /include/process-application.php
<?PHP
echo "0";
?>
OK, I think I've figured this out. $('<input>').attr(...); sets the token attribute on a new <input> element. But this is after var formData = new FormData(this);, so the token doesn't get included in formData. Then I guess you get an authentication error, and I guess it does the authentication before it even gets to the PHP part. It would just be a HTTP401 response with no body, hence "". But then, on the second attempt, the <input> has already been created with the correct token, and this ends up being used to authenticate.
Either keep onsubmit or action. Remove action from form tag, it will work

Return mysql fetch data and insert into form field value

i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});

select specific element jquery inside php foreach loop

I have foreach loop in php on front page for getting images and description of the image, inside foreach loop I have form, form is use for sending comment, this is front page..
<?php foreach ($photo as $p) : ?>
<div class="photo-box">
<div class="galP photo-wrapper" >
<div data-fungal="<?php echo $p->id; ?>" class='galFun-get_photo'>
<img src="<?php echo $p->thumb; ?>" class='image'>
</div>
</div>
<div class='inline-desc'>
<a href="/gallery/user.php?id=<?php echo $p->userId; ?>">
<?php echo $p->username; ?>
</a>
</div>
<form method="POST" action="" class="form-inline comment-form galForm">
<div class="form-inline">
<input type="hidden" class='photoId form-control' name="photoId" value="<?php echo $p->id; ?>" >
<input type="hidden" class='userId form-control' name="userId" value="<?php echo $session->userId; ?>" >
<textarea cols="30" rows="3" class='comment fun-gal-textarea' name="comment" placeholder="Leave your comment"></textarea>
<button type='button' name='send' class='sendComment'>SEND</button>
</div>
</form>
<div class='new-comm'></div>
<div class='comments-gal' id='comments'>
<div data-id='<?php echo $p->id; ?>' class='getComment'>
<span>View comments</span>
</div>
</div>
</div>
Using ajax I want to send userId,photoId and comment after clicking the button that has class sendComment. When I send comment on the first image everything is ok but when I try to send comment for some other image it wont work. I can't select that specific input and textarea for geting the right value .This is my jquery
$('body').on('click','.sendComment',function(){
var selector = $(this);
var userId = selector.siblings($('.userId'));
var photoId = selector.siblings($('.photoId'));
var c = selector.siblings($('.comment'));
var comment = $.trim(c.val());
if (comment == "" || comment.length === 0) {
return false;
};
$('#no-comments').remove();
$.ajax({
url: '/testComment.php',
type: 'POST',
data: {comment:comment,userId:userId,photoId:photoId}
}).done(function(result) {
...
}
})
});
Also, I have tried in every possible way to get the right value from the form without success..
This line
var userId = selector.siblings($('.userId'));
will be unlikely to get the correct input as, according to https://api.jquery.com/siblings/
.siblings( [selector ] )
selector
A string containing a selector expression to match elements against.
so this would need to be :
var userId = selector.siblings('.userId');
at that point you also need to get the actual value from the input, giving:
var userId = selector.siblings('.userId').val();
var photoId = selector.siblings('.photoId').val();
var c = selector.siblings('.comment');
and the rest of the code as-is.

using javascript var to query data with php mysql

i cant find any solution with this condition, when id user text value changed, name & address will filled. but it return some error in the php query.
sorry if this post duplicated because i cant find solution with my condition.
here the html form
<form id="frm_add_bill" name="frm_add_bill" >
<label >id user</label>
<input type="text" onchange="getplg()" id="kdp" name="kdp">
<label >user name</label>
<input type="text" maxlength="25" name="name" id="name" readonly>
<label >user address</label>
<input type="text" name="address" id="address" readonly>
</form>
Here javascript and php code
<script type="text/javascript"> function getplg(){
var kdpe = $('#kdp').value;
$.ajax({
type: 'post',
url: '',
data: kdpe,
timeout: 50000
});
}</script>
<?php
if (isset($_POST['kdpe'])) {
$kpde=htmlspecialchars($_POST['kdpe']);
$amxz=mysql_query("SELECT name, address from tbl_user where id_user='$kpde'");
$camqz=mysql_fetch_array($amxz);
echo "<script>document.write(fillem());</script>";
}
?>
<script type="text/javascript">
function fillem(){
document.frm_add_bill.name.value=<?php echo $camqz['0'];?>;
document.frm_add_bill.address.value=<?php echo $camqz['1'];?>;
}
</script>
function getplg(){
try{
var kdpe = $('#kdp').val();
console.log("here");
$.ajax({
method: 'post',
url: '',
data: {val:kdpe}}).done(function(data){
console.log(data);
console.log("hello");
});
}catch(Exception){
alert("error");
}
}
</script>
try this.
First of all change your ajax function as:
function getplg()
{
var kdpe = $('#kdp').val();
$.ajax({
type: 'post',
url: '',
data: "kdpe="+kdpe,
timeout: 50000
});
}
Here you need to pass as "kdpe="+kdpe by using param.
And move fillem() in if (isset($_POST['kdpe'])) check.
<?php
if (isset($_POST['kdpe'])) {
$kpde=htmlspecialchars($_POST['kdpe']);
$amxz=mysql_query("SELECT name, address from tbl_user where id_user='$kpde'");
$camqz=mysql_fetch_array($amxz);
echo "<script>document.write(fillem());</script>";
?>
<script>
function fillem(){
document.frm_add_bill.name.value=<?php echo $camqz['0'];?>;
document.frm_add_bill.address.value=<?php echo $camqz['1'];?>;
}
</script>
<?php
}
?>
Side note:
Stop using mysql_* becuase its deprecated and close in PHP 7. Use mysqli_* or PDO
You should pass data like this format:
$.ajax({name:value, name:value, ... })
i was found answer for this case
this js code use inside tag
<script type="text/javascript">
$(document).ready(function()
{
$("#kdp").blur(function() {
var idkategori = $(this).val();
if (idkategori != "")
{
$.ajax({
type:"post",
url:"getsubkat.php",
data:"id="+ idkategori,
success: function(data){
$("#name").html(data);
}
});
}
});
});
</script>
and this html
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">
User Code
</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="kpd" name="kdp" >
</div>
</div>
<div id="name">
</div>
and the php code are different page with js and html (getsubkat.php)
<?php
include ("components/inc/connection.php");
$id=$_POST['id'];
$query=mysql_query("SELECT name, address from tbl_user where user_code='".$id."'");
$data=mysql_fetch_array($query);
echo"<div class='form-group'>";
echo"<label for='inputEmail3' class='col-sm-2 control-label'>user name </label>";
echo"<div class='col-sm-10'>";
echo"<input type='text' class='form-control' value='$data[user_name]' readonly>";
echo"</div>";
echo"</div>";
echo"<div class='form-group'>";
echo"<label for='inputEmail3' class='col-sm-2 control-label'>user address</label>";
echo"<div class='col-sm-10'>";
echo"<input type='text' class='form-control' value='$data[user_address]' readonly>";
echo"</div>";
echo"</div>";
?>
You must use onkeydown, onkeyup, onpaste, or oninput event instead of onchange event.

Image not send using javascript when submit form no refresh page

I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).

Categories

Resources