My AJAX code is like below
$('select[id="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/cities',
type: "GET",
data: { id: 7},
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}else{
$('select[name="city"]').empty();
}
});
My route is like below
Route::get('/cities/{id}', 'LocationController#getSelectedCityajax');
My controller code is like below
public function getSelectedCityajax($id)
{
return response()->json([
'success'=>'get your data'
]);
}
But I am getting result like below
Error - 400: Bad Request
If your route is -Route::get('/cities/{id}', 'LocationController#getSelectedCityajax');
then ajax call should be-
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
$('select[id="state"]').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/cities/7',
type: "GET",
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}else{
$('select[name="city"]').empty();
}
});
and if u want send data by post request then route should be -
Route::post('/cities', 'LocationController#getSelectedCityajax');
AJAX Request would be -
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
})
$.ajax({
url: '/cities',
type: "post",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { id: 7},
success:function(data) {
$('select[name="city"]').empty();
$.each(data, function(key, value) {
$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
And controller code -
public function getSelectedCityajax(Request $request)
{
$id = $request->get('id');
return response()->json([
'success'=>'get your data'
]);
}
Related
Hi I'm new to Laravel and I'm having problem in passing the request properly in my controller which is a resource for update function I'm using Laravel 8. there is no error with the syntax it just return the request is empty. I paste my code for references.
my AJAX Request
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "PATCH",
data: {
'fullname' : 'albert'
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});
and here is controller
public function update(Request $request, $id)
{
return response()->json($request);
}
and here is my Route
Route::resource('companystructure', CompanyStructureController::class);
this is the return I receive from my controller
type: 'PATCH' does not exists on HTTP methods thus will not be recognized by Laravel.
Try this:
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "POST", /// UPDATE
data: {
'fullname' : 'albert',
'_method': 'PATCH', /// UPDATE
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});
I have this code, how can I pass a parameter to data.php (data.php?q=) so when user digits something I can filter
the data and retrieve just a subset of records?
var company;
$(document).ready(function() {
$('.select-ajax').multiselect({
maxHeight: 400,
buttonWidth: '100%',
includeSelectAllOption: true,
enableFiltering: true
});
$.ajax({
type: 'GET',
url: '/data.php',
dataType: 'json',
success: function(data) {
$.each(data, function (i, item) {
company = item.company;
$('.select-ajax').append('<option value="' + item.company + '">' + item.company + '</option>');
console.log(item)
});
$('.select-ajax').multiselect('rebuild');
},
error: function() {
alert('error loading items');
}
});
$('.select-ajax').trigger( 'change' );
});
</script>```
I works with ASP.net MVC and I have get "Error" from belowe my JavaScript code:
This is my AJAX jQuery code:
$(document).ready(function () {
var dataId;
$(".item2 .small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').prop('href', url);
$.ajax({
url: '/Carpet/CheckCarpet',
type: 'POST',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success == false)
$('#dateLink').hide();
else
$('#dateLink').show();
alert("Success");
},
error: function (errorThrown) {
alert("Error");
}
});
and this is a controller code:
[HttpPost]
public ActionResult CheckCarpet(int CarpetImageid)
{
bool DecorShow = false;
DecorShow = db.Images.Where(x => x.Id == CarpetImageid).FirstOrDefault().DecorTest;
return Json(new JsonData { Success= DecorShow });
}
what's the reason? Someone knows?
I found the solution.i change url to #Url.Action("CheckCarpet", "Carpet") and fixed.
$(".small-img").click(function () {
dataId = $(this).data("id");
var url = '#Url.Action("DecorationTest", "Carpet")' + "?Id=" + dataId + "&title=" + '#Url.ToFriendlyUrl(Model.Title.ToString())';
$('#dateLink').attr('href', url);
$.ajax({
url:'#Url.Action("CheckCarpet", "Carpet")',
type: 'Post',
dataType: 'Json',
data: '{"CarpetImageid":"' + dataId + '"}',
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.Success == false) {
$('#dateLink').hide();
$('.p2').hide();
}
else {
$('#dateLink').show();
$('.p2').show();
}
},
error: function (error) {
alert(error.d);
}
});
});
(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem
I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});