how to post image with ajax without form-data? - php

I tried var $pic1 = document.getElementById("pic").value; give the image path: C:fakepath/pictures/pic.jpg
Solutions always include sending in form-data. However, I could not do it.
my images folder: /img
I want image upload to 'img' folder after INSERT process.
view : https://i.stack.imgur.com/t7Gxx.png
<div class="form-row">
<div class="form-group col-md-4"><input type="text" class="form-control" id="input1" name="name" placeholder="Name"></div>
<div class="form-group col-md-4">
<div class="custom-file">
<input type="file" class="custom-file-input" id="pic" aria-describedby="inputGroupFileAddon01" accept=".jpg,.gif,.png">
<label class="custom-file-label" for="inputGroupFile01">Choose Image</label>
</div>
</div>
<div class="form-group col-md-4">
<input type="hidden" name="projeid" value="<?php echo $_POST['proje_id']; ?>">
<button type="submit" name="add" id="add" class="btn btn-primary btn-md btn-block">Add</button>
</div>
</div>
$('#add').click(function(){
var name = document.getElementById('input1').value;
var action = 'insert';
$.ajax({
url:"data/action.php",
method:"POST",
data: {
name: name,
action: action
},
success:function(data) {
load_data(projid);
}
});
});
--data/action.php--
if($_POST["action"] == "insert") {
$query = "INSERT INTO grundriss (name) VALUES ('".$_POST["name"]."')";
$statement = $db->prepare($query);
$statement->execute();
echo '<p>Data Inserted...</p>';
}

Try to convert image to base64 and then post it with ajax.

Related

CKEditor send Null Value to database via Ajax

I'm trying to create the Event's Calendar using PHP, Ajax and CKEditor 4. When I send the value to database via Ajax, it send the null value.
It send every values(title, start date, end date) except: c_details that I use CKEditor 4
Database's picture
My form's picture
Here's my form:
<div class="modal-body">
<form id="new_calendar">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title" placeholder="">
</div>
<div class="form-group">
<label>Description</label>
<textarea type="text" class="form-control" id="editor" name="c_details" placeholder=""></textarea>
</div>
<div class="form-group">
<label>Start Date</label>
<input type="text" class="form-control" name="start" placeholder="YYYY-mm-dd">
</div>
<div class="form-group">
<label>End Date</label>
<input type="text" class="form-control" name="end" placeholder="YYYY-mm-dd">
</div>
<input type="hidden" name="new_calendar_form">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="return new_calendar();">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
Here's Ajax:
function new_calendar() {
for (instance in CKEDITOR.instances) {CKEDITOR.instances[instance].updateElement()}
$.ajax({
type: "POST",
url: "json-event.php",
data: $("#new_calendar").serialize(),
success: function (data) {
$(".close").trigger('click');
alert(data);
location.reload();
}
});
return false;}
Here's all my code on Code Sandbox, I just changed the name='description' to name='c_details'
: https://codesandbox.io/s/blissful-water-nop1y?file=/index.php
Save new data:
public function new_calendar($data)
{
$db = $this->connect();
$add_user = $db->prepare("INSERT INTO calendar (id,title,c_details,start,end) VALUES(NULL,?,?,?,?) ");
$add_user->bind_param("ssss", $data['title'], $data['c_details'], $data['start'], $data['end']);
if (!$add_user->execute()) {
echo $db->error;
} else {
echo "Saved !";
}
}
before send data to ajax request put this:
for (instance in CKEDITOR.instances) {CKEDITOR.instances[instance].updateElement()}
This will update the element textarea with information of ckeditor

PHP/AJAX: Insert BLOB into MySQL Database

I have some hard times to save a blob (image file) to my sql-database.
I have three files: a html form (form.php), an ajax script (ajax.js) and a php-file (save.php).
I think i have some errors in my ajax.js, but after a long google search i couldn`t find a good solution. There must be a problem with the blob handling in JS....
HTML Form:
<div id="editEmployeeModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form id="update_form" enctype="multipart/form-data">
<div class="modal-header">
<h4 class="modal-title">table bearbeiten</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="id_u" name="id" class="form-control" required>
<div class="form-group">
<label>Image</label>
<input type="file" id="image_u" name="image" class="form-control" required>
</div>
<div class="form-group">
<label>Überschrift 1</label>
<input type="text" id="header1_u" name="header1" class="form-control" required>
</div>
<div class="form-group">
<label>Überschrift 2</label>
<input type="text" id="header2_u" name="header2" class="form-control" required>
</div>
<div class="form-group">
<label>Text</label>
<input type="text" id="text_u" name="text" class="form-control" required>
</div>
<div class="form-group">
<label>Link</label>
<input type="text" id="link_u" name="link" class="form-control" required>
</div>
<div class="form-group">
<label>Link-Text</label>
<input type="text" id="linkText_u" name="linkText" class="form-control" required>
</div>
<div class="form-group">
<label>Datum</label>
<input type="date" id="datum_u" name="datum" class="form-control" required>
</div>
</div>
<div class="modal-footer">
<input type="hidden" value="2" name="type">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<button type="button" class="btn btn-info" id="update">Update</button>
</div>
</form>
</div>
</div>
</div>
In form.php i specified all my Inputs and for the image type=file
Ajax Code:
$(document).on('click','.update',function(e) {
var id=$(this).attr("data-id");
var image=$(this).attr("data-image");
var header1=$(this).attr("data-header1");
var header2=$(this).attr("data-header2");
var text=$(this).attr("data-text");
var link=$(this).attr("data-link");
var linkText=$(this).attr("data-linkText");
var datum=$(this).attr("data-datum");
$('#id_u').val(id);
$('#image_u').val(image);
$('#header1_u').val(header1);
$('#header2_u').val(header2);
$('#text_u').val(text);
$('#link_u').val(link);
$('#linkText_u').val(linkText);
$('#datum_u').val(datum);
});
$(document).on('click','#update',function(e) {
var data = $("#update_form").serialize();
$.ajax({
data: data,
enctype: 'multipart/form-data',
type: "post",
url: "save.php",
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$('#editEmployeeModal').modal('hide');
alert('Data updated successfully !');
location.reload();
}
else if(dataResult.statusCode==201){
alert(dataResult);
}
}
});
});
My PHP-Code:
if($_POST['type']==2){
$id=$_POST['id'];
$image= base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$header1=$_POST['header1'];
$header2=$_POST['header2'];
$text=$_POST['text'];
$link=$_POST['link'];
$linkText=$_POST['linkText'];
$datum=$_POST['datum'];
$sql = "UPDATE `tblTable` SET `image`='$image',`header1`='$header1',`header2`='$header2',`text`='$text',`link`='$link',`linkText`='$linkText',`datum`='$datum' WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
}
My Datbase-Connection works fine. I can write and read all other Data (Text and Date) to my local Database. I think my problem is in the ajax.js. How can i specify $('#image_u').val(image); that it must handle a blob file and not just normal text input. And do i have to modify these lines?
var data = $("#update_form").serialize();
$.ajax({
data: data,
enctype: 'multipart/form-data',
type: "post",
url: "save.php",

Insert multiple values in row php

I can`t find a solution for this formular, so i am asking you guys how i can solve this: (1)I have this formular:
<form id="formRetur" action="" method="POST" novalidate="novalidate">
<div id="mail-status" style="color: black;text-align: center;"></div>
<h3><strong>
Detalii client
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nume_prenume" id="nume_prenume" placeholder="Nume Prenume">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_tlf" id="nr_tlf" placeholder="Numar telefon">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="adresa_email" id="adresa_email" placeholder="Adresa email">
</div>
</div>
</div>
<h3><strong>
Detalii comanda
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_comanda" id="nr_comanda" placeholder="Numar comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="data_comanda" id="data_comanda" placeholder="Data comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_factura" id="nr_factura" placeholder="Numar factura">
</div>
</div>
</div>
<h3><strong>
Detalii produse
</strong></h3>
<div class="row">
<i class="fa fa-plus" aria-hidden="true" style="position: absolute;z-index:999;"></i>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="den_prod" id="den_prod" placeholder="Denumire produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="culoare_prod" id="culoare_prod" placeholder="Culoare produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="cantitate" id="cantitate" placeholder="Cantitate">
</div>
</div>
</div>
<div class="maimulte">
</div>
<h3><strong>
Motiv retur
</strong></h3>
<div class="row">
<div class="col-md-12">
<textarea name="motiv" id="motiv" class="form-control" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12" style="margin-top:10px;margin-bottom:10px;"><div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div> </div>
<div class="col-md-12">
<button type="submit" id="send-message" class="btn btn-default">Trimite </button>
</div>
<div id="loader-icon" style="display:none;"><img src="images/loader.gif"></div>
</div>
</form>
I use ajax to insert data in DB, but i have an option where you can add more products when user press + adding +1 row with 3 fields name,color, qty and i want to insert also these in db, here is my ajax:
<script>
$(document).ready(function (e){
$("#formRetur").on('submit',(function(e){
e.preventDefault();
$("#mail-status").hide();
$('#send-message').hide();
$('#loader-icon').show();
$.ajax({
url: "valid_retur.php",
type: "POST",
dataType:'json',
data: {
"nume_prenume":$('input[name="nume_prenume"]').val(),
"nr_tlf":$('input[name="nr_tlf"]').val(),
"adresa_email":$('input[name="adresa_email"]').val(),
"nr_comanda":$('input[name="nr_comanda"]').val(),
"data_comanda":$('input[name="data_comanda"]').val(),
"nr_factura":$('input[name="nr_factura"]').val(),
"den_prod":$('input[name="den_prod"]').val(),
"culoare_prod":$('input[name="culoare_prod"]').val(),
"cantitate":$('input[name="cantitate"]').val(),
"motiv":$('textarea[name="motiv"]').val(),
"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},
success: function(response){
// $( '#frmContact' ).each(function(){
// this.reset();
// });
$("#mail-status").show();
$('#loader-icon').hide();
if(response.type == "error") {
$('#send-message').show();
$("#mail-status").attr("class","alert alert-danger");
} else if(response.type == "message"){
// grecaptcha.reset();
$('#send-message').show();
$("#mail-status").attr("class","alert alert-success");
}
$("#mail-status").html(response.text);
},
error: function(){}
});
}));
});
</script>
Here is my db:enter image description here
And there is my php file who insert in db with values from ajax:
<?php
if($_POST)
{
include('config.php');
$nume_prenume = filter_var($_POST["nume_prenume"], FILTER_SANITIZE_STRING);
$nr_tlf = filter_var($_POST["nr_tlf"], FILTER_SANITIZE_STRING);
$adresa_email = filter_var($_POST["adresa_email"], FILTER_SANITIZE_STRING);
$nr_comanda = filter_var($_POST["nr_comanda"], FILTER_SANITIZE_STRING);
$data_comanda = filter_var($_POST["data_comanda"], FILTER_SANITIZE_STRING);
$nr_factura = filter_var($_POST["nr_factura"], FILTER_SANITIZE_STRING);
$den_prod = filter_var($_POST["den_prod"], FILTER_SANITIZE_STRING);
$culoare_prod = filter_var($_POST["culoare_prod"], FILTER_SANITIZE_STRING);
$cantitate = filter_var($_POST["cantitate"], FILTER_SANITIZE_STRING);
$motiv = filter_var($_POST["motiv"], FILTER_SANITIZE_STRING);
if(empty($nume_prenume)) {
$empty[] = "<b>nume_prenume</b>";
}
if(empty($nr_tlf)) {
$empty[] = "<b>nr_tlf</b>";
}
if(empty($adresa_email)) {
$empty[] = "<b>adresa_email</b>";
}
if(empty($nr_comanda)) {
$empty[] = "<b>nr_comanda</b>";
}
if(empty($data_comanda)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($den_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($culoare_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(!empty($empty)) {
$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' obligatoriu!'));
die($output);
}
// if(!filter_var($email2, FILTER_VALIDATE_EMAIL)){ //email validation
// $output = json_encode(array('type'=>'error', 'text' => '<b>'.$email2.'</b> is an invalid Email, please correct it.'));
// die($output);
// }
//reCAPTCHA validation
if (isset($_POST['g-recaptcha-response'])) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
die($output);
}
}
// bag in db
$sql0 = "INSERT INTO retur (nume_prenume, nr_tlf, email, nr_comanda, data_comanda, nr_factura, den_prod, culoare_prod, cantitate_prod, motiv_retur)
VALUES ('$nume_prenume', '$nr_tlf', '$adresa_email', '$nr_comanda', '$data_comanda', '$nr_factura', '$den_prod', '$culoare_prod', '$cantitate', '$motiv')";
mysqli_query($conn, $sql0);
}
So basically this is a formular for returns products and if he have more products to return i added that jquery to add more fields and i want to be inserted in databased then i will fetch data and display it in my CMS.
1.You don't have to write that much code in ajax. You can easily use serialize():
Reduce you ajax code with below code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#your_form_id");
$("#Your_submit_id").click(function(){
$.ajax({
type:"POST",
url:"URL",
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>
2.To add multiple product:
-You have to create every input field as array for product info like:
<input type="text" name="prod_name[]">
This array statement store you every product info index wise. If you
used normal variable then it will post only you last product
details.
In Php code you have to take the count of posted
product title & use for loop to get the every product information.
for($i=0;$i<count($prod_name);$i++)
{
//Insert/fetch All Values like : $prod_name[$i]
}
-When you click on add, just create clone of the prev available div.

unable to insert record through jquery ajax

Right now I am facing a problem : I am trying to insert records in the database with the help of jQuery & Ajax. Unfortunately, I tried to alert inserted values but It doesn't show. I also checked through serialize function and I am unable to do that.
Here is my code of ajax
<script type="text/javascript">
$(document).ready(function(){
$("#add_new").click(function(){
$("#add").slideToggle();
});
$("#submit").click(function(){
var stud_no=$("#roll").val();
if(stud_no==''){
$("#msg").html("Input Roll Number");
} else {
var datastr = $("#sampleform").serialize();
alert(datastr);
$.ajax({
type:'POST',
url:'add_it.php',
data:datastr,
success:function(response){
$("#my_form")[0].reset();
$("#msg").html("Student Successfully Added");
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
});
});
</script>
Here is body code :
<body>
<a id="add_new">+add new item</a><br /><br />
<div id="msg"></div><br />
<div id="add">
<form id="sampleform">
<fieldset>
<div class="form-group row">
<label for="roll" class="col-sm-2 col-form-label">Roll Number</label>
<div class="col-sm-6">
<input type="text" name="roll" class="form-control" id="roll">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input type="text" name="name" class="form-control" id="name">
</div>
</div>
<div class="form-group row">
<label for="clas" class="col-sm-2 col-form-label">Class</label>
<div class="col-sm-6">
<input type="text" name="standard" class="form-control" id="standard">
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-6">
<input type="email" name="mail" class="form-control" id="mail">
</div>
</div>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</fieldset>
</fieldset>
</form>
</div>
Here is my add_it.php
<?php
include('connectdb.php');
$stud_no = trim($_POST['stud_no']);
$name = trim($_POST['name']);
$standard = trim($_POST['standard']);
$mail = trim($_POST['mail']);
$query = "insert into student (stud_no,name,standard,email) values ('$stud_no','$name','$standard','$mail')";
mysqli_query($con,$query) or die (mysqli_error());
?>
Your HTML form fields doesnt have any of these variables sent. You need to add name="email" etc to your form fields.
So for example the email field has to look like this:
<input type="email" name="email" class="form-control" id="mail">
id, class etc is not sent in POST - and therefor can not be recieved in the other end.
Jquery's serialize() function also only handles "name" fields.
https://api.jquery.com/serialize/
Snippet :
For a form element's value to be included in the serialized string, the element must have a name attribute

Adding dataType: "json" in Ajax won't work

I'm trying to retrieve data from my database then display it into a modal, however, when I add the dataType:"json" in ajax, it seems like it no longer performs my php file.I am new to ajax and json so I don't really have an idea where I am having problem. BTW, I am trying to achieve a CRUD function that is why I am trying to load data into a modal for updating. I am using the same modal for create and update.
This is my html code.
<div class="modal fade" id="addmodal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3>Add Product</h3>
</div>
<div class="modal-body">
<form class="" action="add.php" method="post" id="insert_form" enctype="multipart/form-data">
<div class="form-group input-width center-block">
<input class="form-control" type="file" name="img" id="img" value="" required/>
</div>
<div class="form-group input-width center-block">
<label>Product Name:</label>
<input class="form-control" type="text" name="pnametb" id="pnametb" placeholder="Product Name" required>
</div>
<div class="form-group input-width center-block">
<label>Price:</label>
<input class="form-control" type="text" name="pricetb" id="pricetb" placeholder="Price" required>
</div>
<div class="form-group input-width center-block">
<label>Category:</label>
<select style="" class="action form-control" name="category" id="category" required>
<option value="" disabled selected>Select a category:</option>
<?php
while($row = mysqli_fetch_assoc($result))
{
?>
<!-- Separated HTML and PHP -->
<option value="<?php echo $row['category']?>"><?php echo $row['category']?></option>
<?php
}
?>
</select>
</div>
<div class="form-group input-width center-block">
<label>Description:</label>
</div>
<div class="form-group input-width center-block">
<textarea style="color:black" name="destb" id="destb" class="message-box" placeholder="Description" rows="5" id="comment" required></textarea>
</div>
<input type="hidden" name="id" id="id">
<input class="btn btn-success" type="submit" name="add" value="Add" id="add">
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" name="button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My ajax code:
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
alert(id);
$.ajax({
url:"fetch.php",
method:"post",
data:{id:id},
dataType: "json",
success:function(data){
$('#img').val(data.img);
$('#pnametb').val(data.productname);
$('#pricetb').val(data.price);
$('#category').val(data.category);
$('#destb').val(data.description);
$('#id').val(data.id);
$('#add').val("Edit");
$('#addmodal').modal('show');
}
});
});
And here is my php file.
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["id"]))
{
$query = "SELECT * FROM productsa WHERE id = '".$_POST["id"]."'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
?>
Tell me if I need to clarify more things, I'm not really good in expressing what I want to happen. Any help will be highly appreciated.
First add a JSON header to your PHP script like so:
header("Content-Type: application/json", true);
Next instead of echo $row you do:
echo json_encode($row);
And after that you probably have to change your succes: function of your Ajax call to fix printing out the data, but i will leave that up to you :)
Further reading and a more detailed explanation here:
jQuery $.ajax request of dataType json will not retrieve data from PHP script

Categories