I'm using JsonForm: https://github.com/joshfire/jsonform/wiki#wiki-getting-started
I'm trying to load a form schema into $('form').Jsonfrom(), from an external .txt file,
attempting this by loading it into my .html file with ajax, putting it in a javascript variable , then calling $('form').Jsonfrom() with a click event .
Here is my code:
<script>
#Load in .txt to javascript variable using ajax
var stringData = $.ajax({
url: "schema.txt",
async: false
}).responseText;
#check that file is loaded correctly .- have check this works.
#alert(stringData);
#on clicking of a piece of text in a <p> wrapper call jsonForm function.
$(document).ready(function(){
$("p").click(function(){
$('form').jsonForm(stringData )
});
});
</script>
the error I'm getting in firebug is:
"TypeError: this.formDesc.schema is undefined"
& my stack trace is this:
http://tinypic.com/r/2uiybo4/5
Think my problem may be in the way in loading in the .txt file with ajax.
however if I comment in: alert(stringData); . . . the scheme for the for is displayed perfectly.
Like so: http://tinypic.com/r/2ynl9qh/5
Also there is no problem with the scheme, as i have tried putting it directly into in $('form').Jsonfrom("here") & it works fine.
Managed to solve this .
had to use a templating language (jinja2) instead of ajax, to get my form schema into my html document.. so that json form ( a jquery form builder) couple execute on a full html doc on the page loading .
Silly !
Hope this helps .
Related
I have a form which when submitted is checked by the JQuery validator plugin. This works fine. In the JQuery code though I have my submit handler.
This part looks like the following:
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "php/main.php",
data: $(form).serialize()
});
return false;
}
Now I dont see anything wrong with this, looks fine to me. Then in main.php, I simply do
<?php
var_dump("OK");
include("APIEmailConnection.php");
var_dump("OK2");
if (isset($_POST["emailAddress"]) && !empty($_POST["emailAddress"])){
var_dump("OK3");
$connection = new APIEmailConnection();
$connection->obtainConnection();
var_dump("OK4");
}
I dont show it above, but I have a success function in my ajax call, and everytime I submit my form with an email address the success is fired. However, if I check firebug, I see the error
Fatal error: Class 'APIEmailConnection' not found in
/var/www/vhosts/myurl.com/httpdocs/folder/php/main.php on line 12
Also, the outputs from my var_dumps are
string(2) "OK"
string(3) "OK2"
string(3) "OK3"
So its missing OK4. My folder structure is like so
index.html
--js
--main.js
--php
--main.php
--APIEmailConnection.php
Now php include should be relative to the current file location, and because I am in main.php I believe my include is the correct path. And my submit handler must be correct, otherwise main.php would never be called in the first place.
So my question is what am I doing wrong? I dont know if it makes a difference, but main.php is a standard php file whereas APIEmailConnection.php is a class (and I dont namespace it).
Any advice on what the problem could be appreciated.
Thanks
Try checking the relevence to the section from which you include or use the main.php file. Hope this helps.
Here's the break down: My problem is two fold, i want to use a button to call to my php script, which in turn calls to my nodejs script running on my little internal test server (this is all done local for now).
Here is my html + script pull:
<input type="submit" value="Save Sketch" id= "run_system">
</body>
<script>
$('#run_system').on('click', function(){
$.ajax({
url : 'exec.php',
type : "GET"
}).done(function(data){
console.log(data);
});
});
</script>
and here is my php script:
<?php exec('node screenshot.js //place holder url that gets dumped into js file// "); ?>
so my problem is that the previous call to this php is not executing this. Everything i've googled says that this exec("") should run my nodejs script. What am i missing?
I am guessing the type : GET is incorrect, tried not having that line, putting POST in there, nothing seems to work though
Oh one more addition, so when i run the above all it does is print what was in the php file to the console, doesn't actually run the script
One of the issues is that the exec is executing the command, but you're not capturing / returning the output of that command. You can probably add an echo or print before exec to return the output to the AJAX request.
You might also want to bind to the submit event to handle form submissions as well as submit button clicks, but that would be bound to the form itself.
Ultimately though, I would recommend that you contemplate handling this exec by adding a simple HTTP server to your screenshots.js node script (or something that wraps it) and handle the AJAX request with that. Will likely need to add a Access-Control-Allow-Origin exemption.
Really sorry if this is a dumb question but I can't seem to get this to work. As the title says i am trying to load an external js file and assign it to a variable as plain text. The project is a simple js "compiler" that stitches together a number of js files and minifies them into one. I am currently using the $.get() method and appending the response to a string.
The problem is that the js file that handles the above also needs to be included in the final minified file. I can load in all the other files and stitch them together just fine but when i load this main file into itself sourcing a js file it seems to evaluate and overwrite itself and so stops the process.
For the time being i have got around the problem by loading in a copy as a .txt file but it means i have to keep two files up to date which isn't ideal.
I found this article but it refers to javascript loaded via script tags in the head.
Any help would be appreciated. I will happily post code but not sure which bits would be useful.
Update: I probably should have mentioned that the project needs to run entirely client side so i can't use PHP/.NET pages. All the files I'm loading in are on the same domain though.
Try to use Ajax.get() :
var script;
$.get('script.js', function(data) {
script = data;
});
for Ajax.get() it will work inside your domain, you can't call external domains, if your application requires loading external JS file then my guess is that you have to use PHP or another server-side language as:
var script;
$.get('getScript.php', {url: "http://test.com/script.js"}function(data) {
script = data;
});
in getScript.php you can use CURL or file_get_contents
Note that $.get() and $.post() and $.ajax() are all the same thing.
$.get and $.post are just shorthand versions of $.ajax() that come with presets (obviously, type: "GET" and type:"POST" for one...). I prefer using $.ajax because the format can be more structured, and therefore easier to learn/use.
Javascript/jQuery would look something like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "loadmyfile.php",
data: 'filename=js/myscript.js',
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#myhiddentext').val(whatigot);
} //END success fn
}); //END $.ajax
}); //END $(document).ready()
</script>
Important: Note that you would need to do all the post-AJAX processing inside the success function. See this link for some simple AJAX examples.
Note that you can send data across to the PHP file by specifying a data: parameter in the AJAX code block. Optionally, you can leave out that line and simply hard-code the filename into the PHP file.
The text of the retrieved js file comes back into the AJAX success function (from the PHP file) as a string in the variable specified as the function param (in this case, called 'whatigot'). Do what you want with it; I have stored it inside a hidden <input> control in case you wish to retrieve the text OUTSIDE the AJAX success function.
PHP would look something like this:
loadmyfile.php
<?php
$fn = $_POST['filename'];
$thefile = file_get_contents($fn);
echo $thefile;
References:
PHP file_get_contents
How can I include code, for example using Javascript? Or if that can't be done, how can I include a whole PHP file?
P.S. Found some script called "require" or "include," but I prefer two lines of code instead of a huge library (using jQuery though). If that can't be done, let me know, I will try to think of something else.
EDIT:
Okay, an example of what I want to do:
function foo() { if(x = 1) return 1; else return 0; }
Then if the function returns 1, I want to either add HTML/PHP code to DIV tags OR I want to include a PHP file containing that code.
EDIT #2:
What about only HTML?
document.getElementById('test').innerHTML = 'a cool link';
That doesn't seem to work either.
I have an empty div tag with id="test" in my code.
function foo() {
if(x = 1) {$("#divid").load("somephp.php");return 1;}
else return 0;
}
Or
if (foo()) $("#divid").load("somephp.php");
The only files could Javascript includes is Javascript files, what ever the extension is. and the only way to do it is using
<script src="path/to some/file.ext"></script>
You should note that the file should be javascript text contents, else errors may be generated.
Javascript can call any file as long as it is on your server.It can't call files on the user's local files, for obvious security reasons.
However, javascript cannot, and will never be able to call PHP code, as in it cannot execute php code. This is because since javascript is client side, users can call their own javascript on your page, and execute PHP code, and potentially mess up your site or browse your backend.
You can, however add HTML code to your page using javascript, fairly simply using the innerHTML property of DOM elements or JQuery.
Javascript can also call more javascript code if you wanted, using eval()
If you wanted to call files off your server onto the page using javascript, you'd have to use AJAX
Google it up, and you can code it from scratch, or use JQuery's convenient AJAX handler.
Let's say you had a php file myfile.php that had some html/php, and you wanted to insert it into a div with the id "mydiv", or in css, "#mydiv"
If you just want to quickly load the html/php and push it into the div:
$("#mydiv").load("myfile.php");
If you want to have maximum control of the response from the html/php file:
$.ajax({
url: "myfile.php", // url to load
success : function(data) { // on success function
// data is the response of the ajax request, the response text
// you can manipulate it here
manipulateData(data);
$('#mydiv').html(data); // set the html of the div
}
});
I'm new to cakePHP but am close to quitting using it due to my inability of getting jQuery to work with it.
I'm using cakePHP 1.3 and so thought the Html and Js helpers had made Javascript and Ajax redundant but I can't really find any help/api documentation on how to use Js that is sufficient.
All I'm trying to do first of all is send some data to cakePHP with jQuery and then get some data back into jQuery and alert() it. For some reason this just isn't working. Here is my code:
test.js
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '/activities/add_activity',
data: 'type=social',
dataType: 'json',
success: function(data)
{
alert(data);
},
error: function()
{
alert('wut');
}
});
});
activities_controller.php
function add_activity()
{
if($this->RequestHandler->isAjax())
{
$this->autoRender = false;
$this->autoLayout = false;
$this->header('Content-Type: application/json');
echo json_encode(array('result'=>'hello');
return;
}
}
Every time I click the button with class='social' I get the alert "wut" which means error.
I have the RequestHandler component and Javascript, Js, and Ajax helpers included in my activities_controller.php.
Also, test.js and jquery.js is linked using html->script(); in default.ctp and all other jQuery stuff is working so it's not that.
I've also got this in my beforeFilter() for activities_controller.php:
if($this->RequestHandler->isAjax())
{
Configure::write('debug',0);
}
parent::beforeFilter();
Any ideas what is wrong? Is it a jQuery thing or a cakePHP thing? Or both?
Thanks in advance,
Infinitifizz
P.S.
I have never done AJAX in jQuery before so maybe it is something to do with that that is messing up, I've only ever done simple javascript AJAX.
Don't give up on CakePHP. There is a learning curve, but it's worth it.
I would specify the url like this:
<?php $Url = Router::url(array('controller'=>'activities','action'=>'addActivity'),true); ?>
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '<?php echo $Url ?>';
...
On the CakePHP side, my method would be like this:
function addActivity()
{
$this->autoRender = false;
$this->autoLayout = false;
App::import('Helper', 'Javascript');
$javascript = new JavascriptHelper();
echo($javascript->object(array('result'=>'hello')));
exit(1);
}
I never use if($this->RequestHandler->isAjax()) although I'm sure some kind soul will tell me why I should.
I prefer to camelCase method names in line with CakePHP convention.
Note that this line in your code: echo json_encode(array('result'=>'hello'); is missing a closing bracket.
Also, I wouldn't use jQuery to do simple AJAX like this - it can make it difficult to debug, but that's just personal preference.
I hate the Ajax Helper in CakePHP... that is until I found this: http://blog.loadsys.com/2009/05/01/cakephp-jquery-ajax-helper-easy-scriptaculous-replacement/
Now I can use native CakePHP Ajax calls with jQuery! Look into this. I was able to solve all of my "simple" ajax issues with this darg-n-drop ajax helper replacements. I just drop this into the helpers directory in my app and replace the ajax.php that is there and viola! jQuery is working. You need to include the jQuery script in the layout of course. Try it, you will love CakePHP again!
I would recommend you to use CakePHP json layout to output the data from view instead of echo json data from your controller.
This probably is offtopic, but...
What I do in order to have the application's root in my javascript:
In the /app/views/layout/default.ctp I have following code
<?php
echo $javascript->codeBlock("var root = '".$html->url('/')."';");
?>
Your parameter url will look like:
url: root+'activities/add_activity',
this way even if you app is in a subfolder or in a tld domain the script will work properly.
Returning "wut" for me means that the script couldn't reach the page in your url parameter. Especially if you working in a subdirectory it will look in http://server.com/activities/add_activity. I am 99% sure that this is the problem :)
Another suggestion: Remove Ajax while it was meant to work with Prototype rather with jQuery