I am trying to update an image in the my database. I have a modal that is loaded with jquery. When clicking on the save modification button, alla the form data shows up except for the image file, which does not show up in the $_FILES in php. I tried all the indication found on the web (php ini file enables file upload, images size is good). The code works if I use that classic submit method, but I don't want a full screen refresh, I need to do it all in ajax. Here is the html:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
alert(data);
var url = '/PubDev/updatePubDev';
$.post(url, data, null, 'json')
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error");
}
})
.fail(function (data) {
alert("ajax error");
})
.always(function () {
});
});
<div class="md-modal md-effect-1" id="updatePubDevModal" >
<div class="md-content">
<div class="modal-header">
<button class="md-close close">×</button>
<h4 class="modal-title">Update Publisher/Developer</h4>
</div>
<form id="updatePubDevFrm" class="dz-clickable dropzone" action="/PubDev/updatePubDev" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="row dropzone">
<div class="col-lg-5">
<div class="form-group">
<label for="pubDevName">System Id of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevIdDisplay" id="pubDevIdDisplay" class="form-control input-large" disabled="true">
<input type="hidden" name="pubDevId" id="pubDevId" >
</div>
<div class="form-group">
<label for="pubDevName">Name of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevName-update" id="pubDevName-update" class="form-control input-large">
</div>
<div class="form-group">
<label for="date-founded">Date Founded</label>
<input type="text" placeholder="Date founded" id="date-founded-update" name="date-founded-update" class="form-control date-picker input-large">
</div>
<div class="form-group">
<label>What type of company is this?</label>
<div class="checkbox-nice">
<input type="checkbox" name="isPub-update" id="isPub-update">
<label for="date-founded-update">
This company is a publisher
</label>
</div>
<div class="checkbox-nice">
<input type="checkbox" name="isDev-update" id="isDev-update">
<label for="isDev-update">
This company is a developer
</label>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="main-box clearfix main-box-frame" >
<header class="main-box-header clearfix">
<h2>Upload Publisher /Developer Logo</h2>
</header>
<div class="main-box-body clearfix imgcontainer center">
<img id="preview" src="" class="pointable" alt="No Image Available" style="max-height:100%; max-width: 100%; "/>
<div class="main-box-body clearfix">
<div id="dropzone" class="drop-zone-frame" >
<input type="file" name="image2" id="image2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="confirmUpdPubdev" class="btn btn-primary">Save Modifications.</button>
</div>
</form>
</div>
</div>
Here is the php code:
public function updatePubDev() {
$fields = array();
$fields[$this->pubdev->get_id_name()] = $this->input->post('pubDevId');
$fields['name'] = $this->input->post('pubDevName-update');
if ($this->input->post('date-founded'))
$fields['date_founded'] = stampa_data_formato_DATE($this->input->post('date-founded-update'), '/');
if ($this->input->post('isPub-update'))
$fields['publisher'] = 1;
else
$fields['publisher'] = 0;
if ($this->input->post('isDev-update'))
$fields['developer'] = 1;
else
$fields['developer'] = 0;
$row_count = $this->pubdev->update($fields,$this->pubdev->get_id_name());
$file = $_FILES['image2'];
//$idPubDev = $this->input->post("pubDevName");
$ds = DIRECTORY_SEPARATOR;
$path = dirname('../') . $ds . 'application' . $ds . 'assets' . $ds . 'img' . $ds . 'pub_devs' . $ds . 'logos' . $ds;
//print_r($file);
$info = new SplFileInfo($file['name']);
//var_dump($info->getExtension());
$filename = "logo_id_" . str_pad( $this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . "." . $info->getExtension();
$result = $this->upload->uploadfile($file, $path, $filename);
//echo "test";
if ($result['status'] === "OK") {
$logo = 'logo_id_' . str_pad($this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . '.' . $info->getExtension();
$this->pubdev->update(array('logo' => $logo, $this->pubdev->get_id_name() => $this->input->post('pubDevId')), $this->pubdev->get_id_name());
$result['message'] = "file saved successfully";
$result['query'] = $this->db->last_query();
}
$result['update_rows']= $row_count;
echo json_encode($result);
}
I tried the .ajax version, but the problem persist, here is the modified jquery:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = '/PubDev/updatePubDev';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false
})
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error!");
}
})
.fail(function (data) {
alert("ajax error!");
})
.always(function () {
});
});
It is not a duplicate question because the answer provide contained different properties necessary to uplaod both image and data inputs. these two properties in the $.ajax call are needed:
processData: false,
contentType: false
This way, it solved my problem.
Use FormData as data instead of $(this).serialize();, set processData and contentType to false
var data = new FormData();
data.append("file", $(":file", this)[0].files[0]);
$.ajax({
url: "/PubDev/updatePubDev",
type: "POST",
data: data,
processData: false,
contentType: false
})
Please try to use file_get_contents('php://input'); to get the upload content.
Related
check_availability.php
this is my php to check the form if it is already exist.
<?php
require_once("config.php");
//code check email
if (!empty($_POST["CUSUNAME"])) {
$result = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE CUSUNAME='" . $_POST["CUSUNAME"] . "'");
$row = mysqli_fetch_row($result);
$email_count = $row[0];
if ($email_count > 0) echo "<span style='color:red'>Username is already used.</span>";
else echo "<span style='color:green'>Username is available.</span>";
}
// End code check email
//Code check user name
if (!empty($_POST["PHONE"])) {
$result1 = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE PHONE='" . $_POST["PHONE"] . "'");
$row1 = mysqli_fetch_row($result1);
$user_count = $row1[0];
if ($user_count > 0) echo "<span style='color:red'>Phone is already used.</span>";
else echo "<span style='color:green'>Phone number is available.</span>";
}
// End code check username
?>
LogSignModal.php
here is my page.
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"CUSUNAME">Username:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkUserNameAvailability()" id="CUSUNAME" name="CUSUNAME" placeholder=
"Username" type="text" value="">
<span id="username-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"PHONE">Contact Number:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkPhoneAvailability()" id="PHONE" name="PHONE" placeholder=
"Phone Number" type="number" value="">
<span id="Phone-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4" align = "right"for=
"image"></label>
<div class="col-md-8">
<input type="submit" name="submit" value="Sign Up" class="submit btn btn-pup" />
<button class="btn btn-default" data-dismiss="modal" type=
"button">Close</button>
</div>
</div>
</div>
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'CUSUNAME='+$("#CUSUNAME").val(),
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'PHONE='+$("#PHONE").val(),
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
my code is all worked, but I can't make a submit button to appear when the value I input in textbox is available in database and disappear if it is already use.
I hope someone help me, thank you.
Edit: First, you should definitely also check the comment of Dharman and rewrite how you fetch data from MySQL in your PHP code since the current state is vulnerable to SQL Injections and is absolutely not safe to use!
The problem is how you pass your data to your ajax function. The way you do it, the server receives nothing but a plain string, for example 'CUSUNAME=dave'. This way $_POST["CUSUNAME"] will find nothing and your server response will stay empty. So you should pass your data as an object the following way :
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'CUSUNAME': $("#CUSUNAME").val()},
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'PHONE': $("#PHONE").val()},
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
Please refer question: Jquery Image Upload in Form with Plugin goes Null
I am trying to submit a form using JQuery Ajax and trying to retrieve in a PHP file and save. for the particular form there are two file inputs.
Image
Note
when I debug using var_dump($_FILES), I was able to see only Note's array but not Image's. for image upload I am using a plugin called FancyUpload, that is what probably causing the issue. below is the form
<form id="form" action="add.php" method="post" autocomplete="off" enctype="multipart/form-data">
<div>
<input aria-label="cxname" id="cxname" name="cxname" class="form-control" placeholder="Name" type="text">
</div>
<div>
<select name="sales" id="sales" class="SlectBox form-control">
<option value='0'>Sales</option>
<?php echo sales(); ?>
</select>
</div>
<div>
<input class="custom-file-input" placeholder="choose note" name="note" id="note" type="file">
<label class="custom-file-label">Choose Note</label>
</div>
<div>
<input class="custom-file-input" placeholder="Choose Image" name="image" id="image" type="file" multiple>
</div>
<div>
<button id="submit" class="btn btn-primary btn-size">Add</button>
</div>
</form>
Jquery Below along with its fancy uploader classes
<!-- JQuery min js -->
<script src="assets/plugins/jquery/jquery.min.js"></script>
<script src="assets/plugins/jquery-ui/ui/widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.ui.widget.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fileupload.js"></script>
<script src="assets/plugins/fancyuploder/jquery.iframe-transport.js"></script>
<script src="assets/plugins/fancyuploder/jquery.fancy-fileupload.js"></script>
<script>
$(document).ready(function(e){
var image = $('#image').FancyFileUpload({
maxfilesize : 1000000,
params : {
action : 'form'
},
autoUpload: false
});
$("#form").on('submit', function(e){
e.preventDefault();
var fd = new FormData();
fd.append('pimage', $(image)[0].files[0]);
fd.append('deliveryNote', $("#note")[0].files[0]);
fd.append('cxname', $('input[name=cxname]').val());
fd.append('sales', $('select[name=sales]').val());
$.ajax({
type: 'POST',
url: 'add.php',
data: fd,
dataType: 'json',
processData:false,
contentType: false,
cache: false,
async: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset();
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>');
alert('received');
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
Retreiving PHP
upload_dir = 'uploads/';
pdf_dir = 'doc/';
if (isset($_POST['cxname']) || isset($_POST['deliveryNote']) || isset($_POST['pimage']) || isset($_POST['sales'])) //even tried with ($_FILES['pimage'])
{
$cxname=$_POST['cxname'];
$sales=$_POST['sales'];
var_dump($_FILES);
//MOVE IMAGE -> Comes Empty
if(!empty($_FILES['pimage']['tmp_name']))
{
$temp = $_FILES['pimage']['tmp_name'];
$name = $_FILES['pimage']['name'];
$result = move_uploaded_file($temp,$upload_dir.$name);
$response['status'] = 1;
$response['message'] = 'IMAGE HAS BEEN SAVED';
}
else{
$name = '';
$response['status'] = 0;
$response['message'] = 'IMAGE CAME EMPTY!';
}
//SAVE NOTE
$_pdfDN = $_FILES['deliveryNote']['name'];
$Tempfile = $_FILES['deliveryNote']['tmp_name'];
$_pdfResult = move_uploaded_file($Tempfile,$pdf_dir.$_pdfDN);
}
If I do without image upload plugin, it works fine. Please advice.
I want to sent some data with ajax to a php file. I created a FormData, and then, i append all the data to it, that i want to send. I dont get any error message in the console.
My problem is, that the formdata is always empty, and the php file is not getting any data also.
The form:
<div class="tab-pane show" id="tab5">
<form id="AllapotForm" class="form-horizontal" method="post" enctype="multipart/form-data">
<table id="products" class="table table-hover">
<thead>
<tr class="tr_bold">
<!--width="33.3%"-->
<td class="left" >Létrehozva</td>
<td class="left" >Állapot</td>
<td class="left" >A megrendelő értesítve email-ben</td>
<td class="left" >Megjegyzés</td>
</tr>
</thead>
<tbody id="allapotok">
<?php
$get_r_allaptok = mysqli_query($kapcs,
"
SELECT
rendeles_allapot.*,
rendeles_allapotok.rendeles_allapotok_nev
FROM rendeles_allapot
LEFT JOIN rendeles_allapotok ON rendeles_allapot.allapot_allapot_id = rendeles_allapotok.rendeles_allapotok_id
WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id ASC
")
or die(mysqli_error($kapcs));
if(mysqli_num_rows($get_r_allaptok) > 0 )
{
while($r_allapot = mysqli_fetch_assoc($get_r_allaptok))
{
if($r_allapot['allapot_notify'] == 0 ) { $ertesitve = "Nem"; }
if($r_allapot['allapot_notify'] == 1 ) { $ertesitve = "Igen"; }
echo '<tr>
<td class="left">'.$r_allapot['allapot_datetime'].'</td>
<td class="left">'.$r_allapot['rendeles_allapotok_nev'].'</td>
<td class="left">'.$ertesitve.'</td>
<td class="left">'.$r_allapot['allapot_comment'].'</td>
</tr>';
}
}
?>
</tbody>
</table>
<img src="<?php echo $host; ?>/images/assets/preloader.gif" id="preloaderImage2" style="display:none" class="img-responsive" style="margin:10px auto;">
<div class="form-group row">
<label class="control-label col-md-2">Állapot:</label>
<div class="col-md-2">
<select name="allapot" id="allapot" class="input input-select form-control">
<?php
$check_allapot = mysqli_query($kapcs, "SELECT allapot_allapot_id FROM rendeles_allapot WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id DESC LIMIT 1");
if(mysqli_num_rows($check_allapot) > 0 )
{
$allapot_fetch = mysqli_fetch_assoc($check_allapot);
$ertek = $allapot_fetch['allapot_allapot_id'];
}
else
{
$ertek = intval($a['status']);
}
$get_allapotok = mysqli_query($kapcs, "SELECT rendeles_allapotok_id, rendeles_allapotok_nev FROM rendeles_allapotok WHERE rendeles_allapotok_status = 1 ORDER BY rendeles_allapotok_nev ASC");
if(mysqli_num_rows($get_allapotok) > 0 )
{
while($allapot = mysqli_fetch_assoc($get_allapotok))
{
$selected = $ertek == $allapot['rendeles_allapotok_id'] ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $allapot['rendeles_allapotok_id'] . '">' . $allapot['rendeles_allapotok_nev'] . '</option>'."\n";
}
}
?>
</select>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megrendelő értesítése email-ben:</label>
<div class="col-md-2">
<input type="checkbox" name="notify" id="notify" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés hozzáadása az email-hez:<span class="help">Amennyiben ezt bepipálja, a megjegyzés az ügyfélnek kiküldött üzenetbe is bele fog kerülni.</span></label>
<div class="col-md-2">
<input type="checkbox" name="add_text" id="add_text" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Fájl csatolása az email-hez:</label>
<div class="col-md-2">
<input type="file" name="file" id="file" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés:</label>
<div class="col-md-8">
<textarea name="comment" id="comment" style="width:100%;height:200px;"></textarea>
<div style="margin-top: 10px; text-align: center;">
<a class="saveButton btn btn-primary" style="color:#fff" onclick="allapot_modosit();" id="history_button">Állapot módosítása</a>
</div>
</div>
</div>
</form>
</div>
I call this function on a button click event.
function send_data()
{
var html;
var RendelesID = <?php echo $id; ?>;
var RendelesUserEmail = "<?php echo html($a['email']); ?>";
var RendelesUserName = "<?php echo html($a['nev']); ?>";
var webshopEmail = "<?php echo $webshopEmail; ?>";
var webshopName = "<?php echo $webshopName; ?>";
var Allapot = $( "#allapot option:selected" ).val();
var Comment = CKEDITOR.instances['comment'].getData();
if($("#notify").is(':checked')){var Notify = 1;}else{var Notify = 0;}
if($("#add_text").is(':checked')){var AddToEmail = 1;}else{var AddToEmail = 0;}
var formData = new FormData($('#AllapotForm')[0]);
formData.append('fileName', $('#file')[0].files[0]);
formData.append(RendelesID, RendelesID);
formData.append(RendelesUserEmail, RendelesUserEmail);
formData.append(RendelesUserName, RendelesUserName);
formData.append(webshopEmail, webshopEmail);
formData.append(webshopName, webshopName);
formData.append(Allapot, Allapot);
formData.append(Comment, Comment);
formData.append(Notify, Notify);
formData.append(AddToEmail, AddToEmail);
console.log(formData);
$.ajax({
type: 'POST',
cache: false,
url: 'files/update_rendeles_allapot.php',
//dataType: 'html',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: { formData:formData },
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
alert(data);
},
complete: function(){
$('#preloaderImage2').hide();
},
error: function (e) {
alert(e.responseText);
console.log(e);
}
});
}
data: { formData:formData },
You need to pass the form data object itself, not a plain object.
data: formData
Have you already seen this?
FormData created from an existing form seems empty when I log it
If yes try to check your network look to the Network then take a look at your request.
You can also try to check your API via Postman if it's working properly.
This is my code for a form. I am asking user to input email and password and checking if user is registered or not. If he is registered then I alert success:
<form role="form" class="legacy-form" action="" method="POST" id="myform1">
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="email" name="email" id="loginemail" class="form-control" placeholder="Email Address" required>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="password" name="password" id="loginpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="row" style="padding:15px">
<div class="col-xs-6 col-sm-3 col-md-3 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="submit" value="Log In" class="btn btn-primary" id="loginbtn">
</div>
</div>
<div class="col-xs-6 col-sm-3 col-md-3">
<div class="form-group">
<input type="submit" value="Cancel" class="btn btn-danger" data-dismiss="modal">
</div>
</div>
</div>
</form>
This is the php code wherein the connection is placed in another file 'init.php'
<?php
include('init.php');
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result) {
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
echo json_encode(array("server_response"=>$response));
} else {
echo "error";
}
mysqli_close($con);
}
?>
this is my js file. On printing info in console I get Connection sucess{"server_response":[{"Count":"1","name":"sagar"}]}
$("#loginbtn").click(function(e) {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
check_for_user(loginemail, loginpassword);
function check_for_user(loginemail, loginpassword) {
console.log("in check_for_user");
var i = 0;
console.log(i);
i++;
var c = "";
var x = "1";
var user = "";
var formdata = {
loginemail: loginemail,
loginpassword: loginpassword
}
$.ajax({
url: 'getData.php',
type: "POST",
data: formdata,
dataType: 'text',
success: handle_success,
error: handle_error
});
function handle_success(info) {
console.log(info);
var obj = jQuery.parseJSON(info);
console.log(obj);
$(obj.server_response).each(info, function(index, value) {
user = value.name;
c = value.Count;
});
console.log(c);
console.log(user);
if (x == c) {
alert("Welcome");
//document.location='online.html';
} else {
alert("Enter valid username and password");
}
}
function handle_error() {
alert("error");
}
}
});
The flow of the code is like when the #loginbtn is clicked it posts loginemail and loginpassword on php and then it checks in database whether there is an identical entry in database, if yes it alerts "welcome". I have searched a lot on StackOverflow I found that it says there is error in either parsing JSON or in decoding it.
It looks like you are echoing "Connection success" in init.php although we can't see that.
A json response should have no other content in response ... just the json.
Here is my HTML Code:
<div class="form-horizontal row-border">
<div class="form-group">
<label class="col-md-2 control-label">Title:</label>
<div class="col-md-10"><input class="form-control" id="title" name="title" type="text"></div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Article:</label>
<div class="col-md-10">
<textarea name="editor1" id="editor" rows="10" cols="80">
Let's go...
</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Tags:</label>
<div class="col-md-10"><input class="tags" id="tags" type="text" value="">
</div>
</div>
<div class="row" style="margin-left:92%;">
<input type="button" id="PostArticle" class="btn btn-success" value="Post Article"></input>
</div>
</div>
Here is my JavaScript code:
<script type="text/javascript">
$("#PostArticle").click(function() {
var title = $("#title").val();
var text = $("#editor").text();
var tags = $("#tags").val();
$.ajax({
url: 'post_new_article.php',
type: 'POST',
data: {
title: title,
tags: tags,
text: text
},
dataType: 'json',
success: function (data) {
noty({text: 'MySite.com:' + data.title + ' was successfully created!', type: 'success'});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
noty({text: 'Failure - The article was not created! Error is: ' + errorThrown + '', type: 'error'});
}
});
});
</script>
Here is the code from: post_new_article.php:
<?php
require "include/config.php";
require "include/functions.php";
ConnectWithMySQLDatabase();
error_reporting(E_ALL);
ini_set('display_errors', '1');
$title = $_POST['title'];
$text = $_POST['text'];
$tags = $_POST['tags'];
$month = date('F');
$year = date('Y');
$day = date('d');
if(isset($_POST['title']))
{
mysql_query("INSERT INTO `Blog` (`id`, `Title`, `Article`, `Autor`, `Date`, `Month`,`Year`, `Tags`, `Image`) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");
}
$result['title'][0] = $title;
echo json_encode($result);
From all things it seems that only the MySQL insert function is not working. I can confirm that ConnectWithMySQLDatabase(); function is working as intended and this function is establishing the connection to MySQL.
Somehow it seems i can not insert the mysql query after i hit the Post Article button. I can confirm that i receive response from post_new_article.php because i receive a notification with the title of the article as a back response. So the json seems to read back the title of the article.
So can you help me out resolve this problem and make it insert the query to the MySQL database ?
Thanks in advance!
Try this
in your form submit button should be
<input type="submit" id="submit" class="btn btn-success" value="Post Article"></input>
And AJAX Should be
<script>
$(function(){
$( "#submit" ).click(function(event)
{
event.preventDefault();
var title = $("#title").val();
var text = $("#editor").text();
var tags = $("#tags").val();
$.ajax(
{
type:"post",
dataType: 'json',
url: "./post_new_article.php",
data:{ title:title, text:text,tags:tags},
success:function(data)
{
}
});
});
});
</script>
EDIT 01
Change this
mysql_query("INSERT INTO Blog (id, Title, Article, Autor, Date, Month,Year, Tags, Image) VALUES ('', '$title', '$text', 'Venelin Vasilev', '$day','$month', '$year', '$tags', '')");