passing and retrieving variables in cakephp from javascript using GET METHOD - javascript

i know how to construct url parameters in javascript and i know how to extract it if im going to pass it to a php file.
However, here's the scenario, i am going to pass variables from javascript to a function. I have 2 textboxes and i can already get the values of these textboxes and store it to javascript variables:
var fname;
name = document.getElementById('fname');
var lname;
lname=document.getElementById('name');
now im stucked up on how i am going to construct it in a way that cakephp post method will be able to understand it. is it just the same with php like the code below?
var vars = "fname="+fname+"&lname="+lname;
here's my code:
if(window.XMLHttpRequest){
xmlVariable = new XMLHttpRequest();
}
else{
xmlVariable = new ActiveXObject("Microsoft","XMLHTTP");
}
xmlVariable.open("POST","save",true);
xmlVariable.send(vars);
"save" is actually a function in my cakephp where i wanna process the saving of "fname" and "lname" variables.
i need to do it in cakephp. Would there be any way?

Try with Params or data
Params variable is used to provide access to information about the current request.
public function save()
{
this->params['form']['lname'];
this->params['form']['fname'];
}
OR
Used to handle POST data sent from the FormHelper forms to the controller.
public function save()
{
this->data['lname'];
this->data['fname'];
}

Related

How to receive HTTP POST parameters on vue.js? [duplicate]

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

Accessing MVC server side variable in Javascript

I'm moving one of our web applications from Drupal to an ASP.net MVC Web Application.
One of the Drupal functions gets some data from a web service and converts it to a JS Array, as follows:
foreach ($xml_result->JobList->JobDetail as $job_detail) {
// dsm((array)$job_detail);
$open_job_details[] = array("east"=>(string)$job_detail->Easting,"north"=>(string)$job_detail->Northing, "duedate"=>(string)$job_detail->openDate);
}
//dsm($open_job_details);
$open_jobs_data = json_encode($open_job_details);
drupal_add_js(array('open_jobs' => array('open_newjobs' => $open_jobs_data)), 'setting');
In the Javascript file, it is accessed using;
var openJobsData = JSON.parse(Drupal.settings.open_jobs.open_newjobs);
Is there a simple way to access a server side variable in the JS file in .NET? I can call the web service and get the relevant data from the XML file but not sure how to access it in the JS file.
Thanks
You can use Strongly Typed view to create cshtml page
if you want to access JSON object
View1.cshtml
#model mvcApplication1.Models.model1
#{
var serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
var jsonModel = serializer.Serialize(Model);
}
var JsonData = #Html.Raw(jsonModel); // declare a javascript variable and use it
if you want to access server variable at cshtml page
just use # to access server-side variables
after getting the value you can use javascript variable in another js file
Declare your javascript variable outside
$(document).ready(function()
{}
or before using the variable
you can use that variable in Javascript file.

Access server side variable in javascript/jquery in asp.net

I am working on asp.net web forms application.I need to access datatable returning from database in javascript/jquery.
But problem is that I am not able to get value. I tried declaring it on top of class as well as as session but didn't work.
I am getting blank if I try to alert it.
Here is my code..
On page load.. there are nested methods which are being used to load data inside GridView. Now I want to get same data in client side as well so that I can use to show in on Google map..
On Page_load event my below is code to get data from database
this.gvGmap.DataSource = null;
GmapDataTable = GetDataTable("someparameter to get data from db");
Session["GmapDataTable"] = GmapDataTable;
this.gvGmap.DataSource = GmapDataTable;
this.gvGmap.DataBind();
Now I tried two different approach to get this data client side.. but it's blank
1st
var mJSVariable = <%:GmapDataTable %>;
alert(mJSVariable);
2nd session approach
var yourVariable = '<%= Session["GmapDataTable"] %>';
alert(yourVariable);
If you data is just linked with your current page and not huge then use viewstate instead of session this will not create much load on your server. Instead of accessing session directly in client side assign it to a property this will make your code more reuseable.You can searilize your data table.View State Vs session
Although using session you can do with the following way.
`public static DataTable GmapDataTableProperty
{
set { HttpContext.Current.Session["GmapDataTable"] = value; }
get
{
if (HttpContext.Current.Session["GmapDataTable"] != null)
{
return (DataTable)HttpContext.Current.Session["GmapDataTable"];
}
return null;
}
}
GmapDataTableProperty = GmapDataTable; `
Access it on client side like
var mJSVariable = <%= GmapDataTableProperty %
your approach via session is right, but you need to convert your session object into DataTable object, make sure your session variable is not null.
var myValue = '<%= ((System.Data.DataTable)Session["dt"]).Rows[0][0] %>';
alert(myValue);

Do Ajax calls and maintain class structure

Hello I am wondering what is the common method of structuring ajax and php?
I am doing a website/application which have a lot of ajax calls. Also I do have a class in php I use for my main php code for keeping track of the user.
When I do ajax calls with jquery to smaller php files I need to re-declare my object I have in other files. I want the object that I have in my "main" php file. What is a good method to get the same object? Right now I am using jquery to pass the values from a div element (which comes from the object previously).
I feel this is not the best practice. I want to do it structured.
Example: I store the user session in User.
I have a button a user can click to get some information about his data. For this I have a jquery ajax call which sends and retrieves data for display. In that php file I do have to redo everything again, even if I include the class file, because the object is declared elsewhere.
Example. User can create lists in this kind of way.
I have the main index file which includes this file of new User. This type of stuff.
$user = new User();
if($_SESSION["user_connected"])
{
$user_profile = $twitter->getUserProfile();
$displayname = $user_profile->displayName;
}
$user->username = $displayname;
// Also user has an array of lists
jQuery
$('#createlistform').submit(function(event)
{
var newlistname = $('#listname').val();
var createlistRequest = $.ajax(
{
url: "ajax/ajax_add_list.php",
dataType: "html",
type: "POST",
data: {
listname: newlistname
}
}
);
the ajax_add_list file ajax is calling below. Now what I do to get this work is sending the username through as a data parameter to the php file from picking it up by $('#username').text() then set a new user with that username. It is not in the example now... but you get the point I think.
include_once("../user.class.php");
$theUser = new User();
if(class_exists('User'))
{
echo "yes class exists";
$newlistname = $_POST['listname'];
$theUser->createList($newlistname);
}
I wish I could get the same User object that was defined in my index file. I don't wanna create a new one. Although if this is how people do it when they have ajax I'll do it. I just want to know how you usually go by when dealing with different files here and there with javascript getting data from various places, while still maintaining a good structure with class and object.

Set Session Variable In MVC View and DateTimePicker

How can i set a Session value in the MVC View from Javascript in a DateTimePicker?
I have this code:
if('#Session["Data"]'==""){
$('#datetimepicker').datepicker('setDate', startDate); #Session["Data"] = startDate;}
else { $('#datetimepicker').datepicker('setDate', '#Session["Data"]'); }
This code work fine but the code
#Session["Data"] = startDate;
not working. How can i save Data here?
Thank you to all
You're merging javascript and c# code.
You can't set the startDate (javascript) to Session (c#) because javascript runs on client side.
If startDate is equals to DateTime.Now it'll help you.
<script>
if('#Session["Data"]'===""){
$('#datetimepicker').datepicker('setDate', new Date());
#(Session["Data"] = DateTime.Now);
} else {
$('#datetimepicker').datepicker('setDate', '#Session["Data"]');
}
</script>
Your C# Code in your razor view gets executed in server. But your javascript code executes on client. So you cannot set a c# variable value inside your javascript like what you have in your question.
What you can do is make an ajax call to an endpoint and set the value in session there. So create an action method to handle the ajax call
[HttpPost]
public ActionResult SetDate(DateTime date)
{
// Set to session here
return Json( new { Status="Success"});
}
Now from your javascript code, use ajax to call this endpoint and pass the date value.
var startDate= "Read the date value here";
$.post("YourControllerName/SetDate", { date = startDate},function(r){
if(r.Status==="Success")
{
alert("Date is now in session")
}
});
You may consider using the Url.Action helper method to generate the path o the action method instead of hardcoding.

Categories

Resources