At my Ajax response there is two variable: js, html.
The js variable contents Javascript in tag script: //Some code
And html contents HTML template.
How I can execute js code for html template from the successful response Ajax?
I tried this solution:
$('head').append(response.js); // not works
The full Ajax request:
getFormShare: function(type){
var posting = $.post('/share/getFormShare', { type : type } );
posting.done(function( response ) {
response = $.parseJSON(response);
$("head").append(response.js);
$('.ShareBlock #block').html(response.html).show();
initFileUpload(config);
initEditor();
});
}
The PHP side:
$js = $this->listdata->WrapperJavaScript($specialization, array('name_field' => 'type[]', 'tab' =>'tab', 'div_element' => '.specMain', 'label' => 'Category', 'autosearch' => 'true'));
$html = $this->load->view('social/forms/video', $this->data, true);
echo json_encode(array('html' => $html, 'js' => $js)); die();
You can use .getScript() and run your code after it loads:
$.getScript("my_lovely_script.js", function(){
alert("Script loaded and executed.");
// here you can use anything you defined in the loaded script
});
You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?
Edit:
Since you're returning actual javascript and would like to execute it, you can simply do this in your ajax response:
$.get(url,function(data){ $("body").append(data); });
Edit:
And with help from Mike's answer, you can use eval() to run the script if you don't have script tags in your response. His answer gives more info on this.
You can utilize javascript's eval to run string as code.
Keep in mind your string needs to be pure JS, no html or other elements to it.
example
eval("function foo() {console.log('bar');}");
//this call will create/instantiate a function called foo
Related
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.
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.
I have a CHTML:ajax function that does some AJAX stuff on a select dropdown - I simply want to do something which says..
"on change, grab the selected value & pass that as param childID in the URL"
This should then display the following in the url section of the
CHTML::ajax function:-
'url' => 'isAjax=1&childID=5134156'
I've tried to append the variable selected onto the url but it doesn't work - can anyone see what I'm doing wrong
jQuery(function($) {
$('#child-form select[name="Child[user_id]"]').bind('change', function(e){
var selected = this.value;
console.log('selected : '+selected ); // outputs an ID to the console.
<?php echo CHtml::ajax(array(
'url' => '?isAjax=1&childID='+selected,
'type' => 'post',
'update' => '#parents-sidebar',
// rest of the ajax function (quite long...)
You can't take a value extracted from the dom using javascript and inject it directly into PHP code.
From the PHP.net documentation:
Since Javascript is (usually) a client-side technology, and PHP is
(usually) a server-side technology, and since HTTP is a "stateless"
protocol, the two languages cannot directly share variables.
CHtml::ajax() is primarily a shortcut for generating javascript code. So the easy solution would just be to write your javascript manually. That will allow you to use your selected variable.
Note:
You might try Taron Saribekyan's solution, posted in the comments. The idea is that the javascript expression ('...+selected') will be printed by PHP as a string, and thus be evaluated by javascript. In theory, this should work.
That is obvious. You have defined a javascript variable and you are using it in your php code! Everything inside <?php ?> block, will interpret on the server and before javascript. So, I think you should use normal jquery ajax method in your case. Something like this:
$.ajax({
"url": <?php echo Yii::app()->baseUrl.'/controller/action' ?>'?isAjax=1&childID='+selected,
'type' => 'post',
...
})
I have a form that gets submitted.
Now I would like to retrieve the submitted data with javascript on the next page.
This works just fine when I put it in the body of the html:
<script>
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["form_input_name"]);
</script>
Now I want to have this functionality in a jQuery plugin method.
I tried the following in my jquery plugin:
$.pluginname.test = function() {
var $_POST = <?php echo json_encode($_POST); ?>;
document.write($_POST["form_input_name"]);
};
But when I try to execute it in the body of the html, I get the following error messages:
[Error] SyntaxError: Unexpected token '<'
[Error] TypeError: undefined is not an object (evaluating
'$.pluginname.test')
Why is this code-snipped working in a regular Javascript environment but not when called by a jQuery plugin?
Your PHP tags are being evaluated as JavaScript. That means that PHP is not processing them.
Presumably, this is because you have moved the script to a .js file.
While it is possible to generate a JavaScript file from PHP, that won't help you here: The data you are trying to generate is being submitted to the PHP script that generates your HTML document.
Move the script back between <script> and </script> in the PHP file that generates the HTML.
if this code:
$.pluginname.test = function(){};
is in external js file then you can't assign a php code values to it. It will cause errors. So i have one solution for it like make a args based plugin like:
$.pluginname.test = function(phpObj){
document.write(phpObj["form_input_name"]);
};
and you can call this on your php/html page in the script block like:
<script>
$.selector.test(<?php echo json_encode($_POST); ?>);
</script>
If you want to create a jQuery plugin:
$.fn.pluginname = function() {
var $_POST = 'SOME TEXT HERE';
$(this).text($_POST);
};
$('.el').pluginname();
Demo: http://jsfiddle.net/bfjLo02m/
Note: Make sure jQuery is included before
EDIT:
Since you've placed the plugin in a separate .js file you'll need to pass the PHP variables to your plugin in the index.html file. Here is an example:
// pluginname.jquery.js <-- separate file for your plugin
$.fn.pluginname = function(options) {
$(this).text(options.var1);
};
// index.html (or any html file)
$('.el').pluginname({ var1: $_POST["somePHPVar"], var2: 'var2Value' });
I want to paste two variables from javascript to PHP so I tried
$.post("index.php", {myQuery: myFinalSQL, action: "show_all_stories_sorting"});
where myFinalSQL is a string in javascript
In index.php, I try to printout the myFinalSQL with
echo $_POST['myQuery'];
But it didn't work. Would you please tell me how to insert javascript variables to PHP?
You using wrong approach.
It is bad way to interract with server by such method (inserting php variable in <? ?> tags into script tag).
You should use this:
$.post("ajax.php/myGlobalAction", params, callback);
In callback you will do with your data all what you need.
Example:
var params = {
id: 5
};
$.post( "ajax.php?action=getSqlQueryForSomething", params , function( data ) {
$( ".sqlQuery" ).html( data.sqlQuery );
});
So you have complex architecture problem if you need to work with php and js like this. Change your architecture before it's too late.
If you want to add value from PHP to Javascript you can use :
<script>
var myQuery = "<?php echo $myQuery; ?>;
</script>
But, if you want to add value from Javascript to PHP, you'r not allowed because PHP is server based and javascript is text based.
If you used $.post() :
$.post("index.php", {myQuery: myFinalSQL}, *your_javascript_action* );
in your index.php, you can use this :
if(isset($_POST['myQuery'])){ // checking method
echo $_POST['myQuery'];
}