using jquery $.ajax to call a PHP function - php

This may be a simple answer, but I'm using jQuery's $.ajax to call a PHP script. What I want to do is basically put that PHP script inside a function and call the PHP function from javascript.
<?php
if(isset($_POST['something'] {
//do something
}
?>
to this
<?php
function test() {
if(isset($_POST['something'] {
//do something.
}
}
?>
How would i call that function in javascript? Right now i'm just using $.ajax with the PHP file listed.

Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
I believe that's a simple incarnation of the Command pattern.

I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).
You basically send a JSON string in a specific format to the server, e.g.
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
which includes the function to call and the parameters of that function.
Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.
This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.

You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).
If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:
function test() {
// function code
}
test();
Or, use a PHP include:
include 'functions.php'; // functions.php has the test function
test();

You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.
Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).

You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net
Phery::instance()->set(array(
'phpfunction' => function($data){
/* Do your thing */
return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
}
))->process();
The javascript would be simple as
phery.remote('phpfunction');
You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):
function mcrypt(variable, content, key){
phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}
//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');
and in the server
Phery::instance()->set(array(
'mcrypt_encrypt' => function($data){
$r = new PheryResponse;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
return $r->set_var($data['variable'], $encrypted);
// or call a callback with the data, $r->call($data['callback'], $encrypted);
}
))->process();
Now the variable will have the encrypted data.

Related

Use the autocomplete event in the succes of my ajax

I would like to use an autocompletion in my application. I'm trying to use the jquery UI completion but nothing happens. I made an ajax to get all columns with a specific variable written by the user. The query is working, I have my array with all my columns back from the server. With this query reponse, I tried to do the jquery autocompletion in the success ajax but as I said nothing is happening.
Do you have an idea?
function autoCompleteRegate(){
$("#code_regate").keyup(function() {
// AJAX de l'auto-complete
var source = '/gestion/gestDepot/ajaxautocompleteregate';
var codeRegate = $("#code_regate").val();
$.ajax({
type : "POST",
url : source,
async : false,
dataType : 'json',
data : {
'codeRegate' : codeRegate
},
success : function(response) {
var availableTags = response;
$("#code_regate").autocomplete({
source: availableTags
});
}
});
});
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
echo json_encode($response);
}
Network query - form
Exemple of nothing happening
The answer from the server
You have to directly pass the cd_regate array instead of a multidimensional array. One workaround is you could process the json output on the backend side :
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
$json = [];
foreach ($response as $key => $value) {
array_push($json, $value->cd_regate); // the output will be "[774970, 774690, 774700,... ]"
}
echo json_encode($json);
}
I would suggest the following for your JavaScript:
$("#code_regate").autocomplete({
source: function(request, response){
$.ajax({
type : "POST",
url : '/gestion/gestDepot/ajaxautocompleteregate',
async : false,
dataType : 'json',
data : {
'codeRegate' : request.term
},
success : function(data) {
response(data);
}
});
}
});
This uses a function as a Source. From the API:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().
When 1 or more letters are entered into the text field, this will be passed to the function under request.term and you can POST that to your script via AJAX. When you get the result data, it must be in an Array or an Object with the right format.

send data via ajax to xml type php [duplicate]

This may be a simple answer, but I'm using jQuery's $.ajax to call a PHP script. What I want to do is basically put that PHP script inside a function and call the PHP function from javascript.
<?php
if(isset($_POST['something'] {
//do something
}
?>
to this
<?php
function test() {
if(isset($_POST['something'] {
//do something.
}
}
?>
How would i call that function in javascript? Right now i'm just using $.ajax with the PHP file listed.
Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:
$.ajax({ url: '/my/site',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();break;
case 'blah' : blah();break;
// ...etc...
}
}
I believe that's a simple incarnation of the Command pattern.
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).
You basically send a JSON string in a specific format to the server, e.g.
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
which includes the function to call and the parameters of that function.
Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.
This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.
You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).
If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:
function test() {
// function code
}
test();
Or, use a PHP include:
include 'functions.php'; // functions.php has the test function
test();
You are going to have to expose and endpoint (URL) in your system which will accept the POST request from the ajax call in jQuery.
Then, when processing that url from PHP, you would call your function and return the result in the appropriate format (JSON most likely, or XML if you prefer).
You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net
Phery::instance()->set(array(
'phpfunction' => function($data){
/* Do your thing */
return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
}
))->process();
The javascript would be simple as
phery.remote('phpfunction');
You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):
function mcrypt(variable, content, key){
phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}
//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');
and in the server
Phery::instance()->set(array(
'mcrypt_encrypt' => function($data){
$r = new PheryResponse;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
return $r->set_var($data['variable'], $encrypted);
// or call a callback with the data, $r->call($data['callback'], $encrypted);
}
))->process();
Now the variable will have the encrypted data.

call php function with arguments using Jquery

I have a php file func.php where I defined many functions let's say :
<? php
function func1($data){
return $data+1;
}
?>
I want to call the function func1 using ajax. thank you for your help
You can't call a PHP function directly from an AJAX call, but you can do this:
PHP:
<? php
function func1($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
?>
JS:
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { alert(response); }
});
You should call your php script through an ajax request, using jQuery like:
Javascript:
$.ajax({
url: "script.php",
data: { param1: "value1", param2: "value2" },
type: "GET",
context: document.body
}).done(function() {
// your code goes here
});
You could give your parameters through data property of ajax object.
Php
// you can do isset check before
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
// validate // sanitize // save to db // blah blah // do something with params
More information you could get from jQuery.ajax() function description from http://api.jquery.com/jQuery.ajax/
It's a bit more complicated, but I will try to shrink it down to the basics.
You will need some kind of interface (a convention, basically) between the caller and your script. Two are the main concerns here:
The way your script understands what needs to be called and with what arguments. Let's say you decide to use a GET request for calling a function. The function name could be in a func field and the arguments in an args one, as a string separated by ;. In other words, calling funcFoo(5,'bar') would be done by requesting func.php?func=func1&args=5;bar.
The way in which the caller receives (and understands) the return value. Since your requirements are js-oriented, a JSON approach would be highly appropriate.
Add the following code along with your functions:
if(isset($_GET['func']))
{
$func=$_GET['func'];
if(function_exists($func))
{
$args=(isset($_GET['args'])?explode(';',$_GET['args']):array());
$result=call_user_func_array($func,$args);
}
else
$result=array('error'=>"Unknown Function $func!");
}
else
$result=array('error'=>"No function name provided!");
echo json_encode($result);
However, your functions should also be changed to meet the new requirements. Since there's no way of telling how many arguments the caller will supply, a function should be designed to accept no mandatory arguments and check for the supplied ones itself. Also, it should always return an array in order to be json_encoded before it is returned to the caller.
Your example function, for instance, should look something like this:
function func1(){
$data=func_get_args();
if(count($data)) // at least one -- rest will be ignored
return $data[0]+1;
else
return array('error'=>__FUNCTION__."() expects an argument!");
}
Be aware though: This is just a skeleton to get you started with the whole concept. A lot more care should be taken for both fault tolerance and security. But that's another topic's subject.
Yes you can !
here my code :
$.ajax({
type: "POST",
url: "ajax.php",
data: { kode: $(this).val(), func: 'my_func' },
success: function(response) {
//any success method here
}
});
and here the code in php to receive what function to call.
$post = (object) $_POST;
if(!$post)
return false;
$func = $post->func;
return $func($post);
function my_func($post) {
$json['any_data'] = false;
if($post->kode == 'ND'){
$json['any_data'] = 'ND-'.date('Y');
}
echo json_encode($json);
}
Hope it help you out bro... :D

Is there a JavaScript way to do file_get_contents()?

Here is the PHP documentation
Here is how I would use it in an Ajax call, if I don't find a pure client way to do this.
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
Is there way to do this client side instead so I don't have to ajax the string over?
you could do
JS code:
$.post('phppage.php', { url: url }, function(data) {
document.getElementById('somediv').innerHTML = data;
});
PHP code:
$url = $_POST['url'];
echo file_get_contents($url);
That would get you the contents of the url.
It's 2020 and some modern approach;
async function file_get_contents(uri, callback) {
let res = await fetch(uri),
ret = await res.text();
return callback ? callback(ret) : ret; // a Promise() actually.
}
file_get_contents("https://httpbin.org/get", console.log);
// or
file_get_contents("https://httpbin.org/get").then(ret => console.log(ret));
JavaScript cannot go out and scrape data off of pages. It can make a call to a local PHP script that then goes on its behalf and grabs the data, but JavaScript (in the browser) cannot do this.
$.post("/localScript.php", { srcToGet: 'http://example.com' }, function(data){
/* From within here, data is whatever your local script sent back to us */
});
You have options like JSONP and Cross-Origin Resource Sharing at your disposal, but both of those require setting up the other end, so you cannot just choose a domain and start firing off requests for data.
Further Reading: Same origin policy
This function will return the file as a string just like the PHP file_get_contents().
function file_get_contents(uri, callback) {
fetch(uri).then(res => res.text()).then(text => callback(text));
}
However unlike PHP, JavaScript will go on to the next statement, not waiting for the data to return.
Not in a general sense. Cross-domain restrictions disallow Javascript code from doing this.
If the target site has CORS (cross-origin resource sharing) set up, you can use XMLHttpRequest to load files. Most sites do not, as it's off by default for security reasons, and is rarely necessary.
If you just need to include an HTML page, you can stick it in an <iframe> element. This is subject to some layout gotchas, though (the page ends up in a fixed-size element).
Or You can use php.js library. Which allow some php functions for javascript. file_get_contents() function one of them.
<script>
var data = file_get_contents('Your URL');
</script>
You can find more info about php.js : http://phpjs.org/
I think this may be useful for you:
An npm package with the "file-get-contents" method for node.js
https://www.npmjs.com/package/file-get-contents
It is asynchronous so if you are using express it should be used like this
app.get('/', async (req, res)=>{
//paste here the code below
}
Example
const fileGetContents = require('file-get-contents');
// A File request
try {
let data = await fileGetContents('/tmp/foo/bar');
console.log(data);
} catch (err) {
console.log('Unable to load data from /tmp/foo/bar');
}
// Or a HTTP(S) request
fileGetContents('https://pokeapi.co/api/v2/pokemon/1/').then(json => {
const pokemon = JSON.parse(json);
console.log(`Name of first pokemon is ${pokemon.name}`);
}).catch(err => {
console.err(`Unable to get content from PokeAPI. Reason: ${err.message}`);
});
<div id="svg">
</div>
<script>
function file_get_contents(uri, callback) {
fetch(uri).then(res => res.text()).then(text =>
{
var xmlSvg =text;
console.log(xmlSvg );
document.getElementById('svg').innerHTML = xmlSvg;
})
}
var uri ='You-urlllllllll-svg';
file_get_contents(uri);
</script>
function file_get_contents(filename) {
fetch(filename).then((resp) => resp.text()).then(function(data) {
document.getElementById("id").innerHTML = data;
});
}
file_get_contents("url");
<span id="id"></span>

Executing PHP function from JSON

I am trying some things with JSON and PHP and there is something that I can't find a way to do, though I'm not 100% sure there is one. But because it looks like a nice option (If possible) I decided to ask here.
I have these examples from jquery offical site. There are two files, the first one is index.php where I execute my Ajax, hete it is:
<!DOCTYPE html>
<html>
<head>
<title>Simple form sending and receiving a JSON object to/from PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
});
function showResult(res)
{
$("#fullresponse").html("Full response: " +res);
}
</script>
<div id="fullresponse"></div>
</head>
<body>
Nothing complicated at all. And I have my simpleformSubmi.php which is :
<?php
$logFile = 'logFile';
$res = json_decode(stripslashes($_POST['data']), true);
error_log("result: ".$_POST['data'].", res=".json_encode($res), 3, $logFile);
error_log("\n", 3, $logFile);
//header("Content-type: text/plain");
foreach ($res as $key=>$value)
{
$str[] = $value;
}
$functionArray ="function(){ \$a = 10; echo \$a;}";
$jsStr = $str[0][1];
echo json_encode($jsStr['firstname']);
echo '<hr />';
echo json_encode($res);
echo '<hr />';
echo json_encode($functionArray);
?>
As you can see $functionArray - is in fact a string containing PHP function which I want to return back using JSON and to execute it after that. So is there any way to do that really? Now what I get in index.php afet executing the files is:
"function(){ $a = 10; echo $a;}"
Thanks
Lern
Seems like you're trying to execute a PHP function through JavaScript. Since PHP is executed server-side the only way you have to execute a PHP function in that context is to ask the server back to execute the function for you, by doing another ajax call for example.
Something like this:
index.php
$(document).ready(function(){
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
var dataString = JSON.stringify(data);
//Change post() success callback function to executePHP()
$.post('simpleformSubmi.php', { data: dataString}, executePHP, "text");
//Let's define executePHP() outside post() call for clarity
function executePHP()
{
//Ask the server to execute function foo(), and get the result
$.get("example.com/somefile.php?function=foo", function(data)
{
//Success function, do whatever you want.
alert(data);
});
}
});
Then, in somefile.php
<?php
//Condition(s), if any. You could even implement this interface using REST.
//Get function to execute
if($_GET["function"] == "foo")
{
//Output function's result.
echo foo();
}
//The function you want to run
function foo()
{
//Do something
$a = 10;
return $a;
}
?>
If all went well, when JavaScript reaches the alert(data); statement you will see 10.
You cannot execute a PHP function after sending it as a response since the response is received on the client end, and PHP is a server side language.
Usually, you would just return the values. In your example, you would just return an associative array that holds the key value pair a,10.
You can return javascript functions from the PHP script and execute that on the client side using eval but eval'ing opens a pandora's box of security vulnerabilities.
You can't execute PHP code outside of a PHP server. So you can't run it in the browser.
You can, however, pass a string of JavaScript and run it through eval. Some people will tell you that's bad, but remember that eval used to be the only way to parse JSON in the first place.
In order to send back something to PHP, you must call the serverside via, p.e via GET or POST actions from a form. But, no, you cannot execute anything serverside via echo, as echo outputs to the client side. You could always use eval (http://php.net/manual/es/function.eval.php) at serverside to execute something from a POST message, but it is not recommended as it can open a great security hole.
You've returned a function (I'm assuming you meant this to be javascript), now you need to call it. This can be done by using the jQuery $.post success callback.
Try changing this..
$.post('simpleformSubmi.php', { data: dataString}, showResult, "text");
To
$.post('simpleformSubmi.php', { data: dataString}, function(data){eval(data)}, "text");
If its PHP (which it looks like) and not Javascript, then this will need to executed from the server. Being that its a server-side language 'n all.

Categories