JavaScript Development
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
 
User Name:
Password:
Remember me
 



Go Back   Dev Articles Community ForumsProgrammingJavaScript Development

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Display Modes
 
Unread Dev Articles Community Forums Sponsor:
  #1  
Old April 29th, 2003, 09:39 AM
Evil_homer Evil_homer is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Mar 2003
Posts: 5 Evil_homer User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Calling php functions with JavaScript

Thanks to asgeo1 and stumpy for answering my previous JavaScript related query. However i've now come across another problem:

Is there any way to call a php function, or execute some php code using JavaScript. I've searched on google for a while but found no real solution.

Basically i use a form to call a javascript function, then i want that javascript to call a php function found within the same page, or failing that be able to execute a few lines of php script from within the javascript.

Any help greatly appreciated

Reply With Quote
  #2  
Old April 29th, 2003, 09:01 PM
stumpy's Avatar
stumpy stumpy is offline
May contain nuts.
Dev Articles Regular (2000 - 2499 posts)
 
Join Date: Aug 2002
Posts: 2,056 stumpy User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 5 h 44 m 22 sec
Reputation Power: 0
Sounds like you're getting confused with developing on the web.

Javascript (unless specified) is a "client-side" language, meaning that it runs on the clients browser AFTER has page has been compiled and sent from the server. This means that there is no PHP/ASP in the code, only HTML & Javascript.

PHP, ASP, JSP are server-side languages which only run on the server-side.

So to answer your question, no you can't directly get the Javascript to call a PHP (server-side) function, but you can post to a PHP page which will then in turn carry out whatever function u like.

Reply With Quote
  #3  
Old April 30th, 2003, 06:05 AM
Evil_homer Evil_homer is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Mar 2003
Posts: 5 Evil_homer User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Right, thanks for the heads up.

Reply With Quote
  #4  
Old August 16th, 2004, 03:24 PM
Tjerk Tjerk is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Aug 2004
Posts: 1 Tjerk User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
Lightbulb Calling php methods from javascript is possible

calling php methods from javascript is possible by using xmlrpc (see xmlrpc.com) you can call a php methods remotely with javascrit by setting up a xmlrpc server (a php page) and then acces that server within javascript. There are php xmlrpc libs and javascript xmlrpc .js files.

in computersceince everything is possible

Reply With Quote
  #5  
Old September 2nd, 2004, 08:15 AM
nvdberge nvdberge is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2004
Posts: 1 nvdberge User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: < 1 sec
Reputation Power: 0
A good working solution I think

Hi,

I wrote this code.
The comments say enough I think.

Code:
<HTML>
 <BODY>
  <?php 
   if (isset($_GET[action])){
	// Retrieve the GET parameters and executes the function
	  $funcName	 = $_GET[action];
	  $vars	  = $_GET[vars];
	  $funcName($vars); 
	 } else if (isset($_POST[action])){
	  // Retrieve the POST parameters and executes the function
	  $funcName	 = $_POST[action];
	$vars	  = $_POST[vars];
	$funcName($vars); 
	  
	 } else {
	  // If there is no action in the URL, then do this
	echo "<INPUT NAME='btnSubmitAdmin' TYPE='button' ONCLICK='javascript:javaFunction()' VALUE='Call Javafunction() which redirects to a PHP function'>";
   }
	 
   function phpFunction($v1){
	// makes an array from the passed variable 
	// (note: $vars = 1 string while it used to be a javascript Array)
	// with explode you can make an array from 1 string. The seperator is a , 
	$varArray = explode(",", $v1);
	
	echo "<BR>function phpFunction<BR><BR>"; 
	echo "v1: $varArray[0] <BR>";
	echo "v2: $varArray[1]<BR>";
	
   }
  ?>
 
 
  <SCRIPT language="javascript">
   function javaFunction(){
	// In the varArray are all the variables you want to give with the function
	var varArray = new Array();
	varArray[0] = "var1";
	varArray[1] = "var2";
   
	// the url which you have to reload is this page, but you add an action to the GET- or POST-variable
	var url="<?php echo $_SERVER[PHP_SELF];?>?action=phpFunction&vars="+varArray;
	
	// Opens the url in the same window
	   window.open(url, "_self");
	  }
  </SCRIPT>
 </BODY>
</HTML>


regards,
Niels

Reply With Quote
  #6  
Old September 2nd, 2004, 08:51 AM
kode_monkey kode_monkey is offline
Contributing User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jul 2003
Posts: 367 kode_monkey User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 m 21 sec
Reputation Power: 12
"In computer science everything is possible"

An interesting stand point to take... would love to see a polynomial time algorithm for some of the famous NP problems.

-KM-

Reply With Quote
  #7  
Old March 19th, 2005, 01:24 PM
hack hack is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Mar 2005
Posts: 1 hack User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 13 m 52 sec
Reputation Power: 0
Smile

Quote:
Originally Posted by kode_monkey
"In computer science everything is possible"

An interesting stand point to take... would love to see a polynomial time algorithm for some of the famous NP problems.

-KM-

Patience is a virtue KM, the "famous" NP hard problems may be NP hard now but not necessarily in the future therefore kode_monkey is right.

Reply With Quote
  #8  
Old April 13th, 2008, 01:29 PM
hasantayyar hasantayyar is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Apr 2008
Location: Turkey
Posts: 4 hasantayyar User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 22 m 11 sec
Reputation Power: 0
Send a message via Google Talk to hasantayyar Send a message via Skype to hasantayyar
The simple solution for "How can i call PHP functions from Javascript?"

The simple solution for "How can i call PHP functions from Javascript?"

(i didnt test on i.e. or opera... i tested this on firefox!)

Here you dont need to use XMLHttpRequest or any other complex things.
Code:
// .... here some php lins... variables o some functions....

//... maybe some post variables an some new values.... proccessed over post variables....


<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php for($i=0; $i<10; $i++) echo $i; //maybe a function ?>";
}
</script>

<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>


thats all..

Reply With Quote
  #9  
Old April 25th, 2008, 05:39 PM
Mittineague's Avatar
Mittineague Mittineague is offline
Contributing User
Dev Articles Novice (500 - 999 posts)
 
Join Date: Jul 2005
Location: West Springfield, Massachusetts
Posts: 552 Mittineague User rank is Private First Class (20 - 50 Reputation Level)Mittineague User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 1 Week 1 Day 9 h 1 m 33 sec
Reputation Power: 10
javascript PHP example

Hi hasantayyar, welcome to the forums.
Actually, what you posted is not an example of javascript calling a PHP function, but rather using PHP to populate a javascript function. Javascript is client-side and PHP is server-side, so the PHP will run before the page is sent to the browser. In this case, the page's source code will be
Code:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="0123456789";
}
</script>

<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
This will "work", but it is not javascript calling a PHP function.
__________________
WP plugins - Error Reporting, Clean Options
http://www.mittineague.com/dev/er.php
http://www.mittineague.com/dev/co.php

Last edited by Mittineague : April 25th, 2008 at 05:41 PM.

Reply With Quote
  #10  
Old April 26th, 2008, 03:03 AM
hasantayyar hasantayyar is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Apr 2008
Location: Turkey
Posts: 4 hasantayyar User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 22 m 11 sec
Reputation Power: 0
Send a message via Google Talk to hasantayyar Send a message via Skype to hasantayyar
i see
but this will be usefull for short actions...

for example our php function is
PHP Code:
function doit($w){
swicth($w){
case 
'do': echo "you will be logged in?";
case 
'loguot': echo "you will be logged our?";
}




and so we can use this function like this maybe:

PHP Code:
<?
$w
=""
...... 
actions about w;
?>

<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php 
// the doit function's content here
swicth($w){
case 
'do': echo "you will be logged in?";
case 
'loguot': echo "you will be logged out?";
}
?>";
}
</script>

<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>


and yes you are right about client/server side codes. But about simple solutions this will be helpful.

Reply With Quote
  #11  
Old May 2nd, 2008, 09:49 PM
timidwind timidwind is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2008
Location: AZ
Posts: 5 timidwind User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 24 m 11 sec
Reputation Power: 0
What about activating a javascript function from php? I bet I'm gonna hear about server/client side etc....
Here's the deal:
Have html form, as user enters need to validate fields.
Get values of phone and cell with onBlur activating javascript,
which Sends values to inlaid php testing,
now just need to call a javascript alert and keep user in entry loop until the phone #'s are valid and different

??? Whew....
Anyone?

Reply With Quote
  #12  
Old May 2nd, 2008, 11:46 PM
Mittineague's Avatar
Mittineague Mittineague is offline
Contributing User
Dev Articles Novice (500 - 999 posts)
 
Join Date: Jul 2005
Location: West Springfield, Massachusetts
Posts: 552 Mittineague User rank is Private First Class (20 - 50 Reputation Level)Mittineague User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 1 Week 1 Day 9 h 1 m 33 sec
Reputation Power: 10
validate input

Hi timidwind, welcome to the forums.
I'm a bit foggy. What exactly do you want the PHP to do with the javascript code?

Reply With Quote
  #13  
Old May 2nd, 2008, 11:59 PM
timidwind timidwind is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2008
Location: AZ
Posts: 5 timidwind User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 24 m 11 sec
Reputation Power: 0
Provide an alert pop-up; alerting the user that either (both situations arrived via php tests) a) they have entered either their phone or cell number in the wrong format OR b) both #'s are the same; ...please repair your entries. I have successfully used Javascript to do a simple compare between the two form entries, alert the user and prevent the user to proceed until they're fixed (loop if you will); however that's the only condition tested for within the script. In order to trim, check formatting, and then compare I had to send the values out to php from a javascript capture from an 'on blur' prior to form 'submit'. But now, I've tested them, I need an alert as well as to not proceed until they're fixed.
I can't believe I'm having this much trouble with it though. It seems such a simple concept, to alert the user to entry problems as they happen before submission then receiving a laundry list of problems or re-entries.

Reply With Quote
  #14  
Old May 3rd, 2008, 12:02 AM
timidwind timidwind is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2008
Location: AZ
Posts: 5 timidwind User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 24 m 11 sec
Reputation Power: 0
Am so sorry, I am remiss that I forgot to type a thank you for the welcome first thing to you Mittineague; That was oh too rude. I am so sorry.

Thank You for your interest, and anyone who's willing to help. vbmenu_register("postmenu_196818", true);

Reply With Quote
  #15  
Old May 3rd, 2008, 02:30 PM
Mittineague's Avatar
Mittineague Mittineague is offline
Contributing User
Dev Articles Novice (500 - 999 posts)
 
Join Date: Jul 2005
Location: West Springfield, Massachusetts
Posts: 552 Mittineague User rank is Private First Class (20 - 50 Reputation Level)Mittineague User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 1 Week 1 Day 9 h 1 m 33 sec
Reputation Power: 10
validation logic

So if I'm correct, it goes something like:
1: Form page loads
2: User enters data
3: Javascript validates input client-side
4: If not OK shows javascript alert(), else if OK (js-wise) makes (AJAX ??) request to server to check validity server-side
5: If OK server-side do stuff, else if not OK "alert" user of error

I guess to "hold up the alert() until they're fixed", you could test the original input value (the bad one) against the "current" or "new" one to make sure they're differnt and then check server-side again.

Is this what you mean?

Reply With Quote
  #16  
Old May 6th, 2008, 07:33 AM
timidwind timidwind is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2008
Location: AZ
Posts: 5 timidwind User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 24 m 11 sec
Reputation Power: 0
Yes n no, ok now I'm confused with that!

Quote:
Originally Posted by Mittineague
So if I'm correct, it goes something like:
1: Form page loads
2: User enters data
3: Javascript validates input client-side
4: If not OK shows javascript alert(), else if OK (js-wise) makes (AJAX ??) request to server to check validity server-side
5: If OK server-side do stuff, else if not OK "alert" user of error

I guess to "hold up the alert() until they're fixed", you could test the original input value (the bad one) against the "current" or "new" one to make sure they're differnt and then check server-side again.

Is this what you mean?


Yes n no, ok now I'm confused with that!

1;2;3; and was 4a show alert; prevent submit until entry(ies) corrected and if correct submit to server side and print report of All entries.(Other problems with entries notified on report)

But because of reading all of the entries here and elsewhere; a)I've gone more of the JavaScript validation for just the two fields;
b)and instead of 'alert(messages)' stopping continued entries being made; having the notice show "after" the submit button is clicked
c) however still stopping a full form submission until just these two fields are correct.

So, it's narrowed down.

To get specific now.... check and validate a phone entry and cell phone entry for (1) not empty (2)format (3)as well as that they aren't the same ....and be specific about the error to correct; and (4)being sure that submission is prevented until they're both correct and not the same.

So, here's the code so far.... (a "code-lette" really, I've pulled out just this part I'm having trouble with.) but I'm having trouble with comparing the two - phone and cell in the validateNmbs function.

Code:
<html>
<head>
<script type="text/javascript">
function validateFormOnSubmit(theForm)
{
var reason = "";

  reason += validatePhone(theForm.phone);
  reason += validateCell(theForm.cell);
  //reason += validateNmbs(theForm.phone,theForm.cell);
  
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }
  alert("All fields are filled correctly");
  return false;
}


function validateEmpty(fld) 
{
    var error = "";
 
    if (fld.value.length == 0) {
        fld.style.background = 'PowderBlue'; 
        error = "The required field has not been filled in.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

function validateNmbs(fldp,fldc)
{
	phoneN=fldp.value;
	cellN=fldc.value;
	
  if (phoneN == cellN)
  {
        error = "The Phone and Cell cannot be the same.\n";
        fldp.style.background = 'PowderBlue';
        fldc.style.background = 'PowderBlue';
  }
  return error;
}

function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    
	var regex = /^\d{3}-\d{3}-\d{4}$/;

   if (fld.value == "") 
   {
        error = "You didn't enter a Phone number.\n";
        fld.style.background = 'PowderBlue';
    }
     else if (isNaN(parseInt(stripped))) 
     {
        error = "The Phone number contains illegal characters.\n";
        fld.style.background = 'PowderBlue';
    }
    else if (!(regex.test(fld.value)))
    {
        error = "The Phone number is the wrong format. Please use the format shown.\n";
        fld.style.background = 'PowderBlue';
  	}
     else if (!(stripped.length == 10)) 
     {
        error = "The Phone number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'PowderBlue';
    }
    return error;
}
function validateCell(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    
	var regex = /^\d{3}-\d{3}-\d{4}$/;

   if (fld.value == "") 
   {
        error = "You didn't enter a Cell number.\n";
        fld.style.background = 'PowderBlue';
    }
     else if (isNaN(parseInt(stripped))) 
     {
        error = "The Cell number contains illegal characters.\n";
        fld.style.background = 'PowderBlue';
    }
    else if (!(regex.test(fld.value)))
    {
        error = "The Cell number is the wrong format. Please use the format shown.\n";
        fld.style.background = 'PowderBlue';
  	}
     else if (!(stripped.length == 10)) 
     {
        error = "The Cell number is the wrong length. Make sure you included an area code.\n";
        fld.style.background = 'PowderBlue';
    }
    return error;
}

</script>
<title>PowderBlue</title>
</head>
<body> 
<form name="MickeyMC" onsubmit="return validateFormOnSubmit(this)" action="">
<table summary="Registration Form">
  <tbody>


 
  <tr>
    <td><FONT SIZE="3"><label for="phone">Your telephone number: </FONT>
    		<FONT SIZE="1">(xxx-xxx-xxxx)</FONT></label></td></TR><TR>
    <td><input name="phone" size="35" maxlength="25" type="text"></td>
  </tr>   
  <tr>
    <td><FONT SIZE="3"><label for="cell">Your Cell number:</FONT>
    		<FONT SIZE="1">(xxx-xxx-xxxx)</FONT></label></td></TR><TR>
    <td><input name="cell" size="35" maxlength="25" type="text"></td>
  </tr>   
  
  <tr>
    <td> </td>
    <td><input name="Submit" value="Send" type="submit" ></td>
    <td> </td>
  </tr>
  </tbody>
</table>
</form> 
</body>
</html>


I've '//' out the problem line; but I'm sure the error is in the function ? validateNmbs( , ) I guess my first queston should be is that since 'fld' isn't a key word; why can't I use 'fldp' and 'fldc' for phone and cell? As you can tell, I'm getting snippets from folks and trying help me to put it all together. I'm sure it's probably something stupid like a ';' or ':' or something, but I don't have a book on JavaScript, just Php and Java, & Html. Different animals I know.

I've tried if fldc.value == fldp.value; if (fldc.value == fldp.value); with and w/out quotes, parenthesis, all which ways, then tried here to set the values to vars; but just can't get it to work. Without the '//' it sends anything to the (''fake'' server) at this point itself really, because I just want to be sure it stops the submit correctly. This excerpt part runs on it's own though, without the comparisson though .


OK, I ramble, yet in my defense after 7-9 hours longdistance on the phone with a coheart trying to do just this part, getting it from where we were to here, it's now early a.m. and we're burnt, she went to bed 2 hours ago!

Thank you for all your help

Reply With Quote
  #17  
Old May 6th, 2008, 07:04 PM
timidwind timidwind is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: May 2008
Location: AZ
Posts: 5 timidwind User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 2 h 24 m 11 sec
Reputation Power: 0
Thumbs up Thank All; for direct help; AND previous POST

Thank everyone for their time and reading long entries.
After finally turning in at @5am; waking at 11:30am; and getting right back in.......
IT'S RESOLVED!! I got it!!!!!!!

Frustration over, again thank you all for allowing me to air my problems and frustration code.

FYI: Originally, re: this validation of the phone (causing my first post) was being done with JavaScript 'onBlur'. Do wish could use it with this newer code; but tried and finally decided ... don't mess with it if it works!
1) with only the comparison of these phone entries being done there.
2) then 'trying' to go out and do regex/ereg in php..on them successfully.. but then...........
3) then trying to get back to JavaScript to finally stop submission based on regex/ereg results until the numbers were fixed

I was circling... wrong I'm sure. Then tried to do all in JavaScript with onBlur and couldn't seem to get it all done & working, until I found, after hours of searching some tutorial sites with some conceptually similar code I could adapt.

Just 4 days, long days, on 'n off, on the phone long-distance trying to solve just this ''round a bout!'

Here's what I/we (I) finally got working. My long distance coding buddy (whom FYI is the one with the 'not so helpful' JavaScript book. )

I didn't have to change the '//' code calling this function; other than removing '//'.


Code:
function validateNms(fldp,fldc)
{
   var strippedP = fldp.value.replace(/[\(\)\.\-\ ]/g, ''); 
   var strippedC = fldc.value.replace(/[\(\)\.\-\ ]/g, ''); 

  if (strippedP === strippedC)
 {
	  error = "The Phone and Cell cannot be the same.\n";
      fldp.style.background = 'PowderBlue';
      fldc.style.background = 'PowderBlue';
 }
 else if (fldp.value != fldc.value)
 	{
	 	   error = "";
	}
   return error;
}


Finally got it! So Jazzed. Just a bit of 'clean up for the rest of the vals' and we'll be good to go. ?
Again Thank you all for eMails and opinions and suggestions. It was Mittineague whom made me STOP and think my logic through again, thank you. If you were having trouble understanding my explanation; Now you can imagine how spinning my head was... I thought I understood it!

Thank you for all your help === NO LONGER confused

If anyone wants the entire code for all the pages, ( doubt it really) eMail me at timidwind@yahoo.com

Bye all. Good programming.


PS: to kode_monkey
Quote:
"In computer science everything is possible"

In our (my 'coding buddy' & I) ...averaging @ 10 years each (neither consecutively) floating with different languages including:

Basic, Assembly, COBOL, Programming Logic(yeah forgot a lot about that one huh?), Pascal, Visual Basic,
Visual C++, C, C++, PHP, HTTP/HTML, Java, ...and still some others that fall under the category as obsolete.

.. some in college years ago, ...some others by trying to teach myself/ourselves as the needs arose; We generally & eventually have 'gotten it done' unfortunately, without the opportunity of these types of forums.

Point??? So, when my 'coding buddy' and I get coding and run into a road block we used to say that 'between the two of us we make on h??! of a coding machine!' sometimes adding that 'if it's possible 'we'll find out how' and if it's not possible? 'we'll find out how to make it possible.' Only NOW we're so behind computer evolution and DevA Forums is here!!!! Thank Goodness.

So... yes: Totally agreed.
"In computer science everything is possible." ...I would add "..some of us bend programming to it's limits and then some, making it jump higher and go places and do things nobody even ever thought to go or do." (the latter because we've come up with some doozy solutions to unique problems; as well as with researching 'how to' do things, I've seen others do the same!)
Thank you all, your posts really helped.

Thumbs up and drink up if you want to ... To this site and other helpful ones around!

Reply With Quote
  #18  
Old August 12th, 2008, 12:31 PM
winotosw winotosw is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Aug 2008
Posts: 1 winotosw User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 25 m 53 sec
Reputation Power: 0
use jqSajax

You can use jqSajax (please search with Google) to call PHP method/function from javascript.

Quote:
Originally Posted by Evil_homer
Thanks to asgeo1 and stumpy for answering my previous JavaScript related query. However i've now come across another problem:

Is there any way to call a php function, or execute some php code using JavaScript. I've searched on google for a while but found no real solution.

Basically i use a form to call a javascript function, then i want that javascript to call a php function found within the same page, or failing that be able to execute a few lines of php script from within the javascript.

Any help greatly appreciated

Reply With Quote
  #19  
Old December 16th, 2008, 09:55 AM
poste9 poste9 is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Dec 2008
Location: Brazil
Posts: 1 poste9 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 9 m 2 sec
Reputation Power: 0
I made a tutorial to make this

http://www. postenove.com.br/blog/en/2008-11-25/jrc-javascript-remote-connection.pnhtml

Demo: http://www. postenove.com.br/projects/jrc/

Reply With Quote
  #20  
Old January 7th, 2009, 01:14 PM
narfy892 narfy892 is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jan 2009
Posts: 2 narfy892 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 19 m 30 sec
Reputation Power: 0
get the variable of a function into the php code

Quote:
Originally Posted by hasantayyar
The simple solution for "How can i call PHP functions from Javascript?"

(i didnt test on i.e. or opera... i tested this on firefox!)

Here you dont need to use XMLHttpRequest or any other complex things.
Code:
// .... here some php lins... variables o some functions....

//... maybe some post variables an some new values.... proccessed over post variables....


<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php for($i=0; $i<10; $i++) echo $i; //maybe a function ?>";
}
</script>

<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>


thats all..


Hello,
Iíd like to get the variable police = policeFromJavascript into my php code. How can I do it that way?
<script type="text/javascript">
function showDirPhoto(){
document.getElementById('JavaSidebarPh').innerHTML = "<?php for($i=0; $i<$nbFolderPhoto; $i++){print "<a onMouseOver=`showDirPhotoPhoto($i);`>$photoNameDir[$i]</a><br/>"; } ?>";
}

function showDirPhotoPhoto(police){
document.getElementById('JavaSidebarPh1').innerHTM L = "<?php for($i=0; $i<$nbPhoto[policeFromJavascript]; $i++){print $photoDir[policeFromJavascript][$i];} ?>";
}
</script>

Reply With Quote
  #21  
Old January 9th, 2009, 07:39 AM
narfy892 narfy892 is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jan 2009
Posts: 2 narfy892 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 19 m 30 sec
Reputation Power: 0
any solution for firefox

Quote:
Originally Posted by narfy892
Hello,
Iíd like to get the variable police = policeFromJavascript into my php code. How can I do it that way?
Code:
<script type="text/javascript">
function showDirPhoto(){
document.getElementById('JavaSidebarPh').innerHTML   = "<?php for($i=0; $i<$nbFolderPhoto; $i++){print "<a onMouseOver=`showDirPhotoPhoto($i);`>$photoNameDir[$i]</a><br/>"; } ?>";
}

function showDirPhotoPhoto(police){
document.getElementById('JavaSidebarPh1').innerHTM  L = "<?php for($i=0; $i<$nbPhoto[policeFromJavascript]; $i++){print $photoDir[policeFromJavascript][$i];} ?>";
}

</script>


Ok I found an alternative with a double loop. Itís working fine with IE7 but why isnít it working with firefox.

Code:
function showDirPhoto()
{
	document.getElementById('JavaSidebarPh').innerHTML   = "<a onmouseover=`document.getElementById(\'JavaSidebar  Ph1\').innerHTML = \'<a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/001.jpg\\\');\\\">001.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/002.jpg\\\');\\\">002.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/003.jpg\\\');\\\">003.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/004.jpg\\\');\\\">004.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/005.jpg\\\');\\\">005.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/006.jpg\\\');\\\">006.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/007.jpg\\\');\\\">007.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/008.jpg\\\');\\\">008.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-06-14/009.jpg\\\');\\\">009.jpg</a><br>\';`>2008-06-14</a><br><a onmouseover=`document.getElementById(\'JavaSidebar  Ph1\').innerHTML = \'<a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-10-19/006.jpg\\\');\\\">006.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-10-19/007.jpg\\\');\\\">007.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-10-19/008.jpg\\\');\\\">008.jpg</a><br><a onMouseOver=\\\"p002(\\\'site/foot/pictures/2008-10-19/009.jpg\\\');\\\">009.jpg</a><br>\';`>2008-10-19</a><br>";

}

Reply With Quote
  #22  
Old April 12th, 2010, 09:32 AM
jch8183 jch8183 is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Apr 2010
Posts: 1 jch8183 User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 3 m 12 sec
Reputation Power: 0
You are the mother-f-ing man!

Quote:
Originally Posted by hasantayyar
The simple solution for "How can i call PHP functions from Javascript?"

(i didnt test on i.e. or opera... i tested this on firefox!)

Here you dont need to use XMLHttpRequest or any other complex things.
Code:
// .... here some php lins... variables o some functions....

//... maybe some post variables an some new values.... proccessed over post variables....


<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php for($i=0; $i<10; $i++) echo $i; //maybe a function ?>";
}
</script>

<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>


thats all..


You have no idea how much easier you just made my job and/or life. You are the man. I would like to add that "kode_monkey" is a pretentious fartknocker. Booya!

Reply With Quote
  #23  
Old June 30th, 2010, 06:41 AM
LordMX LordMX is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jun 2010
Posts: 1 LordMX User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 8 m 53 sec
Reputation Power: 0
Hi, if you want easy way to call php function from javascript I suggest to take a look here


h t t p://myitviewoflife.blogspot.com/2010/06/japi-direct-direct-call-php-methods.html

Cheers

Reply With Quote
  #24  
Old September 12th, 2011, 03:24 PM
AD5XJ AD5XJ is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2011
Posts: 3 AD5XJ User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 12 m 37 sec
Reputation Power: 0
OK you guys seem to be more helpful than another web developer forum I have tried, so here goes.

I have created javascript methods that create and display a faux analog meter given the min, max, ticks, etc. to display a numeric value.

I wish to get that numeric value from a public web page (textpage.txt) on a public server external to my site.

I think that I can get the page text using cURL methods in a php script, but as with some of these posts I need to get the text into a string var of a javascript parsing routine.

So how do I go about all that ( in simple terms for my simple mind)?

Reply With Quote
  #25  
Old September 13th, 2011, 02:34 PM
AD5XJ AD5XJ is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Sep 2011
Posts: 3 AD5XJ User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 12 m 37 sec
Reputation Power: 0
Quote:
Originally Posted by LordMX
Hi, if you want easy way to call php function from javascript I suggest to take a look here


h t t p://myitviewoflife.blogspot.com/2010/06/japi-direct-direct-call-php-methods.html

Cheers


Thanks for this. It is the only pertinent and appropriate solution to my question. However, I find that the cURL call is only returning the cryptic message "Some error occured".

I picked an arbitrary page to test with and I am still stumped.

Here is my PHP code:

Code:
<?php 
include('jAPI-CORE.php');


// class to get text of external page

class GetHtml
{

    public function getPage() 
    {
        curl_init("http://www.swpc.noaa.gov/ftpdir/latest/wwv.txt");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (curl_exec($ch) === false) 
        {
            return "Error: " + curl_error($ch) + "<br />\n";
        }        

        else 
        {
            return curl_multi_getcontent($ch);
        }
    }

}

//Create new instance of jAPIBaseClass with names 
//of all classes that you want to use them separeted with comma...

new jAPIBaseClass('GetHtml');
?>


The web page has :
Code:
	<script type="text/javascript" >
	  document.write("<p>Getting page...</p>");
	  document.write(GetHtml.getPage());
	</script>


I have tried a number of things in the PHP but to no different result.

=== UPDATE 15 Sept 2011 =====
Although it is not my default browser and I only use it for compatibility checking, Google Chrome has a debug console that is useful. Running this script provides a message that says the return value is described as javascript but is returned as MIME type HTML. This message does not appear in the FireFox or IE debug console output. Anyone have ideas?

Last edited by AD5XJ : September 15th, 2011 at 06:14 PM. Reason: UPDATE

Reply With Quote
  #26  
Old January 8th, 2013, 09:58 AM
Xaxis Xaxis is offline
Registered User
Dev Articles Newbie (0 - 499 posts)
 
Join Date: Jan 2013
Posts: 1 Xaxis User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 5 m 15 sec
Reputation Power: 0
jquery.php - a plugin solution to calling PHP functions within JavaScript

I recently published version 2.0 of jquery.php, my own solution to the problem of calling and using PHP functions within javascript: h t t p s://github.com/Xaxis/jqueryphp

I've developed a few different ways in which one can use PHP in there JavaScript ranging from arbitrary execution of PHP strings to sending JSON formatted blocks of PHP pseudo-code.

In addition, function chaining is supported between PHP function calls.

I hope this helps anyone who is interested.

Reply With Quote
Reply

Viewing: Dev Articles Community ForumsProgrammingJavaScript Development > Calling php functions with JavaScript


Developer Shed Advertisers and Affiliates


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.

© 2003-2014 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap