Opening new page passing parameters without showing them on the URL - javascript

I'm making a MVC C# Web App, and I began wondering whether you could open other pages that need parameters to function, without actually sending them through the URL, which is unsafe, and can lead to some user messing up another registry of the database.
My issue is though, I've never done such a thing, and I cannot find any example of code that does such a thing. The project is run with C# and JS, and the main things I've tried include:
-Doing so with Ajax:
First of all I have a button that calls for a function:
Link Text|
function openHorario(id, id_schedule, id_tool) {
alert(oid, id_schedule, id_tool);
$.ajax({
type: 'POST',
url: '/Schedules/actionEditStuff',
data: {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
},
async: 'false',
success: function (data) {
//???
}
});
}
I know there's a way to go to a new page with the success Ajax return, but... That also requires for you to send the parameters through URL.
Obviously, that didn't work, because what the action does in the controller is to return a view, not a page. So... I realized that my idea was not very smart, and moved onto somewhere else: Link, but those always end up having to send the parameters visibly through URL.
Is there any way at all to do this in a proper, clean manner?
Thank you!

#Layan - just to illustrate my comment above, - you could implement something along these lines:
your client side invokes via ajax
...
var data = {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
};
$.ajax({
url: '/Schedules/actionEditStuff',
type: "POST",
data: data,
contentType: 'application/json; charset=utf-8',
success: function (view) {
//load returned data into div? or popup?
}
, error: function (xhr, status, error) {
...
}
});
...
and your controller action
public ActionResult actionEditStuff(....parameters...)
{
...
...do your magic ...
return PartialView("~/Views/_PartialViewThatShowsSomething.cshtml", ...pass model...);
}

Related

Ajax post not sending data to c# API Controller

I am trying to use $.Ajax() function to post data after a triggered event to my controller, but the data is not being sent. If I change the same function to "GET" method instead of "POST", it sends the data correctly, so I guess it has something to do with the VS2019 ASP.NET web project configuration, but I cannot find what it is.
The front code I am using is as follows:
marker.on('click', function (ev) {
let id = ev.target.features.properties.id
$.ajax({
url: "/public/pushDocuments",
method: "POST",
data: {
id: id,
objectname: "Prueba2",
bucketkey: "Prueba2"
},
contentType: "JSON",
success: function (data) {
launchViewer(data.urn);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
and in the server side:
[HttpPost]
[Route("public/pushDocuments")]
public async Task<IActionResult> postDocument(string id, string objectname, string bucketkey)
{
//Code here
}
but, as I said, the server is not getting the information. Nevertheless, if I change the method to GET in the server and front, I do get the data I am sending, but it is not the correct way to do it, as the work I want to do inside the server function is to save some data to a database. I have done it multiple times in other project and works, but I cannot figure out why it is not working on this one.

JavaScript URL issue with Permalinks enabled

I am using the following JavaScript function to fetch the data using ajax call
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
It calls the following php file and works fine.
http://127.0.0.1/osclass/oc-content/themes/bender/ajax-test.php
But when I enable SEO friendly Permalinks in my CMS current page URL is appended in start of link and I get the following error in Chrome Console.
GET http://127.0.0.1/osclass/fashion-beauty/oc-content/themes/bender/ajax-test.php?name=Jhon 404 (Not Found)
Anybody tell me how to solve this issue?
The url you've provided in the ajax call is document relative. When you changed the server's url generation scheme, you also caused the url pointed at by the ajax call to change.
Adjust the ajax url, changing:
url: "oc-content/themes/bender/ajax-test.php",
To:
url: "/osclass/oc-content/themes/bender/ajax-test.php",
Why don't you make the URL server-relative? Something like this:
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "/osclass/oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
As you have not posted the php code. I would mention that any url directly navigated through addressbar of browser causes in the GET request and i can see you have a POST request in the ajax, so, it can't work.
Workaround would be to use $_REQUEST super globals at php end. $_REQUEST would work for $_GET/$_POST requests.

Call post on external Rest API with Ajax

I am new to angular, and I'm trying to make a call to a Rest API and get its response. My issue is that my JavaScript keeps getting stuck on the Ajax call. I'm not sure if it's the data I am sending or the syntax of the Ajax call. I tried to alert 'Hello world' and that worked, then I alerted the JSON array and that was formatted correctly, but when I do the Ajax post, I don't get any response at all.
Any insight would be nice, thank you.
test.html
<button onclick="myFunction()">Post it</button>
test.js
function myFunction() {
var postData = [{"logintype":"1","user":"Administrator","password":"12345","controlid":"999","host":"192.168.2.164"}
];
$.ajax({
url: '192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
};
You have specified a relative URL, where I think you intended to specify an absolute URL. If the current page URL is http://localhost/myapp/, and you request 192.168.2.164/isapi/rip.dll/rest/session, that URL is resolved as http://localhost/myapp/192.168.2.164/isapi/rip.dll/rest/session.
If 192.168.2.164 is the ip address of the server you are trying to hit (and not a directory relative to your current path on your server), you will need to add // to the beginning of the URL to make it absolute (well, schema-relative at least):
$.ajax({
url: '//192.168.2.164/isapi/rip.dll/rest/session',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( postData ),
success: function(){
alert('hello');
},
error: function(){
alert('error');
}
});
Your issue has nothing to do with angular. What I will refer you to is the angular docs description of how to do a POST request and a small example of the syntax taken from the docs.
Learn to use $http or something similar if you want to develop with angular. https://docs.angularjs.org/api/ng/service/$http
Small example:
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

CodeIgniter Access Controller from PHP Require

I am using codeigniter for my project and I am stuck trying to figure this out.
I have some javascript that needs to perform an AJAX call to fetch some results based on a dropdown value that was selected.
function fetchLines(){
$.ajax({
url: baseURL + "resources/ajax.php?node=fetchLines",
type: 'GET',
cache: false,
data: {
lineType: 'business'
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
In this AJAX file, I am trying to include my controller and then access the function within it.
<?php
define('BASEPATH', "AJAX");
require_once('../application/controllers/Project.php');
switch($_REQUEST['node']){
case 'fetchLines':
$objLines = new Project();
$objLines->fetchLines($_REQUEST['lineType']);
break;
}
?>
My CI Controller then has a private function in it which I am trying to call to get the data I need:
private function fetchLines($lineType){
$lines = $this->project_model->fetchLines($lineType);
return $lines;
}
My goal here is to have an AJAX file or controller (if needed) be used for all my AJAX calls. It needs to be able to access a controller and return data.
With the current code above, I am getting the error: Class 'CI_Controller' not found in <b>C:\xampp\htdocs\blueprint\application\controllers
\Project.php
Is there a better way to handle situations like this? I'm not an expert with OOP but some reading suggested something along these lines.
why you are not sending this request to the controller method instead ?
function fetchLines(){
$.ajax({
url: baseURL + "controller-name/method-name",
type: 'GET',
cache: false,
data: {lineType: 'business'},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
console.log(data);
}
});
}
NOTE and in controller you can access these values as
function method-name(){
echo $this->input->get('lineType');
}
Lets say my ajax file is in the controllers folder
And I want to re-use my controllers, i would do it like this :
$this->load->library('../controllers/your_controller');
$this->your_controller->_some_method($data);
Load the controller as library and used it like a library.
Hope this helps.
You should put the code that listens to AJAX call in a controller function only. The way you are trying to do is not a good practice at all.
If you want a method to be executed only if the request was an XHR i.e.AJAX request then use
if($this->input->is_ajax_request()){
//your code
}else{
redirect(base_url())
}

How to catch JSON result from ASP.NET MVC 4 Controller?

I'm trying to catch data from the AJAX POST, which I've sent via jQuery to controller endpoint of ASP.NET MVC, like this:
$("form#auth").submit(function() {
var login = $('input[id=login]').val();
var password = $('input[id=password]').val();
$.ajax({
url: "/Home/Auth",
type: "POST",
data: "Login=" + login + "&Password=" + password,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
success: function() {
}
});
I've tested the controller understads what I'm sending to him, but the main problem is with the returning the result for my jQuery function.
I'm returning the result from Controller like this:
http://ideone.com/hNkF3Z
But I don't understand why the server is returning a file for download:
If to open the file, the result is valid: {"Result":"failed"}
I know, that I didn't write a code in a success function in JavaScript, but I think server must not return a file download and also the debugger must stop at the breakpoint, which was defined on last scope } of success function.
What you're seeing is the default form submission. Because you don't prevent the default browser action, the form is still being posted as if the event handler wasn't even there.
Update your JavaScript to prevent the default browser behavior with e.preventDefault()
$("form#auth").submit(function(e) {
e.preventDefault();
/* rest of your code here. */
}

Categories

Resources