Since One week i try to post 2 array from Js to my php controller by using Ajax but when i try to get it in my controller it is null so i don't know what to do.
This is my javascript function. It is based from a form when the user enter a departur and an arrival addresses. With this i use an api to geocoding it and i put it into two array coordonneeDepart ans coordonneeArrive but when i post it it don't work, my variable are null in my php i don't see why in when i console.log it in my js it is ok the coordinate are into my array !
If someone can help me it would be very kind ! I hope i have been clear !
$(document).ready(function() {
var coordoneesDepart=new Array(2);
var coordoneesArrive=new Array(2);
var connexion = $('.routeConnexion').data('routeController');
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
coordoneesDepart[0]= position.coords.latitude;
coordoneesDepart[1] = position.coords.longitude;
$.ajax({
url:"https://api-adresse.data.gouv.fr/reverse/?lon="+coordoneesDepart[1]+"&lat="+coordoneesDepart[0],
success: function (data){
document.getElementById("form_cp1").value= data.features[0].properties.postcode;
document.getElementById("form_adresse1").value=data.features[0].properties.name;
}
})
});
}
$("#form_cp1").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp1]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
var postcodes = [];
response($.map(data.features, function (item) {
// Ici on est obligé d'ajouter les CP dans un array pour ne pas avoir plusieurs fois le même
if ($.inArray(item.properties.postcode, postcodes) == -1) {
postcodes.push(item.properties.postcode);
return { label: item.properties.postcode + " - " + item.properties.city,
city: item.properties.city,
value: item.properties.postcode
};
}
}));
}
});
}
});
$("#form_adresse1").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp1]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
coordoneesDepart[0] =data.features[0].geometry.coordinates[1];
coordoneesDepart[1] =data.features[0].geometry.coordinates[0];
console.log(coordoneesDepart);
response($.map(data.features, function (item) {
return { label: item.properties.name, value: item.properties.name};
}));
}
});
}
});
$("#form_cp2").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp2]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
var postcodes = [];
response($.map(data.features, function (item) {
// Ici on est obligé d'ajouter les CP dans un array pour ne pas avoir plusieurs fois le même
if ($.inArray(item.properties.postcode, postcodes) == -1) {
postcodes.push(item.properties.postcode);
return { label: item.properties.postcode + " - " + item.properties.city,
city: item.properties.city,
value: item.properties.postcode
};
}
}));
}
});
}
});
$("#form_adresse2").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://api-adresse.data.gouv.fr/search/?postcode="+$("input[name='form[cp2]']").val(),
data: { q: request.term },
dataType: "json",
success: function (data) {
coordoneesArrive[0] =data.features[0].geometry.coordinates[1];
coordoneesArrive[1] =data.features[0].geometry.coordinates[0];
console.log(coordoneesArrive);
response($.map(data.features, function (item) {
return { label: item.properties.name, value: item.properties.name};
}));
}
});
}
});
$.ajax({
method:"POST",
url:connexion,
contentType: "application/json",
data: JSON.stringify({
depart: coordoneesDepart,
arrive: coordoneesArrive,
}),
})
});
here it is my controller
/**
* #Route("/connexion", name="app_login")
*/
public function login(Request $request, AuthenticationUtils $authenticationUtils, SessionInterface $session, EntityManagerInterface $entityManager): Response
{
$user=$this->getUser();
$form = $this->createForm(LoginType::class);
$trajet = $session->get('trajet');
$depart = $request->request->get('depart');
dump($depart);
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
if($user!==NULL){
$id=$user->getId();
$trajet->setUserId($id);
$entityManager->persist($trajet);
$entityManager->flush();
}
dump($trajet);
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'form' => $form->createView(),
]);
}
It seems that you send json data, then you can get them by doing :
$data = file_get_contents('php://input');
Related
Im getting the following error on my Ajax post back {"readyState":0,"status":0,"statusText":"error"}
on my first ajax call but the second one returns data I want.
My C# method (UserSelect) JsonResults shows the data when I put break point
My C# code :
public IActionResult OnPostAreaSelect(string Id)
{
//Generating list for Areas
Guid ModelId = new Guid(Id);
List<ModelArea> modelAreas = _context.ModelArea.Distinct()
.Where(w => w.ModelId == ModelId).OrderBy(o => o.AreaColumn.Name).Include(i => i.AreaColumn).ToList();
return new JsonResult(modelAreas);
}
public IActionResult OnPostUserSelect(string Id)
{
//Generating list for Users
Guid ModelId = new Guid(Id);
List<UserModel> userModels = _context.UserModel
.Where(w => w.ModelId == ModelId).OrderBy(o => o.User.FullName)
.Include(i => i.User)
.ToList();
return new JsonResult(userModels);
}
My JavaScript :
<script type="text/javascript">
$(document).ready(function () {
$("#RepfocusModelDropdown").change(function () {
var Id = $(this).val();
if (Id != null) {
$.ajax({
async: true,
type: "POST",
url: "./Create?handler=UserSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
crossDomain: true,
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
$.ajax({
type: "POST",
url: "./Create?handler=AreaSelect",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
Id: Id
},
dataType: "json",
success: function (response) {
alert(JSON.stringify(response));
},
error: function (response) {
alert(JSON.stringify(response));
}
});
}
})
})
The second ajax call on my script works fine only the first one returns the error
How can I solve the error
When you work with EntityFramework (or other ORM) there may be problems with serialization because an entity could have some circular references. To avoid this problem a solution is to set serialization settings:
services.AddMvc().AddJsonOptions(opt => {
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
or:
Newtonsoft.Json.JsonConvert.DefaultSettings = () => new Newtonsoft.Json.JsonSerializerSettings {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
I try to send two arrays to the controller, each array from a different class. But all I get is alert with an error message. What am I doing wrong? When I send only one array in ajax data, it is obtained fine in the first array of the controller.
my code js:
$("#Button2").click(function () {
var dict = new Array();
$(":checkbox").each(function () {
if ($(this).prop("checked")== true) {
var key = this.name
if ($("input[name = 'r" + key + "']").length) {
dict.push({
Code: key,
Reccomendation: $("input[name = 'r" + key + "']").prop("value"),
});
}
else{
dict.push({
Code: key,
Reccomendation: $(this).prop("value"),
});
}
}
}) //end function each
var dict2 = new Array();
dict2.push({
Mentioned: $("#yesno").val(),
FollowUp: $("#Follo").val(),
UpdateCode:5
})
$.ajax({
type: 'POST',
url: "#Url.Action("SavevisitSummary")",
traditional: true,
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: { 'a': JSON.stringify(dict), 'b': JSON.stringify(dict2) },
success: function () {
alert("sucssec")
},
error:function(){
alert("error")
}
})
})
controller looks like:
public ActionResult SavevisitSummary(Reccomendations[] a, Summary[] b) { }
I am trying to get a List<Cities> using autocomplete from a web service. The list is successfully returned to the function but the return assignment is not right
I am using console.log to see returned results and this is what I get:
For console.log(itemList) I get:
[Object, Object, Object]
0:Object
CityId: 7932
CityName: "BADGERYS CREEK"
__type: "Cities"
__proto__: Object
1: Object
CityId: 7933
CityName: "BALGOWLAH HEIGHTS"
__type: "Cities"
__proto__: Object
2: Object
CityId: 7934
CityName: "BALMAIN EAST"
__type: "Cities"
__proto__: Objectlength: 3
__proto__: Array[0]
....
To be able to read the reply from the web-service I have to loop the result. I need to do some thing like this but don't know what is the correct syntax:
$("#txtDeliveryCity").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SfWebService.asmx/GetCitiesByPrefix",
dataType: "json",
data: "{'prefixText' :" + "'" + request.term + "'}"
success: function (data) {
response($.map(data, function (itemList) {
var listCityName = [];
var listCityId = [];
var counter = 0;
for (var i = 0; i < itemList.length; i++) {
listCityName[i] = itemList[i].CityName;
listCityId[i] = itemList[i].CityId;
}
// ------ This is not right:
return { label: listCityName, value: listCityId };
}));
}
});
Server side:
public class Cities
{
public string CityName { get; set; }
public int CityId { get; set; }
{
[WebMethod]
public List<Cities> GetCitiesByPrefix(string prefixText)
{
var service = new Cities();
var cities = service.GetCityByPrefix(prefixText);
return cities;
}
Use the below code if you are facing issues in rendering the text and value field.
$("#elementID")
.bind("blur", function(event) {
var currentText = $(this).html();
if (currentText === undefined || currentText === "") {
this.innerHTML = this.value = "";
}
}).autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: "your url",
data: {},cache: false,type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(datas) {response(datas.d);},
error: function(error) {alert(error.responseText);}
});
},
focus: function(event, ui) {
$(this).html(ui.item.CityName);
return false;
},
select: function(event, ui) {
$(this).html(ui.item.CityName);
$(this).attr("value", ui.item.CityId);
}
}).autocomplete("instance")._renderItem = function(ul, value) {
return $("<li></li>").data("item.autocomplete", value).append('<span value=' + value.CityId + '>' + value.CityName + '</span>').appendTo(ul);
};
this will handle all requirements for Autocomplete e.g. Press of downarrow,uparrow and enter for selection.
Hope this helps :)
I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
I want to create a function to simplify configuration of jQuery UI AutoComplete. Here is my function code:
(function($) {
$.fn.myAutocomplete = function() {
var cache = {};
var dataUrl = args.dataUrl;
var dataSend = args.dataItem;
$.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
$.ajax({
url: dataUrl,
dataType: "json",
type: "POST",
data: dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
}
}) (jQuery);
but when I'm using this function like:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
It's give me an error:
Uncaught ReferenceError: request is not defined
Perhaps the error is referring to request.term in
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { term: request.term, category: $("input#category").val() }
});
Sorry for the trouble, I'm not adept at using jquery. Here's the final working code.
(function($) {
$.fn.myAutocomplete = function(opt) {
var cache = {};
this.autocomplete({
source: function(request, response) {
if (cache.term == request.term && cache.content) {
response(cache.content);
}
if (new RegExp(cache.term).test(request.term) && cache.content && cache.content.length < 13) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(cache.content, function(value) {
return matcher.test(value.value)
}));
}
opt.dataSend.term = request.term;
$.ajax({
url: opt.dataUrl,
dataType: "json",
type: "POST",
data: opt.dataSend,
success: function(data) {
cache.term = request.term;
cache.content = data;
response(data);
}
});
},
minLength: 2,
});
return this;
}
}) (jQuery);
To use this function just write code like this:
$("input#tag").myAutocomplete({
dataUrl: "/auto_complete/tag",
dataSend: { category: $("input#category").val() }
});
Thanks Jeffery To for sharing with me to solve this problem.. ^_^