Fill the fields of lightbox's form with json data - php

I have a form that loads into a lightbox panel and a json response from a php script.
So im trying to load the data from json in the fields of form but nothing happens. Neither an error nor a result.
Here is some code:
Form:
<form id="FORM" name="newUserForm">
<br>
<label for="username" style="padding-right:35px;">Username: </label>
<input type="text" name="username" id="username" value="" style="margin-right:35px;">
<label for="email" style="padding-right:35px;">Email: </label>
<input type="text" id = "email" name="email" value="" ><br><br>
<label for="password" style="padding-right:40px;">Password: </label>
<input type="password" id="password" name="password"><br><br>
<label for="repeatpassword">Repeat Password: </label>
<input type="password" name="repeatPassword" style="margin-right:35px;">
<label for="submitBt" id="submitEditUser" style="background-color:black;color:white;font-weight:bold;padding:4px 4px 4px 4px;">Submit</label>
</form>
Javascript:
var user = user_id;
jQuery.ajax({
type: "POST",
async : false,
url: "/op/controller.php",
data: { method: "editUser", user_id: user },
contentType : ('application/x-www-form-urlencoded'),
dataType : "json" ,
success : function(json){
$('#lightbox-background').fadeIn(300);
$('#lightbox-panel').fadeIn(300).load('forms/editUserForm.php');
$('#username').val = json.username;
}
});
I have also tried with getElementById and populate but nothing happened.
Is there any idea why this problem exists? Maybe its because of the lightbox?
In addition i want to say that the html form exists in to the forms/editUserForm.php file.
Thanks.

You need to put the last command in the callback of load() and also the new value of #username must be passed as argument in val() like this
var user = user_id;
jQuery.ajax({
type: "POST",
async : false,
url: "/op/controller.php",
data: { method: "editUser", user_id: user },
contentType : ('application/x-www-form-urlencoded'),
dataType : "json" ,
success : function(json){
$('#lightbox-background').fadeIn(300);
$('#lightbox-panel').fadeIn(300).load('forms/editUserForm.php', function(){
$('#username').val(json.username);
});
}
});

Related

How to send an image alongside other fields to PHP?

I have a jQuery function that does the insert of an image with other fields to the database. Currently my function only inserts the image but does not insert the other form fields. I am using formData object and I don't understand how to append my fields together with the image file so I can pass it to the ajax request body.
Here is what I have tried so far:
// submit function
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
var firstname_h = $("#firstname_h").val();
var middlename_h = $("#middlename_h").val();
formData.append(firstname_h, middlename_h);
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// html form
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" id="firstname_h" placeholder="First name" />
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" id="middlename_h" placeholder="Middle name" />
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>
The image name is succesfully inserted in the db and the image is uploaded to the required target location,However, the fields - firstname and middlename are not inserted and I don't understand how to append these properties to the formData.
How can I pass these fields to the formData please?
You can use the following approach for storing the data with image.
1.In PHP API write logic for Upload image to server using move_uploaded_file() & Insert image file name with server path in the MySQL database using PHP.
2.In JS/JQuery, Read all HTML element & create an object & POST it to the API using AJAX Call.
your JS code should be like this. Hope this will help you to fix the issue.
var RegObj = {
'Field1': $("#Field1").val(),
'Field2': $("#Field2").val(),
'logo': $("#company_logo").attr('src'),
}
console.log(RegObj);
$.ajax({
url: "API_PATH_HERE",
type: "POST",
data: JSON.stringify(RegObj),
headers: {
"Content-Type": "application/json"
},
dataType: 'text',
success: function (result) {
//
},
error: function (xhr, textStatus, errorThrown) {
}
});
Like #Professor Abronsius suggested in the comments section I only needed to add the "name" tag to the form elements and remove the append from my function thus, I have edited the function and the form as follows:
// since I have added the name tag to the form elements, there is now
// no need to use the append() thus, I have commented out the append
// lines.
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
// var firstname_h = $("#firstname_h").val(); // removed this
// var middlename_h = $("#middlename_h").val(); // removed this
//formData.append(firstname_h, middlename_h); // removed this
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// added the "name" tag to the form elements
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" name="firstname_h" id="firstname_h" placeholder="First name" /> // added name="firstname_h"
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" name="middlename_h" id="middlename_h" placeholder="Middle name" /> // added name="middlename_h"
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>

Ajax file upload with Input texts - $_POST & File is empty

Hi I have problem for no reasons. I need help. I am trying to upload files and text input to my db and I am using ajax and PHP code for that. I have looked through many StackOverflow posts and stuffs but still unable to fix this.
HTML:
<form method = "POST" enctype = "multipart/form-data" id="myform">
<label class="form-label text-start">Enter your Name</label>
<input class="form-control" name="name" type="text" id="myname" placeholder="John">
<label class="form-label">Title</label>
<input class="form-control" type="text" name="name" id="title" placeholder="Operator">
<label class="form-label">Your Cute Photo (format: jpg and png only, less than 500kb)</label>
<input class="form-control" name="file" id="imgfile" type="file">
</form>
JQuery/Javascript:
var file_data = $('#imgfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', $('#name').val());
form_data.append('title', $('#title').val());
$.ajax({
type: 'POST',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
url: 'save_data.php',
data: {form_data},
success: function(data){
//alert(php_script_response);
alert(data)
window.location = 'account.php';
}
});
Error:
Undefined index name
Undefined index title
Undefined index file
PHP:
$name = $_POST['name'];
$title = $_POST['title'];
$file = $_FILE...
//all the other PHP codes
JQuery version
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
There are two elements in your form with the same name so it is a lottery which is used when you request it. Admittedly you were using the element ID rather than the names so probably perfectly OK. With FormData you can supply a reference to the form itself as the argument and that should take care of the rest for you. You can supply that formdata object directly as the data parameter in the ajax request. I'm not a user of jQuery so had to mix your jQuery with some vanilla js but you should see the idea.
const form = document.forms.usrupload;
form.bttn.onclick = () => {
var form_data = new FormData(form);
$.ajax({
type: 'POST',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
url: 'save_data.php',
data: form_data,
success: function(data) {
alert(data)
window.location = 'account.php';
}
});
}
label {
display: block;
width: 100%;
margin: 1rem;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
`label` elements should be associated with an input in one of two ways:
Using the `for="elemID"` or by wholly encompassing the input element as below
-->
<form name="usrupload" method="POST" enctype="multipart/form-data">
<label class="form-label text-start">Enter your Name
<input class="form-control" name="name" type="text" placeholder="John" />
</label>
<label class="form-label">Title
<input class="form-control" type="text" name="title" placeholder="Operator" />
</label>
<label class="form-label">Your Cute Photo (format: jpg and png only, less than 500kb)
<input class="form-control" name="file" type="file" />
</label>
<input type='button' name='bttn' value='Submit' />
</form>
The error is on
data: {form_data},
To change to
data: form_data,

handle posted formData object with files and other inputs in php

I need to handle inputs from form post and I have no idea, how to do it in php, because when I write for example $_POST["header"], it var_dumps null.
I am creating formData object and inserting all inputs from form. Then posting it with ajax.
Can you please help me? I need to handle "header", "content", "password" and files.
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>
$("#uploadFiles").submit(function(event){
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
console.log(Array.from(formDataObj));
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: {
formDataObj: formDataObj
},
dataType: 'json',
contentType: false,
processData: false,
success: function(results){
}, error: function(){
}
});
});
In uploadNews.php I have this:
exit(json_encode(var_dump($_POST["header"])));
It always returns "Undefined index: header", same as content or count($_FILES["file"]["name"])
All I want is to get somehow to posted values.. Thank you very much
You just to pass the actual formDataObj variable via your $.ajax. This is not the correct syntax to pass FormData via ajax => formDataObj: formDataObj
A FormData itself is an object which stores your data so what you are doing is making another object on top of it when you pass it via data
You can now var_dump(header) or var_dump($_FILES["file"]["name"]) to see everything coming to your PHP file.
Live Demo: (Change you jQuery code to this below and it will just work fine)
$("#uploadFiles").submit(function(event) {
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: formDataObj, //just pass the form Data object.
dataType: 'json',
contentType: false,
processData: false,
success: function(results) {
},
error: function() {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>

How to receive AJAX type post with PHP

I have got this straightforward HTML form
<form enctype="multipart/form-data" class="Mesform">
<textarea maxlength="400" type="text" placeholder="Your message" class="MessageInp"></textarea>
<div class="attach">
<input type="file" id="chatfil" accept="image/*">
<label for="chatfil">
<img src="../img/camera.png" class="addphc">
</label>
</form>
and this jquery
$("body").delegate('.MessageInp','keydown',function(e) {
if (e.which==13 ) {
$(".Mesform").submit();
}
});
That's how i submit my form
$(".Mesform").submit(function(){
var val=$(this).children('textarea').val();
var who=$(".headChat").text();
var formData = new FormData($(this)[0]);
alert(formData);
if (val!="") {
$.ajax({
url: '../files/ajax.php',
type: 'POST',
data:formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
But I do not know how to receive this AJAX call with PHP
In order for the form elements to show up in any request array, such as $_POST they will need name attributes (name="<something>"). For example:
<form enctype="multipart/form-data" class="Mesform">
<textarea name="description" maxlength="400" placeholder="Your message" class="MessageInp"></textarea>
<div class="attach">
<input name="chatfil" type="file" id="chatfil" accept="image/*">
<label for="chatfil">
<img src="../img/camera.png" class="addphc">
</label>
</form>
Plus as stated, <textarea> does not use a type.
One way to do it is this way:
switch (strtolower($_SERVER['REQUEST_METHOD'])) {
case 'post':
$postdata = file_get_contents('php://input'));
//Do Something For Post
break;
case 'get':
$getdata = file_get_contents('php://input'));
//Do Something For Get
break;
}

Onclick autocomplete Jquery from JSON

I'm trying to make an autocomplete for multiple inputs.
this is the suggestions:
<div id="person" class="204232">
<div class="name" >John Smiths</div>
<div class="age" >25 years</div>
</div>
<div id="person" class="204255">
<div class="name" >Michael Sosh</div>
<div class="age" >31 years</div>
</div>
I need to make something, when I click at div #person, autocomplete this form.
<form ...>
<input type="text" name="name" />
<input type="text" name="age" />
<input type="text" name="adress" />
<input type="text" name="city" />
<input type="text" name="country" />
</form>
I can get these informations JSON encoded on get.php?code=[.className of #person]
This is what i did, but it's not working.
$("#search").on(click, function() {
source: function (request, response) {
$.ajax({
url: "get.php?code="+$(this).attr('class'),
type: "GET",
data: request,
success: function (data) {
response($.map(data, function (el) {
return {
name: el.name
};
}));
}
});
},
select: function (event, ui) {
this.name = ui.item.name;
$('#name').val(ui.item.name);
event.preventDefault();
}
});
NOTE: In this example, I'm trying to autocomplete just the first input but i need to complete all.
Get.php?code=204232 return:
{"age":"25 years",
"name":"John Smiths",
"adress":"KariStr. 112",
"city":"London",
"country":"England"}
If you just want to set the inputs, you don't need to use source/select. Just call the ajax request, set the response type to JSON, and on the callback set the values directly like this:
$("#search").click(function() {
$.ajax({
url: "get.php?code="+$(this).attr('class'),
type: "GET",
dataType: 'json',
success: function (data) {
$("input[name='name']").val(data.name);
$("input[name='age']").val(data.age);
$("input[name='address']").val(data.address);
$("input[name='city']").val(data.city);
$("input[name='country']").val(data.country);
}
});
});
See that you were using the selector #name that means id=name. You either add the id to the input tag or use the name selector as i did above.

Categories