I have a form with a click event on submit button like this:
<div class="col-md-6 col-md-offset-4" id="submit_div">
<button type="submit" id="submit" class="btn btn-warning" onclick="entity();">
Update Entity
</button>
</div>
ajax:
$(document).ready(function() {
function entity() {
$.ajax({
url: 'entity/create/add',
type: 'post',
dataType: 'JSON',
success: function(data) {
$('#submit_div').html('<button type="button" class="btn.btn-success">Edit</button')
},
error: function(data) {
alert("Oh no!");
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content');
}
});
}
});
controller:
public function store(EntityRequestCreate $request)
{
$geoloc = new Geoloc;
$geoloc->lat = $request->input('lat');
$geoloc->lng = $request->input('lng');
$geoloc->slug = $request->input('name');
$geoloc->save();
$user_id = Auth::id();
$entity = new Entity;
$entity->name = $request->input('name');
$entity->type = $request->input('type');
$entity->email = $request->input('email');
$entity->tags = $request->input('tags');
$entity->_geoloc()->associate($geoloc);
$entity->save();
$entity_id = $entity->id;
$address = new Address;
$address->building_name = $request->input('building_name');
$address->address = $request->input('address');
$address->town = $request->input('town');
$address->postcode = $request->input('postcode');
$address->telephone = $request->input('telephone');
$address->entity_id = $entity_id;
$address->save();
$role = User::find($user_id);
$role->role = "2";
$role->save();
DB::table('entity_user')->insert(array('entity_id' => $entity_id, 'user_id' => $user_id));
$result = $geoloc->save();
$result2 = $entity->save();
$result3 = $address->save();
$result4 = $role->save();
if ($result && $result2 && $result3 && $result4) {
$data = $entity_id;
} else {
$data = 'error';
}
return response()->json(['results' => $data]);
}
route:
Route::post('entity/create/add', 'EntityController#store');
Everything seems to work, there are no errors but instead of a button from success(data) I get the actual response:
{
"results": 112
}
But I don't even know why it is happening can someone please help me?
form doesn't have any action and it looks like ajax is not being called?
Related
I have a script that should update a user's post without rebooting. But the form data, for some reason, is not transferred through the formData object, everywhere is null, except for those fields that are manually registered in the controller (id, user_id). What can be wrong?
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "PATCH",
data: formData,
success: function(data) {
console.log(data);
$("#textpostdata"+id).html($(data).find("#textpostdata"+id).html());
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
contentType: false,
processData: false,
});
});
And my controller
public function editPost(storeRequest $request, $id, $postId) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/' . Auth::user()->id . '/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
//return redirect()->back();
return $post;
}
Hello there
Hope you will be doing good.I want to download txt file generated on the fly from the controller of laravel i have search alot but could not find any solution.Please help out i will be very thankful.
Blade code with axios request
submitHandler:function(form,e){
var btn=document.querySelector("#BtnSubmit");
btn.style.display="none";var img=document.createElement("img");
img.setAttribute("src",base_url+'front/images/loading.gif');
var loader=document.querySelector("#loader");loader.appendChild(img);
var url="<?php echo route('database.export-txtProcess');?>";
var cur_url="<?php echo route('database.export-txt');?>";
//var tblExportSelect = $("#tblExportSelect").val();
var pushArray = [];
$.each($("#tblExportSelect option:selected"), function(){
pushArray.push($(this).data("id"));
});
var data = new FormData();
data.append('tblExportSelect',pushArray);
//$("#tblExportSelect").val(selected);
axios({
method: 'POST',
url: url,
data: data,
})
.then(function(res){
console.log(res);
})
e.preventDefault();
}
});
Controller Method
public function exportTxtProcess(Request $request){
/*dd($request->tblExportSelect);*/
$tables = explode(",", $request->tblExportSelect);
$destinationPath = public_path('/');
$result;
foreach ($tables as $table) {
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table."-".$today;
$fp = fopen($destinationPath . "$fileName.txt","wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table,$output);
fwrite($fp,$netResult);
}
$result = fclose($fp);
}
/*$arr = array(['Good' => true,'message' => 'Data has been successfully imported.'], 200);
echo json_encode($arr);*/
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$downloaded = response()->download($pathToFile)->deleteFileAfterSend();
}
}
I want to download when txt file which is created as above but instead of download it streaming in the console.
Thank in advance
You have to pass the headers. Most importantly you are not returning the reponse.
$headers = [
'Content-type' => 'text/plain',
'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
'Content-Length' => sizeof($content)
];
return response()->download($pathToFile, $fileName,$headers)->deleteFileAfterSend();
I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
Somehow it just doesnt upload the image to the folder. It goes so far as adding to the database (what model is all about) however no upload.
I hope to know what im doing rong. See my code bellow
The
HTML
<div class="dropzone infile dz-clickable" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" id="file" type="file" multiple />
</div>
</div>
JS
var myDropzone = new Dropzone("#my-dropzone", {
url: admin_url+'add_image/material',
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sending",function(file, xhr, formData){
file.token = Math.random().toString(36).substr(2,9);
formData.append("token",file.token);
formData.append("type", file.type);
formData.append("size", file.size);
});
this.on("complete", function (file) {
console.log(file);
});
this.on("successmultiple", function(file, response) {
console.log(file);
});
this.on("errormultiple", function(file, response) {
console.log(file);
});
this.on("removedfile",function(file){
var token = file.token;
$.ajax({
type:"post",
data:{token:token},
url: admin_url+'remove_image',
cache:false,
dataType: 'json',
success: function(res){
}
});
});
},
dictDefaultMessage: "<div class='drag-icon-cph'><i class='material-icons'>touch_app</i></div><h5>Plaats hier bestanden om te uploaden</h5>",
dictRemoveFile : "Bestand verwijderen"
});
PHP (Codeigniter)
public function add_image($type, $rel_id = 0){
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
$path = getcwd() . '/uploads/';
$tmpFilePath = $_FILES['file']['tmp_name'];
if (!empty($tmpFilePath) && $tmpFilePath != '') {
$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];
$extension = strtolower($extension);
$allowed_extensions = array(
'jpg',
'jpeg',
'png'
);
if (!in_array($extension, $allowed_extensions)) {
set_alert('warning', 'PHP blocked file extention');
return false;
}
$filename = uniqid(rand(), true).'.'.$extension;
$newFilePath = $path . '/' . $filename;
// Upload the file into the upload dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$config = array();
$config['image_library'] = 'gd2';
$config['source_image'] = $newFilePath;
$config['new_image'] = $filename;
$config['maintain_ratio'] = true;
$CI->load->library('image_lib', $config);
$CI->image_lib->initialize($config);
$CI->image_lib->resize();
$CI->image_lib->clear();
$data = array(
'rel_type' => $type,
'rel_id' => $rel_id,
'attachment_key' => $this->input->post('token'),
'file_name' => $filename,
'filetype' => $this->input->post('type'),
'size' => $this->input->post('size'),
'dateadded' => date('Y-m-d H:i:s')
);
$id = $this->back_model->add_image($data);
if($id != ''){
array_push($_SESSION['tmp_image'],$id);
}
unlink($newFilePath);
}
}
}
}
The folder uploads is created and for security i added a empty index.html file.
.htaccess is standard Codeigniter
My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced