I have the following ajax code in my frontend.
var formData = $('#application-information-step-one').serialize();
var actionUrl = $('#application-information-step-one').attr('action');
$.ajax({
url: actionUrl,
type: 'POST',
data: formData,
success: function(data) {
var resp = JSON.stringify(data);
console.log(resp);
},
error: function(data) {
}
And following code to return json response from my controller if the request is ajax:
if ($request->ajax()) {
return response()->json([
'message' => 'Information saved sucessfully !'
],200)->headers('Content-Type', 'application/json');
}
But with the above code setup. Laravel returns HTML code of same page from where the request was made.
HTML page is rendered in preview section of network tab .
Can anyone suggest what am I missing here ?
Check for Ajax request is incorrect, otherwise the controller wouldn't have outputted HTML.
You can try several things:
use Illuminate\Support\Facades\Request; at the top of the file
replace request->ajax() with Request::wantsJson()
use request()->ajax()
Any of the above subject to your Laravel version.
More details here
Return JSON response from controller
if ($request->ajax()) {
return response()->json([
'status' => 'success',
'data' =>[],
'message' => 'Information saved successfully!'
], 200);
}
In AJAX success function code:
success: function (data) {
console.log(data.message);
},
and add to AJAX request object next parameters too
dataType: 'json',
contentType: false,
processData: false
Related
I am trying to make a file upload system on AWS based on laravel with ajax. I am talking about a resume parser system where i used the apilayer API to parse the CV from pdf to json.
I tried to make a file upload system where files are uploaded to aws (this works) and after i get the uploaded file url to send to API.
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:doc,docx,pdf|max:2048',
]);
$fileName = time() . '.' . $request->file->extension();
$path = $request->file->storeAs('file', $fileName, 's3');
CVupload::create(['name' => $fileName]);
$urlcv = Storage::disk('s3')->url($path);
return response()->json("$urlcv");
}
}
Everything is ok, but when the API is executed from the below code i receive the error:
Client error: POST https://api.apilayer.com/resume_parser/url?url=https://--.s3.eu-central-1.amazonaws.com/file/-- resulted in a 403 Forbidden response:{"message":"You cannot consume this service"}
I see that the request is POST, and i have to make a GET REQUEST. Maybe its an error in Ajax Script?
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#file-upload').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#file-input-error').text('');
$.ajax({
type: 'POST',
url: "{{ route('resume.store') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
$("#showResponseArea span").html(response); //you will paste your response msg to the
$.ajax({
type: 'GET',
url: "{{ route('resume.api') }}",
dataType: 'json',
data: {
'url': response,
}
})
}
},
error: function(response) {
$('#file-input-error').text(response.responseJSON.message);
}
});
});
</script>
I have been searching high and low for answers but I cant seem to find.
Trying to send file input to laravel controller via ajax but laravel controller can't seem to read the data at all
Following is my ajax code
let fd = new FormData();
fd.append('fwigNo' , $('#fwigNo').val());
fd.append('x' , 27);
formData = fd;
$('#submit').click(function(e) {
e.preventDefault();
url = url.replace(':vdrId', dataId);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT" ,
dataType: "json" ,
cache: false,
processData: false,
contentType:false,
url: url,
data: formData,
success: function(result) {
console.log(result)
},
});//end of ajax
})//end of submit
Following is my laravel controller
public function store($vdrId , Request $request)
{
dd($request->all());
}
I managed to send to form Data via ajax but when I dd($request->all()) , it shows empty
Please do advise
update:
Route shown in cmd
Thank you
in web.php route file,try use resource form method get request
I have just started codeigniter and I am stuck at sending employee ID to my controller.
Actually, I have a datatable which shows all the registered employees, and there is a button which get the ID of the employee of row clicked and send it to controller through ajax call but i am unable to receive it in my ajax call.
JS code
$('#viewAllEmployeeTable tbody').on('click', '.viewEmployeeDetail', function() {
var data = viewAllEmployeeTable.row($(this).parents('tr')).data();
console.log(data);
employeeID = data.employeeID;
alert(employeeID);
$.ajax({
url: "/ackamarackus/employee/viewEmployeeProfile",
type: "GET",
data: {
"employeeID": employeeID
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
Controller
public function viewEmployeeProfile() {
$name = $this->input->post('employeeID');
echo "INPUT";
echo $name;
die();
}
This is what ajax is sending : employeeID:1000
Can anyone tell me what I am doing here? I have already tried google and stack overflow link, but nothing solved my problem. Thanks
You cannot send field data with type: 'GET'
Change this to type:'POST' and this will solve your issue :)
You are sending employeeID as GET method and accessing it as POST in Your controller, change your type in ajax request to POST as follows
$('#viewAllEmployeeTable tbody').on('click', '.viewEmployeeDetail', function() {
var data = viewAllEmployeeTable.row($(this).parents('tr')).data();
console.log(data);
employeeID = data.employeeID;
alert(employeeID);
$.ajax({
url: "/ackamarackus/employee/viewEmployeeProfile",
type: "POST", //Your problem here
data: {
"employeeID": employeeID
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
Background :
this is a simple ajax request to fetch data from database, my query and server side code works just fine.
Problem :
When i put the GET URL in my browser it shows the correct JSON response, but firebug (Firefox extension) doesn't show any response, and the error message is logged.
alert('success'); doesn't show
$('#loadOrderDetails').click(function () {
var id = document.getElementById("order_id").value;
var dataString = 'order_id=' + id ;
alert(dataString);
$.ajax({
type: "GET",
url: "index.php?route=new/orders/GetOrder",
data: dataString,
cache: false,
dataType: 'json',
success: function (data) {
alert ('success');
// my code to show data in table..
},
error: function (req, status, err) {
console.log('something went wrong', status, err);
}
})
});
any suggestions?
thank you all, it seems that my problem was because of www , i solved it in server settings .
I want to send an ajax post request to a module named sampleTest in Drupal6.
I have tried some bits of codes but I do not know how to put the module url in the jquery ajax function.
<script type="text/javascript">
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/drupal/www/admin/build/modules/module/get/contact',
dataType: 'json',
data: "test",
success:function(data) {
alert("123");
},
complete: function(data){
alert("complete");
}
});
});
});
</script>
You can't send an AJAX request to a module as such, rather you implement a path in your module (using hook_menu()), provide a page callback for that path that outputs the AJAX response, and then call that path in your AJAX call. This is a very basic example:
function mymodule_menu() {
$items['ajax-test'] = array(
'access callback' => TRUE,
'page callback' => 'mymodule_ajax_callback',
'type' => MENU_CALLBACK
);
}
function mymodule_ajax_callback() {
$post_data = $_POST;
// Do something with the post data
$output = array('status' => 'OK');
// For Drupal 6
drupal_json($output);
exit();
// Or for Drupal 7, just in case you want to know
drupal_json_output($output);
drupal_exit();
}
Then your JS would look like this:
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: '/drupal/ajax-test',
dataType: 'json',
data: "test",
success:function(data) {
alert(data.status);
},
complete: function(data){
alert("complete")
}
});
});
});