JS $.get or $.getScript pass data to file - javascript

I want to pass data to the js file. however cant get is to work.
js='article.js';
function loadjs(js){
$.get(js,{ name: "test" });
}
article.js
alert(name);
if i do alert('test'); i get a response from the file so i know it works.
also cant use globals.
is there a simple way to send the data to the file and show it?
EDIT to clarify
(yes i can use angelar but i dont)
Onload it triggers 'pagina' with all short of variables. (its dynamic).
all the 'php/html' files are loaded.
and you get what you can see in the link. example
hoverever when i click on a row i want function pagina(); to load the content of the row so far so good. however to show the data that i want. I want to send a ID to the JS file and use a $.post (php) in the JS file to get data json. if i set a ID in $.post id=1 directly its works.
so to not let it be more confusing. i want to send a id to a js file JS $.get or $.getScript.
function pagina(menu,frame,vars,crum,js,togglezoeken,voorwaarden){
'use strict';
if(!menu){$('#frame').show();}
if(menu){
$('#loader-zoeken').hide();
$('#loader-bijwerken').hide();
$('#loader-pagina').show();
$('#menu').hide();
$('#frame').empty();
$('#menu').load(menu+vars,{noncache: new Date().getTime()}, function() {$('#menu').foundation();});}
if(crum==1){$('#breadcrumbs').load('/opbouw/frames/breadcrumbs.php?'+vars,{noncache: new Date().getTime()}, function() {});}
$('#frame').load(frame+vars+'&crum='+crum,{noncache: new Date().getTime()}, function() {
if(togglezoeken){$('#uitgebreidzoeken').toggle();}
if(crum==1){$('#breadcrumbs').show();}else{$('#breadcrumbs').hide();}
if(js){
$.get( js,{ name: "test" });
}
else{
$('#loader-pagina').hide();
$('#menu').show();
$('#frame').show();
}
//if(voorwaarden==1){popup('/opbouw/frames/voorwaarden.php','','/opbouw/js/voorwaarden.js');}
$('#frame').foundation();
});
}

You can't do it that way. $.get is used for AJAX/HTTP(s) requests and your file in that way won't accept the data sent to it.
To achive this you have to use a server-side endpoint on your article.js.
Lets say:
function loadjs( js ) {
$.get(js, { name: "test" });
}
And you make a call of loadjs function:
loadjs('article.js');
On your server you have to have an server-side endpoint directing to a request: /article.js:
You can achieve this by using PHP or express for node.js:
router.get('article.js', function(req, res, next) {
res.json( req.query.data );
});
Or in PHP (note in Apache you have to use mod_rewrite and enable it with .htaccess or in your virtual host configuration):
$req = $_SERVER['REQUEST_URI'];
if($req == 'article.js') {
echo json_encode(array('data' => $_GET['data']));
exit(0); // end the script here
}
In either way used from above you have effectivelly sent a data to your script / endpoint and you can handle it further.
Although your loadjs function just sends a request and doesn't handle a response, you can do the following with a callback function in $.get:
$.get(js, { name: "test" }, function(data) {
alert(data); // you will alert the data from the JSON response
});
Sadly, you haven't described what you actually need and this is as far as I can help you with so far.

Related

How can I access Laravel Helper from Javascript?

I have a Laravel web app and want to access my Laravel Helper from any .js file.
In normally I accessed helper from script in blade.php file like this:-
<script>
function getSiteSettings() {
return JSON.parse('<?php echo json_encode(Helper::getSettings()) ?>');
}
</script>
But I want to access this from my script.js file. Is it possible?
I have tried with localStorage and get it very easily but problem is, in site settings have some secured data.
And if possible to hide localStorage data then my problem will be solved.
I found the answer. Basically, there is no direct way to write PHP code in the .js file. Here is 3 short way to get PHP/Laravel variable or Laravel Helper.
Solution 1. Call an ajax and get the return the value from js and use it as needed.
$(function() {
// ajax call
});
Solution 2. Any Laravel Helper/Var can be accessible from a blade file, like this:
<script>
let name = "{{ \Helper::get_name() }}";
</script>
and use this name anywhere in js.
Solution 3. The last and best way which I have been using is:
Add the external script in the blade and add a getter and setter method into the script so that you can set the value from the blade file inside the js.
// in external/script.js script
var GetLaravelHelper = function () {
let options = {
name_from_laravel : ''
}
return {
init: function(){
// code for on load
},
set_options: function(data){
Object.assign( options, data );
},
get_options: function(){
return options;
}
}
}();
window.GetLaravelHelper = GetLaravelHelper; // You can get acces this GetLaravelHelper into balde file where you imort this js
document.onload(function(){
GetLaravelHelper.init();
})
Then in blade, you can set any value into the Object like this:
<script src="external/script.js"></script>
<script>
GetLaravelHelper.set_options({
name_from_laravel: "{{ config('app.name') }}", // or anything from laravel/php
})
</script>
Hope it will help you a lot. Happy Coding <3
I think your best bet is to do what you're doing right now.
Or, Create a resource endpoint that can return JSON of these settings on page load in your script.js file:
// script.js
document.addEventListener("DOMContentLoaded", function() {
// make an ajax request here and load your setting in a js variable
});
// if using jquery
$(function() {
// make an $.ajax request here and load your setting in a js
})
The easiest solution will be call an api using Ajax or Axios(is using vue) inside the getSiteSettings function and in the response of the api you return the data.

How to pass resource from php to javascript

So I have three different separate files:
functions.php (all functions for the database)
main.html (my main program)
main.js (all javascript functions)
Now, I want to call a function in PHP through AJAX. To do that, I need to pass $conn.
$conn = sqlsrv_connect($serverName, $connectionInfo);
It's a resource, so I can't use json_encode.
The way I set the everything up now is that the php-file is required in the html so I can use the functions and when I change the
value of a dropdown, the js is called.
How can I pass the $conn variable to Javascript?
Regards
It doesn't work like that.
You should never be directly making calls to the database from the front-end.
Think of it as three separate levels. Your HTML/JS is the front-end, your PHP is your server, and your Database is on its own level.
So when the user does something on the front-end, say changes the value of a field and you want to update that in the database the following actions should happen:
Event triggers on JS
AJAX is called as a result of the event being triggered
PHP server receives the AJAX request and executes code to modify database
(optional) PHP server sends something back to the front-end to tell it that the request was successful
Read up on the concept of MVC: https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture
Try this in php code as I assume functions.php
$conn = sqlsrv_connect($serverName, $connectionInfo);
echo $conn;//Don't try echo anything other
In Javascript
$.ajax({
type: "POST",
url: "functions.php",
success: function(data)
{
var conn = data; // here is your conn which comes from php file
}
});
First of all include jquery latest version from cdn
Create an API Url, and use POST method
site.com/api/insert.php // to insert into table
Use $.post() api of jquery to send data
var url = ""; // enter your URL HERE
var postData = {}; // object of post data with table name, cols and values
$.post(url, postData, function(data, status) {
// do what ever you want with data
})
ps: you can also create diff insertion / selection / update / delete api for different table. (recommended)
Read more about $.post() here

POST Slim Route not working

I'm using Slim for development. All my GET routes are working just fine, but whenever I use POST, I get "unexpected result". Please have a look at how I've implemented slim and that "unexpected error".
index-routes.php (index root file)
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim(array(
'debug' => true
));
require_once 'site-index.php';
require_once 'routes/default-routes.php';
$app->contentType('application/json');
$app->run();
?>
routes/default-routes.php
<?php
$app->post('/login',function(){
echo 'AllHailSuccess!';
})
?>
origin of POST request called via AJAX
function try1()
{
var value1 = "afsfesa";
API.call('/login','text','POST',function(data){console.log(data)},{var1:value1});
}
AJAX Call API
var API = {
call:function(url,returnType,reqType,callback,data){
var data = (!!data) ? data : {};
var callback = (!!callback) ? callback : function(){};
$.ajax({
dataType: returnType,
type:reqType,
crossDomain: true,
xhrFields: { withCredentials: true },
url: url,
data:data,
success:callback,
error:function(data){
console.log("Error!");
console.log(data);
}
});
}
}
"Unexpected error": When I execute try1(), THE POST ROUTE DOES GETS EXECUTED SUCCESSFULLY but the contents (The entire code in plain-text) of site-index.php (Which I called in root index-routes.php file) also gets logged along with it. The reason why I imported site-index.php in the first place, is because it acts like a "main stage" for my site. It's the only page I want to load and user navigates within it.
I want to know:
Why I'm getting this type of output?
Is my approach alright? I think importing my main-stage file from index- routes is causing this. Is there any other way of doing this?
Any help is appreciated. Thank you.
Your Slim calls are going to return anything that is displayed on the page.
There are a few ways to work around this:
Nest all of your page renders inside the route and don't render full pages for AJAX routes.
Modify your AJAX calls to search the returned DOM to find the relevant information.
In your example shown, AllHailSuccess! will be displayed after all of the content in site-index.php
Many people use templating software to render their pages and then use a service to render their page via the template. For more basic sites, I would recommend you create a simple service to display content.
Here's a simple example of a Viewer class I use in my project(s)
class Viewer {
/**
* Display the specified filename using the main template
* #param string $filepath The full path of the file to display
*/
public function display($filepath) {
//set a default value for $body so the template doesn't get angry when $body is not assigned.
$body = "";
if (file_exists($filepath)) {
$body = get_include_contents($filepath);
} else {
//You want to also return a HTTP Status Code 404 here.
$body = get_include_contents('404.html');
}
//render the page in the layout
include('layout.php');
}
}
/**
* Gets the contents of a file and 'pre-renders' it.
* Basically, this is an include() that saves the output to variable instead of displaying it.
*/
function get_include_contents($filepath, $params = array()) {
if (is_file($filepath)) {
ob_start();
include $filepath;
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
return false;
}
Your routes that you want to display the page layout to the user should look something like this now:
$app->get('/', function() {
(new Viewer())->display('home.html');
});
This is by no means a comprehensive solution because it does not address proper HTTP status codes and files are referenced directly in your code which can get messy, but it's a good starting point and its quick to mock something like this up.
If you want to continue in this direction, I would recommend you take a look at the Slim v2 Response Documentation and create a class that constructs and returns Response objects. This would give you much more flexibility and power to set HTTP status codes and HTTP Return headers.
I highly recommend checking out Slim v3 Responses as well because Slim 3 uses PSR-7 Response objects which are standard across multiple frameworks.

passing data between views in express js

I'm brand new to express and node, so please bear with me :D
i have an index.ejs file. I need to pass a string from my index.ejs file, to my viewActivity.ejs file. That string will then be used in the javascript portion of my viewActivity.ejs file. I'm not really sure how to go about this though. Is what I want to do even possible? Or do I have to do this via another file and not just directly view to view ?
here is my code. I want to pass the "stringToPass" to another view when a button is clicked.
function getPosts() {
var query = new Parse.Query(Post);
query.find({
success: function(results){
for (var i in results) {
var title = results[i].get("activityTitle");
var stringToPass = results[i].id
}
}, error: function(error) {
console.log("Query Error:"+error.message);
}
});
}
So far I've learned that express acts as the request handler. E.g.: pass you the file or anything based on the given request.
As soon as the request has been finished being handled, express would not know what the client does with the given result. Hence, once it sent the html file or json file or other request has been responded, all the remaining activities will be handled by a client side script that talks back to the express server in other form of requests. UPDATE: you can make this client side script to extract a DOM element and pass it onto your follow up request (when a user click a submit button, etc) that is handled by a different route.

JS/jQuery passing array/variable/data to PHP in same page?

Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?

Categories

Resources