I am trying to do an ajax call in laravel. The ajax call logs my data how I want it, but keeps giving me the 500 error. I've read that you need to set the _token in the data field. But that doesn't work for me. So, I can log all the data, but ones I want to push it to the DB I keep getting this error.
Here's my code.
Script.js
$('.likeBtn').click(function(e){
e.preventDefault();
var userid=$(this).siblings('input[name=userID]');
console.log(userid[0].value);
var useridarticle=$(this).siblings('input[name=userIdFk]');
console.log(useridarticle[0].value);
var articleid=$(this).siblings('input[name=articleId]');
console.log(articleid[0].value);
var token=$(this).siblings('input[name=_token]');
console.log(token[0].value);
$.ajax({
url:"articles" ,
type: "post",
data: {'user_id':userid[0].value,
'article_id':articleid[0].value,
'user_id_fk':useridarticle[0].value,
'_token': token[0].value},
success: function(data){
console.log(data);
}
});
});
Controller.
if(Request::ajax()) {
$data = Input::all();
print_r($data);
}
My tokens are set in the header of my master.blade
<meta name="_token" content="{!! csrf_token() !!}"/>
And at the end of my master.blade
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
What am I not seeing? FYI, You might ask why I need does variables. I need them because I generate the same form in a foreach. This works fine for me, i get the data that I want so.
Related
I have an ajax function in jquery caling a cakephp4 function. The function doesnt work as it is giving a 403 forbidden error. The error is about headers but i cant find what I need to fix this exactly.
This code runs and it does get the var (alert verifies this). Nothing works ?
jquery
///
var freeassessmentid = "<?=$testid?>";
$.ajax({
url: "/freeassessments/freeasssesmenFinaltResult", //path is correct and it can be tested on its own
method: "POST",
dataType: "html",
data: { freeassessmentid:freeassessmentid },
success: function(response) {
//console.log(response);
$('#display-area').append(response); //no output
}
});
public function freeasssesmenFinaltResult($freeassessmentid=0)
{
//debug('test');
$html .= '<li class="listyle" style="height: auto;">hi<br/></li>';
$html .= '</ul>';
//no output
//https://stackoverflow.com/questions/36666256/jquery-ajax-call-results-in-error-status-403
The Ajax url should be:
url: "/freeassessments/freeasssesmen-finalt-result",
Use the kebab case for actions/methods in urls and the camel case for them in the controllers
You have to pass CSRF token in header during ajax call.
You can get CSRF token in many ways.
One of the simplest way is:
You can add bellow code to your head tag of parent layout or inside any of your template file.
<?php echo $this->Html->meta("csrfToken", $this->request->getAttribute("csrfToken")); ?>
At the time of ajax call you will have to get this csrf token and pass it to the ajax header.
Here is the example:
var token = $("meta[name='csrfToken']").attr("content");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: "path/to/controller/method",
method: "POST",
data: { pram1:val },
success: function(response) {
//console.log(response);
}
});
I hope it may help :)
I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });
i am trying to update my record with ajax and i don't know here i am doing wrong the code with my ajax:
$(document).ready(function(){
$('.edit_tag_button').click(function(){
var id = $(this).parent().find('.tag_id').val();
var formData = {
'tag_type' : $('#tag_type').val(),
'quantity' : $('#quantity').val(),
'number' : $('#number').val(),
'active' : $('#active').val(),
'issued' : $('#issued').val(),
};
$.ajax({
url: "{{url('')}}/update/tagslist/"+id,// Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
success: function(data) {
swal("Success!", "Great Job!! Your data has been updated","success");
location.reload();
},
error: function () {
swal("Error", "Look like We got some problem. Can you please refresh the page and try again" , "error");
}
});
});
});
and my controller code is:
public function updateTags(Request $request,$id)
{
$plan = Tags::where('id',$id);
$plan->update($request->all());
}
it says your values updated successfully but it does update my values any help plz
In Laravel POST method required CSRF protection.
Make sure to add meta with csrf token content
<meta name="_token" content="{{ csrf_token() }}">
And share it to ajax setup.
$.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}});
whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')
I have been picking away at this, though thought I would reach out for some advice, if I may, I am fairly new to AJAX.
Right, I am using the django framework, I post the data to the server, which works great, then receive some data back on the callback function, which works, though I want this to be in JSON format so I can populate a table. Currently it either renders in plain text or the browser asks me to download the json data, meaning somethings not quite catching on the $.get part. My code is:
#views.py
if request.POST:
est_show = login_a.test()
return HttpResponse(est_show, content_type='application/json')
<!--JQUERY/AJAX-->
<script type="text/javascript">
$(document).on("submit","#these_choices",function (event) {
var data_form = $('#these_choices').serialize();
if(data_form) {
$.ajax({
type: "POST",
url: "{% url Create_this %}",
data: {'test':'test','csrfmiddlewaretoken': '{{ csrf_token }}'},
cache:false,
success: function(){
jQuery(document).ready(function ($) {
$.get('{% url Create_this %}', function(data) {
alert(data[0]);
});});
},
error: function(){
alert('error !!!!');
}
});}
else {
alert('error elsewhere');
}
event.defaultPrevented(); //not running PreventDefault returns json using defaultPrevented returns json and doesnt render anything when this is blanked out...
return false;
});
</script>
It also seems the alert(data[0]) is being ran before the json data is being received in the browser. Any advice will be appreciated?
Many thanks
Try setting the mimetype in the HttpResponse to application/json. When you don't specify a dataType in the ajax request, JQuery automatically tries to infer it based on the mimetype of the response.
return HttpResponse(est_show, mimetype='application/json')
Alternatively, you can set the dataType to json to tell JQuery to expect json.