Issue executing Perl CGI from JavaScript - javascript

How do I get my Perl script to execute from JavaScript called from an HTML form's 'action' attribute?
I am using scripts built by other people mostly, and the basic gist of it is that I need to call the CGI script from the JS function.
I have to do it this way because it was the best I could come up with based on whether or not the device is mobile.
I need to pass some checkboxes to the Perl script and return some files based on the checkbox states. I know the Perl script works perfectly without having to execute the JavaScript, but I don't know how to check if a device is mobile or not in Perl, and I do in JS.
All I need is to execute the CGI script, passing it the same information as if it was being called directly from the form, but it does nothing.
Here is my JavaScript:
function downloadFiles(){
var isMobile = function(){
try {document.createEvent("TouchEvent"); return true;}
catch(e) {return false;}
}
&& (/Mobi/i.test(navigator.userAgent));
if(!isMobile){
$.ajax({
type:"Post",
url:"https://www.mywebsite.com/cgi-bin/myPerlScript.cgi",
success:function(msg){$("#myHtmlForm").html(msg.d);}
});
}
}
I don't rightly know what 'msg' or its property 'd' is, and I don't even know if my form should be the element where it is. So what I am missing here?

It turns out that I wasn't building the ajax statement completely or correctly. I didn't add any data that I needed to pass into the CGI script.
Here's the ajax statement I ended up with:
$.ajax({
type:"POST",
url:"/cgi-bin/myPerlScript.cgi",
data:$("#myHtmlForm").serialize(),
error:function badCall(){location.href="https://www.mywebsite.com/error.html";}
});
Thank you #ikegami, #mkHun, #simbabque, and #DaveCross!

Related

Button On click call jquery function and acess php

I am very new to Wordpress and Woocommerce. I have few doubts wrt jquery in Wordpress. Say i have a function
function test(){
alert("test");
<?php
error_log("Test ---------------------------- ", 0);
?>
}
and a button:
<input type="button" id="btnclick" onclick="test();" value="Test" />`
error log is printing on page load but not on click. But i want to execute code inside php block only when user clicks on button.Is there a way to achieve this ? Thanks in advance`
jPO has already explained how to solve this in a good way, but I thought I should explain why this happens.
PHP is executed on the server. Once the page has been sent to the client, the PHP is no more. JavaScript happends on the client, and can be executed as long as the user is viewing the webpage. Since they do not live during the same timeperiod they are not aware of each other and can not be mixed in that way.
When you visit the page in your browser, the browser sends a request to the server. On the server the PHP interpreter goes through the code of the requested page, executing everything between <? and ?>. It does not understand what the other stuff around it is - it could be HTML, JS, plain text, anything, the PHP interpreter does not know and does not care. That is why it writes to the error log on page load.
When the PHP interpreter is done it has produced a document looking like this:
function test(){
alert("test");
}
That is sent to the client, and the JS (without any instruction to write to the error log) is run on the client when the button is pushed.
Not possible like that. If you'd like to do so. You need something like ajax method in php which you can call. Let's say you have a file in the root of your project called ajax.php, there you can define a function named test(), then you have to have a $_REQUEST translator, which calls your function test(), so the ajax.php would look like this
<?php
// checks if you sent a parameter named method and calls the method
// if you provide parameter named params it will send them too
if(isset($_REQUEST)){
if(isset($_REQUEST["params"]))
ajax($_REQUEST["method"],$_REQUEST["params"]);
else
ajax($_REQUEST["method"]);
}
function ajax($function,$data = null){
$function($data);
}
function test(){
error_log("Test ---------------------------- ",0);
}
and your ajax would look like this
function test(){
$.ajax({
url:"ajax.php",
data:{
method:"test"
}
});
}
hope it helps

Passing data from PHP to JS and JS to PHP

Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Check iframe status after AJAX File Upload with Rails

There is a similar post Retrieving HTTP status code from loaded iframe with Javascript but the solution requires the server-side to return javascript calling a function within the iframe. Instead, I would simply like to check the HTTP status code of the iframe without having to call a function within the iframe itself since my app either returns the full site through HTML or the single object as JSON. Essentially I've been trying to implement a callback method which returns success|failure dependent upon the HTTP status code.
Currently I have uploadFrame.onLoad = function() { ... so far pretty empty ... } and I am unsure what to check for when looking for HTTP status codes. Up until now, I've mainly relied upon jQuery's $.ajax() to handle success|failure but would like to further understand the mechanics behind XHR calls and iframe use. Thanks ahead of time.
UPDATE
The solution I came up with using jQuery
form.submit(function() {
uploadFrame.load(function() {
//using eval because the return data is JSON
eval( '(' + uploadFrame[0].contentDocument.body.children[0].innerHTML + ')' );
//code goes here
});
});
I think the best solution is injecting <script> tag into your iframe <head> and insert your "detecting" javascript code there.
something like this:
$('#iframeHolderDivId').html($.get('myPage.php'));
$('#iframeHolderDivId iframe head').delay(1000).append($('<script/>').text('your js function to detect load status'));
Maybe it's not the best solution but I think it works

using reCAPTCHA with ajax....javascript loading problem

I trying to implement reCAPTCHA in one of my forms,...but i am using ajax as the submission. (More specifically the prototype ajax.updater)
Once I submit and error check my form I try to load the reCAPCHTA widget thingy (in my updated div element) which basically just calls a javascript file like so:
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Le6SwUAAAAAAIWm8wCRFd8SrI-H0R1Yx4Tkw2Ks"></script>
However the JS file is not being read?...and i've tried all combination of evalScripts:true and evalJS:'force' etc. in the ajax.updater.....however i don't think I have a very good understanding of why the js file isn't processing :(
If anyone can shed some light on this issue I will be very appreciative.
Thanks, Andrew
This doesn't address your exact problem, but 'Dark Side of the Carton' has some excellent code for validating reCAPTCHA via jQuery AJAX which might help.
In summary:
Add the following Javascript:
$(function() {
function validateCaptcha() {
var challengeField = $('input#recaptcha_challenge_field').val(),
responseField = $('input#recaptcha_response_field').val();
// alert(challengeField);
// alert(responseField);
// return false;
var html = $.ajax({
type: 'POST',
url: 'ajax.recaptcha.php',
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if (html.replace(/^\s+|\s+$/, '') == "success") {
$('#captchaStatus').html(' ');
// Uncomment the following line in your application
return true;
} else {
$('#captchaStatus').html(
'Your captcha is incorrect. Please try again'
);
Recaptcha.reload();
return false;
}
}
// Modified as per comments in site to handle event unobtrusively
$('#signup').submit(function() {
return validateCaptcha();
});
});
Then add the ajax.recaptcha.php file which: "outputs only the word “success” if the captcha matches and a message and the response from reCaptchta if it fails. This is important because we are looking for the word success in our validateCaptcha() function."
require_once('/inc/recaptchalib.php');
$publickey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // you got this from the signup page
$privatekey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);
if ($resp->is_valid) {
?>success< ?
} else {
die(
"The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")"
);
}
The example is in PHP, but I adapted it easily to work with Zope/Python
Be careful using any sort of client-side script, such as JavaScript, for validation. You have no control over the end-user's browser. The purpose of a CAPTCHA is to prevent automated submissions of a form. Anyone sophisticated enough to set that up isn't going to have a problem overriding your JavaScript validation and CAPTCHA checking. For example, they could set validateCaptcha() to always return true, bypassing your careful checks - or just disable JavaScript.
That being said, there's nothing wrong with performing the entire form submission with ajax and using the results of the CAPTCHA check to determine if the form gets processed or not.
The important point is that the decision of whether or not to handle the form has to be made on the server-side, not the client-side.
Why client-side validation is not enough
to answer my own question...
there is a reCAPTCHA AJAX api....which is pretty easy way to get around this problem:
link text
Also,..the documentation on the http://www.prototypejs.org/api/ajax/updater site.....talks about the evalscript option and how is only puts any javascript through the native eval() function....which kind of screws me over trying to implement error checking with WMD...but that's another story.
Andrew
If that's the literal code snippet you're using, you haven't closed the tag... so it wouldn't be evaluated.
call Recaptcha.reload(); on callback event in your Ajax code., it will reload new Recapcha every time that Ajax submitted
Hi Friend i found the answer
https://developers.google.com/recaptcha/docs/display?hl=es#AJAX
And in this how validate
http://blog.reaccionestudio.com/comprobar-recaptcha-con-ajax-usando-jquery/
Success for you
Securing AJAX calls with reCaptcha
function performAJAX() {
let captcha = $('[name=g-recaptcha-response]');
$.ajax({
url: 'ajaxHandler.html',
data: {
captcha: (captcha.length?captcha[0].value:''),
// other data fields
},
});
}
I have had similar issues with getting reCaptcha to play nicely when loaded into the page using jQuery's .load() method. Here is a page that has a novel solution: http://www.maweki.de/wp/2011/08/recaptcha-inside-a-with-jquery-ajax-or-load-dynamically-loaded-object/
Basically the reCaptcha API uses document.write method to display the reCaptcha. When you get jQuery invloved this won't work. Use this PHP code in place of loading recaptcha.js
<?php
$api = file_get_contents('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$api = str_replace('document.write','$("body").append',$api);
echo $api;
?>
It just does a find for document.write and replaces it with $(selector).append.
Made my implementation work.

Categories

Resources