script for window.location.href error - javascript

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'

Related

How to get data from a JavaScript to controller and store it in the database

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([...])
}
}

pass id from controller to script after Post

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

How to stop redirect "Authorized redirect URIs" on Deny while log in with google authentication

I am using Google Authentication in Web Application and while log in with Google..if user click on "Deny" option..It still redirect to "Authorized redirect URIs" which i mentioned in Console Developers of google.
<script type="text/javascript">
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = // My Client Id;
var REDIRECT = 'http://localhost:49234/Account/GoogleSign';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
$(document).ready(function () {
login();
});
function login() {
debugger;
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
}
}, 5000);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function (responseText) {
//alert("Call")
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
// console.log(user);
IsAuthenicated(user.id, user);
$('#txtFirstName').val(user.name);
$('#txtEmail').val(user.email);
},
dataType: "jsonp"
});
}
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
function IsAuthenicated(GoogleId, user) { //This function call on text change.
$.ajax({
type: "POST",
url: "http://localhost:49233/AutoComplete.asmx/IsGoogleAuthenicated", // this for calling the web method function in cs code.
data: '{GoogleId: "' + GoogleId + '" }',// user name or email value
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
}
});
}
// function OnSuccess
function OnSuccess(response) {
//alert('s ' + response.d);
debugger;
var retval = response.d;
if (retval == '0') {
$('#txtFirstName').val(user.name);
$('#txtEmail').val(user.email);
$('#hdgmailId').val(user.id);
$('#hgverified').val(user.verified_email);
$('#hglocale').val(user.locale);
$('#hdgiven_name').val(user.given_name);
}
else {
window.open("http://localhost:49233/Dashboard.aspx?Id=1&number=" + response.d, "_self");
}
}
</script>
Can someone suggest better approach how to handle Deny option? And also if i have opened 2 gmail account in same browser then also it is not redirecting me to my application after click on "Allow" access.

Creating a jQuery plugin with getJSON inside the function

I am not sure if this is due to the fact that getJSON is asynchronous or not. I think that would be the most obvious reason, but I don't have a clear understanding of how that works. In my js file, I call the healthCheck method on the body element. Nothing happens. Is my getJSON callback function even getting called? I don't know.
I have uploaded the script on JSFiddle.
The code is also below:
var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
( function($) {
$.fn.healthCheck = function() {
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.getJSON(request, function(data) {
var result = new Object();
$.each(data, function(key, val) {
result.key = val;
if (val == false) {
this.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
this.append(key + " working. <br />");
}
});
});
return this;
};
}(jQuery));
Many thanks in advance. I hope my query is well placed. If anyone knows some good resources to get a better understanding of asynchronous methods in jQuery that would be greatly appreciated, also. I haven't found many that have been easy to follow yet.
Try 1) setting context of jQuery.ajax( url [, settings ] ) to this of $.fn.healthCheck ; 2) create reference to this object at $.each()
var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
(function($) {
$.fn.healthCheck = function() {
// set `this` object within `$.getJSON`
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.ajax({
url:request
, type:"GET"
, contentType: false
, context: this
, processData:false
}).then(function(data) {
// reference to `this` within `$.each()`
var that = this;
var result = new Object();
$.each(JSON.parse(data), function(key, val) {
result.key = val;
if (val == false) {
// `that` : `this`
that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
that.append(key + " working. <br />");
console.log("complete"); // notification
}
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown); // log errors
});
return this;
};
}(jQuery));
$("body").healthCheck();
See also How do I return the response from an asynchronous call?
var baseURL = "https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/62775b7420f8df6b3d83244270d26495e40a1e9d/a.json";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
(function($) {
$.fn.healthCheck = function() {
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = 123;// CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.ajax({
url:request
, type:"GET"
, contentType: false
, context: this
, processData:false
}).then(function(data) {
var that = this;
var result = new Object();
$.each(JSON.parse(data), function(key, val) {
result.key = val;
if (val == false) {
that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
that.append(key + " working. <br />");
console.log("complete"); // notification
}
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown); // log errors
});
return this;
};
}(jQuery));
$("body").healthCheck()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Ajax send image to server

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.

Categories

Resources