this is continue for Q before Orginal q
i'm trying to figure out how to pass Id to link (E>G http://localhost:1914/en/Events/Index/22) .
i was suggested to pass it view json results buti cantpass it back to my script file what i need is after user submit to pass the Id to a url and display the new posted item. (EG MyDomain/GolblizionCode/Controller/View/Id) .with what i got so far i have undefined instead if Id .(http://localhost:1914/EN/Events/Indexundefined )
Code: GetAddres.Js `
function GetLocation() {
var geocoder = new window.google.maps.Geocoder();
var street = document.getElementById('txtAddress').value;
var city = document.getElementById('txtCity').value;
var address = city + street;
console.log(address);
var labelLat = document.getElementById('Latitude');
var labellong = document.getElementById('longitude');
geocoder.geocode({ 'address': address },
function(results, status) {
if (status == window.google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log("Latitude: " + latitude + "\nLongitude: " + longitude); //Ok.
labelLat.value = latitude; //Ok.
labellong.value = longitude;
var form = $('#RestoForm')[0];
var formData = new FormData(form);
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
$.ajax({
url: 'Create',
type: 'POST',
contentType: false,
processData: false,
data: formData,
datatype: "JSON",
success: function(data) {
$('#RestoForm').html(data);
var id = data.id;
console.log(id);
window.location.href = baseUrl + '/Events/Index' + id;
console.log(baseUrl + '/Events/Index' + id);
}
});
error: function e(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
}
});
};`
controller:`
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("Gigform", viewModel);
}
[Authorize, HttpPost]
public JsonResult Create(LectureFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
//return View("Gigform", viewModel);
}
var lectureGig = new LectureGig
{
//Parmeters
};
_context.LectureGigs.Add(lectureGig);
_context.SaveChanges();
return Json(new {Id = lectureGig.Id});
}
}`
Thanks in advance
Try to add the allow get on the Json Response
return Json(new {Id = lectureGig.Id}, JsonRequestBehavior.AllowGet);
Hope this helps
return Json(new {Id = lectureGig.Id}, JsonRequestBehavior.AllowGet);
or you can use ViewBag
C#
ViewBag.MyIdBag = lectureGig.Id;
Razor
#ViewBag.MyIdBag
Related
I want to get the location from this JavaScript to the controller and store it in the database:
var currPosition;
navigator.geolocation.getCurrentPosition(function(position) {
updatePosition(position);
setInterval(function() {
var lat = currPosition.coords.latitude;
var lng = currPosition.coords.longitude;
jQuery.ajax({
type: "POST",
url: "myURL/location.php",
data: 'x=' + lat + '&y=' + lng,
cache: false
});
}, 1000);
}, errorCallback);
var watchID = navigator.geolocation.watchPosition(function(position) {
updatePosition(position);
});
function updatePosition(position) {
currPosition = position;
}
function errorCallback(error) {
var msg = "Can't get your location. Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
else if (error.code == 3)
msg += "TIMEOUT";
msg += ", msg = " + error.message;
alert(msg);
}
To send post with .ajax():
// ....
let formData = new FormData();
const lat = currPosition.coords.latitude;
const lng = currPosition.coords.longitude;
formData.append("x", lat);
formData.append("y", y lng;
$.ajax({
url: "myURL/location.php", // update this with you url
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'POST',
success: function(data){
const response = jQuery.parseJSON(data);
}
});
//....
To receive post data in codeigniter :
$x = $this->input->post('x');
$y = $this->input->post('y');
you just need to change uri parameter to codeginter route that you have
setInterval(function(){
....
url: "change this to codeigniter route url",
....
}, 1000);
then in the controller you just need to save those parameter,
class X extends CI_Controller{
function update_position(){
$x = $this->input->post('x');
$y = $this->input->post('y');
// then save it using model or query.
$this->model_name->insert([...])
}
}
Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object
You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.
objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}
In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';
this Q. is a continue of this question first qestion I have a form that I need to redirect to action with the form uploaded details (just like In stackoverflow) , but apparently because i'm using Ajax , it prevent it from redirect , I have tried to add my Ajax a redirect but I keep getting error and wrong Url . it should redirect from http://localhost:1914/En/VoosUp/Create To http://localhost:1914/En/events/Index/42 (E.G. Id number) the results i'm getting with what I wrote are in my Js Code
How can I redirect it to the correct url (Events/Index/Id )
Thanks in advance
Js
function GetLocation() {
var geocoder = new window.google.maps.Geocoder();
var street = document.getElementById('txtAddress').value;
var city = document.getElementById('txtCity').value;
var address = city + street;
console.log(address);
var labelLat = document.getElementById('Latitude');
var labellong = document.getElementById('longitude');
geocoder.geocode({ 'address': address },
function(results, status) {
if (status == window.google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log("Latitude: " + latitude + "\nLongitude: " + longitude); //Ok.
labelLat.value = latitude; //Ok.
labellong.value = longitude;
var form = $('#RestoForm')[0];
var formData = new FormData(form);
$.ajax({
url: 'Create',
type: 'POST',
contentType: false,
processData: false,
data: formData,
datatype: "html",
success: function(data) {
$('#RestoForm').html(data),
// window.location.href = '#Url.Content:("~/Events/Index")' + "Id";
//= A potentially dangerous Request.Path value was detected from the client (:).
// En/VoosUp/#Url.Content:("~/Events/Index")Id
window.location.href = '#Url.Action("~/Events/Index")';
// =The resource cannot be found >
//En/VoosUp/#Url.Action("Events/Index
}
});
error: function e(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
}
});
};`
Controller:
[Authorize]
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("Gigform", viewModel);
}
[Authorize, HttpPost]
public ActionResult Create(LectureFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View("Gigform", viewModel);
}
var lectureGig = new LectureGig
{
//Parameters
};
_context.LectureGigs.Add(lectureGig);
_context.SaveChanges();
// return this.RedirectToAction( "events", (c=>c.Index(lectureGig.Id));
return RedirectToAction("index", "Events", new { id = lectureGig.Id });
}
and the target
public ActionResult Index(int id)
{
var lecturegig = _context.LectureGigs.Include(g => g.Artist)
.Include(g => g.Genre)
.SingleOrDefault(g => g.Id == id);
if (lecturegig == null)
return HttpNotFound();
var viewmodel = new GigDetailViewModel { LectureGig = lecturegig };
return View("index", viewmodel);
}
This should do it if your JavaScript is in the cshtml:
var id = 1;
var url = '#Url.Action("Index", "Events")';
window.location.href = url + "/" + id;
Based on your description however it seems that you are trying to call this from a .js file which has no idea about MVC helpers so instead you can try something like this:
var id = 1;
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
window.location.href = baseUrl + '/Events/Index' + id;
To get the correct Id modify your action to return the Id e.g.
public JsonResult Create(LectureFormViewModel viewModel)
{
return Json(new { Id=lectureGig.Id });
}
then you can access this Id in JavaScript e.g.
success: function(data) {
var id = data.Id;
}
If it is in a cshtml file you can use the code
window.location.href = '#Url.Action("Index", "Events")'+ "?id=1";
If you are in js file
window.location.href='/Events/Index?id=1'
I am trying to access data from a method within a service which returns coordinates which I use to make an HTTP requests. I added my Leaflet code inside of my controller so I can access that lat,lng coordinates to make an API request to another API. Everything is working. The problem is when I try to pass this data to the controller it does not read the property "L.Control.Search". I also attempted to write an array and access it within the controller and it returned undefined.
app.service('mapService', (function($http,$q) {
//Coordinates
var fmCoordinates = {};
//Function to Request markets
var requestMarkets = function(lat,lng){
var defer = $q.defer();
var dataFromHttp = {};
var options = {
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://someurl?lat=" + lat + "&lng=" + lng
};
$http(options).then(function(result) {
dataFromHttp = result.data;
defer.resolve(dataFromHttp);
}, function(error){
defer.reject(error);
});
return defer.promise;
};
L.Control.Search = L.Control.extend({
_getLocation: function(key) { //extract latlng from _recordsCache
var latLong = this._recordsCache[key];
console.log("This is latlong:\n"+Object.keys(latLong));
fmCoordinates.lat = latLong.lat;
fmCoordinates.lng = latLong.lng;
console.log(fmCoordinates.lat,fmCoordinates.lng || "Nothing yet!");
var promise = requestMarkets(fmCoordinates.lat,fmCoordinates.lng);
promise.then(function(greeting) {
for(var property in greeting.results) {
console.log(property + "=" + greeting.results[property]);
};
console.log('Success: ' + greeting.results);
}, function(reason) {
console.log('Failed: ' + reason);
});
if( this._recordsCache.hasOwnProperty(key) )
return latLong;//then after use .loc attribute
else
return false;
},
L.Map.addInitHook(function () {
if (this.options.searchControl) {
this.searchControl = L.control.search(this.options.searchControl);
this.addControl(this.searchControl);
}
});
L.control.search = function (options) {
return new L.Control.Search(options);
};
}));
I think your promise code is off slightly. Try changing it to the following. Right now you're returning before the promise has been resolved.
var requestMarkets = function(lat,lng){
var defer = $q.defer();
var dataFromHttp = {};
var options = {
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://someurl?lat=" + lat + "&lng=" + lng
};
return $http(options).then(function(result) {
dataFromHttp = result.data;
defer.resolve(dataFromHttp);
return defer.promise;
}, function(error){
defer.reject(error);
return defer.promise;
});
};
Also in one place you have l.Control.Search and L.control.search in another.
I am working phonegap application. I want to send data image to server but i can not sent it.
function addSiteToServer() {
var cId = localStorage.getItem("cId");
var sname = $('#sitename').val();
var slat = $('#lat').val();
var slng = $('#lng').val();
var storedFieldId = JSON.parse(localStorage["field_id_arr"]);
var p = {};
for (var i = 0; i < storedFieldId.length; i++) {
var each_field = storedFieldId[i];
var val_each_field = $('#' + each_field).val();
p[each_field] = val_each_field;
console.log("p" + p);
}
var online = navigator.onLine;
if (online) {
var data = {
site: {
collection_id: cId,
name: sname,
lat: slat,
lng: slng,
properties: p
}
};
//function sending to server
$.ajax({
url: App.URL_SITE + cId + "/sites?auth_token=" + storeToken(),
type: "POST",
data: data,
enctype: 'multipart/form-data',
crossDomain: true,
datatype: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("data: " + data);
alert("successfully.");
},
}
Looks like you are using the normal method to send data/image to server which is not recommended by Phonegap/Cordova Framework.
I request you to replace your code with the following method which works as you expected,I also used local storage functionality to send values to server,
function sendDataToServer(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.some_text = localStorage.getItem("some_text");
params.some_id = localStorage.getItem("some_id");
params.someother_id = localStorage.getItem("someother_id");
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://example.co.uk/phonegap/receiveData.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode+"Response = " + r.response+"Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
function saveData(){
sendDataToServer(globalvariable.imageURI);
alert("Data Saved Successfully");
}
Hope this helps.