Ajax form data passing to API - ajax

Below code not going to succeed, it is showing failure message.. anybody can help
$.ajax({
type: 'GET',
url: 'xyz.com/form_api.php',
data: {
name: 'John',
email: '123333',
mobile: 'deep#gmail.com',
message: 'Test'
},
success: function(response) {
console.log(response);
$('#contact_form #contact_results2').html('Success');
},
error: function(errorThrown) {
console.log(errorThrown);
$('#contact_form #contact_results2').html('failed');
}
});

Try this code:
$.ajax({
type: 'GET',
url: 'xyz.com/form_api.php',
data: { 'name': 'John', 'email': 'deep#gmail.com', 'mobile': '123333', 'message': 'Test'
},
success: function(response)
{
console.log( response );
$("#contact_form #contact_results2").html("Success");
},
error: function(errorThrown)
{
console.log( errorThrown );
$("#contact_form #contact_results2").html("failed");
},
});

Related

Bad Request in AJAX

I am trying to develop a WordPress plugin. I am getting Bad Request from below AJAX code.
// On change division
$('body').on( 'change', '.division', function() {
$.ajax({
type: "POST",
url:localData.statesurl,
data:{
division: $(this).val(),
action: 'division_to_district_ajax'
},
success:function(rss){
alert(rss);
$('.district').empty();
var $opt = '';
$.each( JSON.parse(rss), function(key, value) {
$opt += '<option value="'+key+'">'+value+'</option>';
});
$('.district').append($opt);
},
error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); },
dataType: "json",
contentType: "application/json"
});
});
Could anyone say why I am getting Bad Request ?
Try like this
add_action( 'wp_ajax_division_to_district_ajax', 'division_to_district_ajax_function');
add_action( 'wp_ajax_nopriv_division_to_district_ajax', 'division_to_district_ajax_function');
function division_to_district_ajax_function(){
$myArr = array(
'response' => 'xyz'
);
$myJSON = json_encode($myArr);
echo $myJSON;
die();
}
// On change division
jQuery('body').on( 'change', '.division', function() {
jQuery.ajax({
url: '<?php echo admin_url( 'admin-ajax.php');?>',
type: "POST",
data: {'action': 'division_to_district_ajax', division: jQuery(this).val()},
cache: false,
dataType: 'json',
beforeSend: function(){
},
complete: function(){
},
success: function (response) {
console.log($response);
}
});
});

CSRF token error? on laravel Symfony\\Component\\HttpKernel\\Exception\\HttpException

first was ok. second got error
I use the ajax function on javascript page in laravel
If I initiate the function once it work well
But when I start the function 2 or 3 times in short time I got the error
"exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
"file": "D:\\AppServ\\www\\come\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
I search the error message . The result is the csfr issue.
But how can I fix the error?
I have already have the
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
The question is not on the first time . It's on the second or third times.
Code
$('.findNews_geography').autocomplete({
source: function(request, response) {
var findtable=$('.findtable_num').val();
var terms=request.term;
console.log("findtable="+findtable+";term="+terms);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "findNews_geography",
dataType: "json",
type: "post",
data: {
findtable : findtable,
term : terms,
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("findNews_geography ajax error="+xhr.responseText);
console.log("findNews_geography xhr.status="+xhr.status+";thrownError="+thrownError);
},
success: function(data) {
console.log("see request="+data);
response( $.map( data, function( item ) {
return {
label: item.place,
}
}));
} //success end
}); //ajax end
}, //source end
minLength: 0,
}); //autocomplete end
$(".findNews_geography").focus(function () {
//if (this.value == "") {
console.log("findNews_geography get focus");
if($('.findtable_num').val()){
$(this).autocomplete("search");
}// };
});
$('.findNews_geography').autocomplete({
source: function(request, response) {
var findtable=$('.findtable_num').val();
var terms=request.term;
console.log("findtable="+findtable+";term="+terms);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "findNews_geography",
dataType: "json",
type: "post",
data: {
findtable : findtable,
term : terms,
_token: $('meta[name="csrf-token"]').attr('content')
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("findNews_geography ajax error="+xhr.responseText);
console.log("findNews_geography xhr.status="+xhr.status+";thrownError="+thrownError);
},
success: function(data) {
console.log("see request="+data);
response( $.map( data, function( item ) {
return {
label: item.place,
}
}));
} //success end
}); //ajax end
}, //source end
minLength: 0,
}); //autocomplete end
Try to send the csrf token in your ajax request as data
data: {
findtable : findtable,
term : terms,
_token: $('meta[name="csrf-token"]').attr('content')
},
Hope this helps

Mvc autocomplete ajax

Try to:
$(document).ready(function () {
$('#cityName').autocomplete({
source: function(request,response) {
$.ajax({
type: 'POST',
url: '#Url.Action("Search", "City")',
dataType: 'json',
data: { name: request.term } ,
success: function (data) {
response($.map(data, function (item) {
alert(JSON.stringify(data));
alert(JSON.stringify(item.name));
return {
name: item.name,
label: item.name
}
}));
}
})
},
messages: {
noResults: "", results: ""
}
})
})
In alert(JSON.stringify(data)) got this: {"items":["Boston","Berlin"]}.
In alert(JSON.stringify(item.name)) got this: undefined.
Question: how do it (item.name) works?
You have to just return array of strings:
$(document).ready(function () {
$('#cityName').autocomplete({
source: function(request,response) {
$.ajax({
type: 'POST',
url: '#Url.Action("Search", "City")',
dataType: 'json',
data: { name: request.term } ,
success: function (data) {
response(data.items);
}
})
},
messages: {
noResults: "", results: ""
}
})
})

Can not pass value from Ajax to controller

My AJAX:
$.ajax({
url: '{{ URL::to('dashboard') }}',
type: 'GET',
data: { cid: val },
dataType:'JSON',
success: function(result) {
},
error: function(){
$('#status-msg').addClass('alert alert-danger');
$('#status-msg').text('Fejl!!');
}
});
My Route:
My Controller:
public function dashboard(){
if (Request::ajax()){
$cid = Input::get('cid');
var_dump(json_encode($cid));
} else {
echo "XX";
}
}
The cid is not passing to controller, the request AJAX is not working.
have you try change your ajax type to POST ?
$.ajax({
url: '{{ URL::to("yourURL") }}',
type:'POST',
data:"cid="+$(this).val()+"&_token=" + $("input[name=_token]").val(),
dataType:'JSON',
success:function(result){
},
error: function() {
}
});
Edit:
try to pass _token if you use {{Form::open}}.
hope this will help.
Try this:
$.ajax({
url: '<?php echo base_url() ?>index.php/contorller_name/method_name',
type: 'POST',
data: { cid: val },
dataType:'JSON',
success: function(result) {},
error: function() {
$('#status-msg').addClass('alert alert-danger');
$('#status-msg').text('Fejl!!');
}
});

How can I get imgur.com album images using ajax request

I used this code :
(function($){
var albumID = 'NNbeO';
var albumAPI = "https://api.imgur.com/3/album/" + albumID + "/images";
$.ajax({
url: albumAPI,
headers:{
'Authorization':'xxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
},
type: 'GET',
dataType: 'json',
success: function(data) {
alert(data.data[0].link);
},
error: function() { console.log("ERRORZ"); }
});
})(jQuery);
But I got this error :
{
"data": {
"error": "Malformed auth header",
"request": "\/3\/album\/NNbeO\/images",
"method": "GET"
},
"success": false,
"status": 403
}
I got my solution. It works fine now. Below is my working code. It's problem was, I've not added Client-ID text with Authorization headers.:
(function($){
var albumID = 'NNbeO';
var albumAPI = "https://api.imgur.com/3/album/" + albumID + "/images";
$.ajax({
url: albumAPI,
headers:{
'Authorization':'Client-ID xxxxxxxxxxxxx'
},
type: 'GET',
dataType: 'json',
success: function(data) {
alert(data.data[0].link);
},
error: function() { console.log("ERRORZ"); }
});
})(jQuery);

Resources