SVG data not get on form submit - php

I want save SVG data in a database. I will try with a simple submit and also with AJAX. I also set content-type="image/svg-xml"
I will check data with print_r($_POST); SVG Content displayed here when I will try to store on db svg value as null.
<?php echo form_open('admin/shape/add',array('class' => 'form-horizontal', 'name' => 'catfrm', 'id' => 'catfrm')); ?>
<div class="box-body">
<div class="col-md-8">
<div class="form-group">
<label class="col-sm-2 control-label">Title <span class="error">*</span></label>
<div class="col-sm-10">
<input type="text" name="title" value="" id="title" class="form-control" />
</div>
</div>
<!-- form-group -->
</div>
<div class="col-md-8">
<div class="form-group">
<label class="col-sm-2 control-label">Content <span class="error">*</span></label>
<div class="col-sm-4" id="shape_priview" height="30px">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0,0,100,100"><polygon points="50 0, 0 100, 100 100"></polygon></svg>
</div>
<div class="col-sm-6">
<textarea name="content" id="shape_content" class="form-control"><svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0,0,100,100"><polygon points="50 0, 0 100, 100 100"></polygon></svg></textarea>
</div>
</div>
<!-- form-group -->
</div>
</div>
<div class="box-footer" align="center">
<button type="submit" class="btn btn-success">Add</button>
<button type="reset" class="btn btn-dark" onclick="window.location.href = '<?php echo site_url('admin/shape'); ?>'">Cancel</button>
</div>
<?php echo form_close();?>
$(document).ready(function() {
$("#shape_content").on("change keyup paste", function() {
$("#shape_priview").text('');
var shape_content = $("#shape_content").val();
$("#shape_priview").html(shape_content);
});
$("#catfrm").validate({
rules: {
title: {
required: true,
}
},
messages: {
title: {
required: "Title is required",
}
},
submitHandler: function(form) {
$("#catfrm").submit(function(event) {
event.preventDefault();
var content = $("#shape_content").val();
var title = $("#title").val();
alert(content);
$.ajax({
type: "post",
url: "<?php echo site_url('admin/shape/add'); ?>",
data: {
"title": title,
"content": content
},
contentType: "application/json",
success: function(responseData, textStatus, jqXHR) {
alert(responseData);
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
}
});
});

Related

cannot input textarea with CKeditor on Codeigniter

when i want to input textarea with CKeditor , the string is Null , but when i delete class="CKeditor" in textarea the string successfully filled.
i have check in controller and database but it does not matter
My Controller
function AddNews(){
$data = array(
'title_news' => $this->input->post('title_news'),
'text' => $this->input->post('text_news'),
'date' => $this->input->post('date'),
);
$insert = $this->m_news->save($data);
echo json_encode(array("status" => TRUE));
}
My View
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_news"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<input name="title_news" placeholder="Title Name" class="form-control" type="text"><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<textarea class="ckeditor" name="text_news" rows="3" placeholder="Enter text . . . "></textarea><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date</label>
<div class="col-md-9">
<div class="input-group">
<input class="form-control date-picker" name="date" type="text" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" /><span class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></span>
</div>
</div>
</div>
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
</div>
</form>
My Ajax Input
function save()
{
var formData = new FormData($('#form')[0]);
$.ajax({
url : "<?php echo base_url('admin-spot/news/AddNews')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
redirect: true,
success: function(data){
if(data.status){
$('#modal_form').modal('hide');
}
else
{}
error: function (jqXHR, textStatus, errorThrown){
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
My Model
function Save($data)
{
$sql = $this->db->insert($this->table, $data);
return $sql;
}
hello guys,
when I want to input textarea with CKeditor , the string is Null , but when I delete class="CKeditor" in textarea the string successfully filled.
I have check in controller and database but it does not matter
Add this to your script
function save()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var formData = new FormData($('#form')[0]);
$.ajax({
....
});
}

bootstrap modal insert form submit won't reset to add another entry

I am using php mysql to insert to the database and that was working, however the bootstrap modal won't let me submitting another item. The button still says inserting and the last inserted data is still showing in the inputs.
I want to insert multiple times as this becomes part of a larger edit form.
This is put outside of the edit form submit button:
<div id="add_data_Modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add A New Item</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<input type="hidden" name="job_id" id="job_id" value="<?php echo $job_id;?>">
<input type="hidden" class="form-control" id="job_mat_qty" name="job_mat_qty" value="1" />
<div class="form-group">
<label for="job_mat_desc" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea class="form-control editors" id="job_mat_desc" name="job_mat_desc" autocomplete="off" placeholder="Enter item title and / or description" />
</textarea>
</div>
</div>
<div class="form-group">
<label for="job_mat_cost" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<div class="input-group input-group"> <span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" class="form-control calculate invoice_product_price txt" autocomplete="off" id="job_mat_cost" name="job_mat_cost" aria-describedby="sizing-addon1" placeholder="0.00" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10"> </div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="insert" id="selected" value="Insert" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
$(document).on('click', '.delete-rows', function(){
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this Item?")) {
$.ajax({
type: "POST",
url: "job_remove_material_new.php",
data: ({
id: id
}),
cache: false,
success: function(html) {
$(".delete_mem" + id).fadeOut('slow');
}
});
} else {
return false;
}
});
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
$(function () {
$(document).on("hidden.bs.modal", "#add_data_Modal", function () {
$('#insert_form')[0].reset();
});
});
}
});
Sorry I have no clue how to add this code correctly for this forum so please be kind....
Thanks
You should try like this
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
//$('#insert_form')[0].reset();
$('#insert_form input[type="text"],textarea').val(''); // here is change
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
In my case it will work successfully so I hope it will help you

405 (Method Not Allowed) in custom URL Route Laravel 5.2

I got stuck with my ajax POST request.
My URL looks like this localhost/product/list (if a row is clicked,it will redirect to page.edit through a request like this localhost/product/list/edit/{id} )
When localhost/product/list/edit/{id} receives the edit request the response shows an error like localhost/product/list/edit/update_list 405 (Method Not Allowed).
I am confused why the URL changes from localhost/product/list/edit/{id} to localhost/product/list/edit/update_list, I mean the variable /{id} is missing.
Console always marks this part in my AJAX edit.js as an error.
$.ajax({
type:"POST",
data: {
'id': id,
'judul': judulArtikel,
'isi': isiArtikel,
// --- till the end ---
}
});
Here is my load.js which loads data from a database.
<td><a id='"+result.data[count-1].id+"'' href='list/edit/"+result.data[count-1].id+"' class='glyphicon glyphicon-pencil'></a></td>
Here is my route.php.
Route::get('list/edit/{id}', 'Controller#list_to_edit');
Route::post('/update_list', 'ProductController#update_list');
Here is my controller.
public function list_to_edit($id){
$artikel = Artikel::where("id","=",$id)->get();
return view('page.edit',compact('artikel'));
}
Here is my edit.js.
$(document).ready(function(){
$('#isi_artikel').summernote({
height: 300,
minHeight: 400,
maxHeight: 400,
focus: true
});
$('#btn_submit').click(function(e){
e.preventDefault();
var isiArtikel = $('#isi_artikel').summernote('code');
var judulArtikel = $('#judul').val();
var deskripsiArtikel = $('#deskripsi').val();
var kategori = $('input[name="etype"]:checked').val();
if($('#inputpicture').val() == ""){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
}
})
$.ajax({
type:"POST",
data: {
'id' : id,
'judul' : judulArtikel,
'isi' : isiArtikel,
'kategori' : kategori,
'deskripsi' : deskripsiArtikel,
'image' : null
},
dataType: "json",
url: "update_list",
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf_token']").attr('content'));
},
success: function(result){
if(result){
window.location.href = "kelola";
}
},
error : function(jqXhr) {
var errors = jqXhr.responseJSON;
//console.log(jqXhr);
errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
$.each( errors , function( key, value ) {
errorsHtml += value[0] ;
//console.log(value[0]);
});
errorsHtml += "</div>";
$('.alerts').html("<div>gila lu</div>");
$('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
}
}, "json");
}else{
var ajax = function(imageData){
requestUploadArtikel(judulArtikel, isiArtikel, kategori, deskripsiArtikel, imageData);
}
imageupload($('#inputpicture').get(0), ajax);
}
});
function requestUploadArtikel(judul, isi, kategori, deskripsi, imageData){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
}
})
$.ajax({
type:"POST",
data: {
'id' : id,
'judul' : judul,
'isi' : isi,
'kategori' : kategori,
'deskripsi' : deskripsi,
'image' : imageData
},
dataType: "json",
url: "update_artikel",
success: function(result){
if(result){
window.location.href = "kelola";
}
},
error : function(jqXhr) {
var errors = jqXhr.responseJSON;
//console.log(jqXhr);
errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
$.each( errors , function( key, value ) {
errorsHtml += value[0] ;
//console.log(value[0]);
});
errorsHtml += "</div>";
$('.alerts').html("<div>gila lu</div>");
$('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
}
}, "json");
}
function imageupload(element, ajax){
console.log('testimageupload');
var elementId = element.id;
if(element.files && element.files[0]){
var file = element.files[0];
var validFileType = ".jpg, .png, .bmp";
var extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
$("#"+elementId+"-show").attr('src', "");
console.log(extension);
//validatefile
if(validFileType.toLowerCase().indexOf(extension)<0){
$("#"+elementId+"-alert").show();
$("#"+elementId+"-show")
.attr('style', '')
.css('height','auto')
return;
}
$("#"+elementId+"-alert").hide();
//showfile
var reader = new FileReader();
reader.onload = function(e){
ajax(e.target.result);
}
if (reader.readAsDataURL) {reader.readAsDataURL(element.files[0]);}
else if(reader.readAsDataurl) {reader.readAsDataurl(element.files[0]);}
else if(reader.readAsDataUrl) {reader.readAsDataUrl(element.files[0]);}
}
else{
console.log('else');
$(elementId+"-show").attr('src',"");
}
}
});
here's my edit.blade.php
#extends('layout.layout')
#section('css')
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
#stop
#section('script')
<script type="text/javascript" src="{{ asset('js/artikel/edit.js') }}"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
#stop
#section('content')
<!-- Main Content -->
<div class="container">
<div class="row">
<h1 class="text-center edittengah">Edit Artikel</h1>
<div class="alerts"></div>
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
#foreach ($artikel as $a_artikel)
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Judul Artikel</label>
<input type="text" class="form-control" placeholder="Judul Artikel" id="judul" required data-validation-required-message="Harap tuliskan judul artikel." value="{{$a_artikel->judul}}">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label for="inputpicture">Ganti Foto Artikel</label>
<input type="file" name="picture" class="" id="inputpicture">
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Deskripsi Artikel</label>
<textarea name="deskripsi" id="deskripsi" cols="70" rows="5" placeholder="Deskripsi Artikel">{{ $a_artikel->deskripsi }}</textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Isi</label>
<div id="isi_artikel">{!! $a_artikel->content !!}</div>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Jenis Artikel</label>
<?PHP if($a_artikel->kategori == "umum"){?>
<label><input class="CBumum" type="radio" name="etype" value="umum" checked="true"> Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
<?PHP }
elseif($a_artikel->kategori == "selfhelp"){
?>
<label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp" checked="true"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
<?php }
else{
?>
<label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites" checked="true"> Activities </label>
<?php }?>
</div>
</div>
<hr>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<input class="btn btn-success" id="btn_submit" type="submit">
#endforeach
</div>
</div>
</div>
</div>
</div>
#stop
Your help is needed. Thanks in advance.
OKay my bad knowledge in routes,,
my ajax url update :
"url" : "/update_list"
it must should be
"url" : window.location + "/update_list"
and my controller from :
Route::post('/update_list', 'Controller#update_post');
to
Route::post('kelola/list/{id}/update_list', 'Controller#update_post');
'kelola/list/{id}/update_list' refer to my baseUrl before ajax process URL

How to pass data from post to ajax in codeigniter

So i have table and trying to do C.R.U.D.
I make for edit form with modal. As my table populate inside of foreach i put my modal inside in table to get correct id of row.
This is my ajax function
$("#uin").click(function(){
var mydata = $("form#update-interview").serialize();
var id = $("#jsonid").val();
console.log(mydata); // it's only for test
$.ajax({
type: "POST",
url: "vacancy/interview/" + id , //process
data: { user_submission_token: $("#session_token").val(),mydata },
dataType: "json",
success: function(msg){
alert("Succeess");
$("#form-content").modal('hide'); //hide popup
},
error: function(){
alert("failure");
}
});
});
From this Ajax Submit im getting output like:
candidate_id=120&vacancy_id=48&stage=Interview&date=&candidate_id=120&vacancy_id=49&stage=Interview&date=&candidate_id=120&vacancy_id=53&stage=Interview&date=&candidate_id=120&vacancy_id=54&stage=Interview&date=&candidate_id=120
and this continues until last ID, so i need to get only 1 candidate_id ,vacancy_id and stage with date.
Its getting all of them because is inside in foreach but if i put my form outside of foreach then how i will get my row ID?
this is my function in controller
public function interview($i)
{
$type=$this->input->post();
$test= json_encode($data= array(
"status" => 1,
"candidate_id" => $this->input->post('candidate_id'),
"vacancy_id" => $this->input->post('vacancy_id'),
"date" => $this->input->post('date'),
"stage" => $type[3],
)
);
var_dump($test);
die();
$this->vacancies->update_interview($data, array("vacancy_id" => $i));
}
from this controller var_dump i got this output {"status":1,"candidate_id":false,"vacancy_id":false,"date":false,"stage":null}
seems my function is not correct also, can i get some advice?
and model side is just this
public function update_interview($i)
{
$this->db->insert("interviews", $i);
}
For any case this is my form its little-bit long
<!-- Update Interview-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<form class="no-error-margin" id="update-interview">
<div class="modal-content">
<div class="modal-body">
<div class="form-group">
<input type="hidden" name='candidate_id' value="<?= $candidate_id; ?>" />
<input type="hidden" name='vacancy_id' id="jsonid" value="<?= $row['id']; ?>" />
</div>
<div class="form-group">
<label class="control-label">Type:</label>
<select id="classinput" tabindex="1" name="stage" class="form-control required">
<option value="Interview">Interview</option>
<option value="Final Interview">Final Interview</option>
<option value="">Rejected</option>
</select>
</div>
<!-- Using DatePicker-->
<div class="date-form">
<div class="control-group">
<label class="control-label" style="margin: 0 30%;padding: 7px;">When The Interview Will Be?</label>
<div class="container">
<div class="row">
<div class='col-sm-6 col-md-offset-3'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input name="date" type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="uin" type="submit" data-dismiss="modal" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
</div>
</div>
<?php echo form_close();?>
</div>
</div>
<!-- End Interview-->
UPDATE:
Okay thanks to Niranjan N Raju
Now i'm getting just 1 result in POST and its correct which is looks like
candidate_id=126&vacancy_id=46&stage=Interview&date=12/03/2015+12:00+AM
So now how to insert this into database? Into candidate_id , vacancy_id , stage and date columns with their values?
this is wrong,
data: { user_submission_token: $("#session_token").val(),mydata },
It should be
data: { user_submission_token: $("#session_token").val(),mydata:mydata },
^ ^
data is always is passed as {key:value,key:value}
But you are passing only key.
$("#uin").click(function(){
var mydata = $("form#update-interview").serialize();
var id = $("#jsonid").val();
mydata.push({user_submission_token: $("#session_token").val()
});
$.ajax({
type: "POST",
url: "vacancy/interview/" + id ,
data: mydata,
dataType: "json",
success: function(msg){
alert("Succeess");
$("#form-content").modal('hide');
},
error: function(){
alert("failure");
}
});
});

Image upload not working with event.preventDefault() CodeIgniter

I have created a form in CodeIgniter for uploading an image.
The View file:
<form method="POST" action="<?php echo base_url().'promotions/add_item' ?>" enctype='multipart/form-data' class="form-horizontal" id="addItem">
<div class="form-group">
<label class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Image</label>
<div class="col-sm-9">
<input type="file" name="pro_image">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<textarea class="form-control" rows="3" name="description" placeholder="Description"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
</div>
</div>
</form>
The Ajax code:
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
var url = $(this).attr('action');
$.ajax({
url: url,
data: $("#addItem").serialize(),
type: $(this).attr('method')
}).done(function(data) {
$('#ret').html(data);
// window.location.reload();
$('#addItem')[0].reset();
});
event.preventDefault();
});
});
</script>
The Controller file:
<?php
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('description','Description','required');
var_dump($_FILES['pro_image']);
if ($this->form_validation->run() == FALSE) {
echo '<div class="alert alert-dismissable alert-danger"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><small>'. validation_errors().'</small></div>';
} else {
if ($_FILES['pro_image']['size'] > 0) {
$this->upload->initialize(array(
"upload_path" => './uploads/',
"overwrite" => FALSE,
"encrypt_name" => TRUE,
"remove_spaces" => TRUE,
"allowed_types" => "gif|jpg|png|jpeg",
));
if (!$this->upload->do_upload('pro_image')) {
echo 'Error :'. $this->upload->display_errors();
}
$data = $this->upload->data();
$img = $data['file_name'];
}
$title = $this->input->post('title');
$description = $this->input->post('description');
$this->promotions_model->add_item($title, $description,'uploads/'.$img);
}
Whenever I attempt to upload an image it always comes as null, but if I comment out the event.preventDefault(); line then upload an image, then it works fine. However, then the other functionality like validation and return messages fail to work properly.
Can any one please tell me what is issue with event.preventDefault()?
<script>
$(function(){
$( "#addItem" ).submit(function( event ) {
event.preventDefault();
var url = $(this).attr('action');
var data= new FormData($("#addItem")[0]);
$.ajax({
url: url,
contentType:false,
cache:false,
processData:false,
data: data,
type: 'POST' // POST/GET
success:function(data) {
$('#ret').html(data);
$('#addItem')[0].reset();
}
});
});
});
Add event.preventDefault(); in the begining sumbit listner

Categories