Pass a php function instead of a file to jquery $post method - php

i started to learn jquery yesterday so i'm not so good.
I've a question:
as title there's a way to pass a php function instead of a file to jquery $.post method?
Here's an example of what i would to do:
function send(str)
{
$.post
(
"<?php PHPfunction(); ?>",
{send:str},
function(data)
{
$("#output-text").html(data.reply);
},
"json"
);
}
there's a way to do that? or i need always to pass a file to the first parameter?
Just another question:
how can i pass more than 1 row from php to jquery in the ajax reply?

You'll want to use AJAX to make a request for that function. For more information, see http://api.jquery.com/jQuery.ajax/. Google can also provide you a ton of examples because what you're asking is a fairly common problem with plenty of good solutions.

PHP is run on the server before the page is fully loaded, so you can't call a PHP function on the fly like that. Javascript runs within the browser afterwards, on the clients machine. They are two separate environments, code wise.
You're better off calling a page that uses the function, using Ajax or something.

Related

Passing jQuery Value to PHP

I am calculating the distance between two places using jQuery and I want to pass this value (pickup_distance) for use in PHP.
I am wanting to send this value to tariff.fare.controller.php for use in the following function:
private static function getFare($int_terminate) {
// Function
if pickup_distance(<-- jQuery Value) > 5 {
// Do Something
}
}
How could I go about doing this? I'm aware I can do this via AJAX but being quite new to programming I'm not quite sure how I can do this.
Any help would be much appreciated!
using Jquery it's quite easy:
var your_var_value=1200;
$.post("your_php_script.php", {var_value: your_var_value}, function(data){
alert("data sent and received: "+data);
});
then in your PHP script you get the variable like this:
$distance=$_POST['var_value'];
And what you echo in "your_php_script.php" is returned as the data variable.
As jQuery is client side code and PHP is Server side code, the variables must somehow be passed to the server.
There are a few decent ways of doing this, by far the most common is GET and POST variables.
then you can pick them up in php and do whatever you wish with it.
A very simple example is to have an iframe/php image whatever and just load the src with JavaScript or jquery file.php?EEEE=YYY then fetch that variable $_GET['EEEE']
Best way to do it is to use jQueries built in Ajax functionality. Either use .ajax or .post and send in your required parameters to your PHP script.

How to send data to a php script page during jQuery load and accept the data

I have a php function that builds a list of items for me. Im not sure but i read that you cant call a php function explicitly though jQuery/js.
So i saw that you can still call php pages like this:
$("#name").click(function(){
$("#div").load("script.php");
});
If i can call a php page like that, is there also a way to send it a URL when that page is loaded like this?
$("#name").click(function(){
$("#div").load("script.php", 'http://gdata.youtube.com/feeds/');
});
also another problem comes up that how do i make the script accept that string through from jQuery?
normally when you call a function you pass parameter with the call like so:
<?php makeList( 'http://gdata.youtube.com/feeds/' ); ?>
//on the function-side
<?php
function makeList( $feedURL )
{
//...stuff that uses $feedURL...
}
?>
Since i will make the function a script that runs upon being called how would i pass it a parameter?
I have no idea if this is possible or not and i would understand if this creates tons of security issues which makes it not acceptable.
You have the $.get and $.post methods in jQuery.
$.post('script.php', { url: 'http://gdata.youtube.com/feeds/' }, function(data) {
//data will hold the output of your script.php
});
The url is posted to your PHP script and you can access it through $_POST['url'].
See jQuery.ajax(), the 'sending data to the server' example.

JQuery .GET call/function

Ok so trying to get a page together that needs to connect to our SQL database. So on the javascript page I have functions that will autocomplete a textbox with data out of our mysql DB and then I need to send it to other functions and classes so that it will then look in our SQL DB and return some data. The problem I have is trying to get the .GET call to call in the php page, with the function that calls the class in which I need to get into for the SQL call. I have it setup somewhat but trying to figure out how to send the data through with it as well as just get clarification on how to work the .GET function.
Javascript page:
$.get("dsl_validate.php", calldsl(job));
Php Page
function calldsl($job){
var $dsljob = $job
hasfunctioncode($dsljob);
}
The hasfunctioncode function is in my DSL class page that will return the info I need. Any help on if I am in the right direction or not?
It looks like you're trying to physically call the PHP function calldsl() from the JavaScript. This... isn't right. (I'm assuming the $.get() you're using is from jQuery, please correct me if that assumption is incorrect.)
What $.get() does is simply call a resource on the web server. It doesn't have any knowledge of the server-side code (nor should it, for a number of reasons). From the perspective of the server-side code, there's no difference between a page being called via $.get() vs. one that's just loaded in a web browser.
What you essentially need to do is create a PHP page which accepts arguments either as a form post or query string (if you're using $.get() then the query string is the way to go), does its server-side logic, and then simply outputs the results to the "page." In the case of calling the page via AJAX as you are here, it's a good idea to render the page content using JSON notation. (Don't forget to set the content-type header to "application/json" as well.)
Then what you're getting on the client-side from the $.get() call is the response body, which would be that JSON data. It's really just a "page" like any other, the only difference is the content-type telling the browser that it's JSON data and that it doesn't have HTML, just JavaScript objects. The success callback on the $.get() call (the function you pass it, or create in-line) would receive that response data as an argument and can do what you need to with it.
The way I understand jQuery.get(), the second argument is the "callback" (http://api.jquery.com/jQuery.get/). The callback will hand the results from your server therefore should be a function. Currently your code actually executes the function "calldsl" where you should be only passing a reference like so...
Javascript:
$.get("dsl_validate.php", function(response){
alert("yay I haz ajax! "+response)
});
PHP: "dsl_validate.php"
echo "this is some data from the server";
No, your are not in the right direction. The first parameter of the get method have to br the complete URL of the page, not just the script (this works if the script resides on the same directory of the javascript file, though). The .php file shall return somehting "usable" for you javascript (JSON, or HTML, or text, or... whatever). The "calldsl" function will be called AFTER the data has been returned from the call. Something like that:
$.get('dsl_validate.php?value=somevalue', function(data) {
alert("Data returned from dsl_Validate: " + data)
});
i think you are better off passing the function as a param to your php page
$.get("dsl_validate.php?calldsl="+job, function(data) {
$response = $(data);// create a jquery object from the response
});
`
and in your php file
create a switch statement that call the function based on the parameter
Mmm I think you are wrong, the second argument on your get function is the javascript function that will process de data returned by "dsl_validate.php". I mean, if that page returns "foo", job will contain "foo".
But in my experience is better to use the autocomplete plugin from Jquery UI
jquery autocomplete plugin

Using Ajax to Send Data Back to the Server

I understand there is a method send for xmlHttpRequest objects, but I've been working on this site all day and I'm unable to find any halfway decent tutorials on the subject and my brain feels like mush. Ajax is hard.
What I'm trying to do is send data from one Javascript file back to a PHP script on the server, where the data is simply a string and a small number. Is this possible? Why can't I find a good article on the subject?
tl;dr How do I use the send method to pass a string and a number from a javascript file to a php file?
Why don't you user jQuery or similar library?
Sending a variables with jQuery will be simple as that:
$.post("save.php", { name: "John", time: "2pm" } );
In your save.php file you can handle POST variables as you wish:
$name = $_POST["name"];
$time = $_POST["time"];
You can check it out: http://jquery.com/
I think you are wasting your time trying to make self made methods ...
It's definitely possible. This is a really nicely organized tutorial that walks you through the XmlHttpRequest object, how to set it up, and how to consume it on the server.
The server-side code is PHP, and I'm more of a C# guy, and it made total sense to me. (Maybe I should switch to PHP??).
I hope this helps! Good luck.
EDIT: In response to a previous SO question, I put this jsfiddle together to demo how to use XmlHttpRequest. Hope this also helps.
lots of good links here, so I'm not going to add to that. Just as a sidenote, you're dealing with a light case of ajaxness here :) - typically you'd want to send something back from the server that changes the state of the page in response to what was sent from the page in the first place (in fact one might argue why you need ajax in the first place and not simply post, if the page's not supposed to change - but I can see how there might be situations where you'd want ajax anyway). I'm just saying that because you're going to encounter a lot of content about how to deal with the stuff sent back from the server - just making sure you're aware that's not needed for what you're trying to do (I'm always glad when I know what I can leave out in the first pass ;)
step 1:
get jquery. all you have to do is download the latest file and include it on your page.
step 2:
make 2 files:
somepage.html:
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$.get("someScript.php",
// data to send if you want
{
'someVar' : 'someValue'
},
// receive and do something with response
function(response){
alert(response);
} // function (response)
); // .get()
</script>
someScript.php
<?php
echo $_GET['someVar'] . " response!";
?>
step 3:
upload all your files to your server and go to somepage.html
That's all there is to it. Though, you would generally put that code inside some kind of onclick or whatever, depending on what you want to use ajax for. But the comments in there are pretty self explanatory. jquery is used to make the ajax request, with an example of sending data to the server-side script receiving the request (using GET method). You would do whatever in someScript.php but in this example, it simply echoes back the value you sent. Then jquery takes what someScript.php echoes out and just throws it in a popup.
Using jQuery, you can use the post method:
$.post("test.php", { name: "John", number: 2 } );
Behind the scenes, this uses xmlHttpRequest, have a look at the source to see how they do it.

Calling JavaScript with PHP

I want to call a PHP function when pressing on a button, sort of like:
<?php
function output(){
// do something
}
?>
<input type="button" value="Enter" onclick="output()"/>
I tried to make something like:
<input type="button" value="Enter" onclick="test.php?execute=1"/>
where test.php is current page and then by php
<? if(isset(&execute)){ echo "Hello"; } ?>
but it doesn't work.
Since PHP runs on the webserver, and buttons (and JavaScript in this case) appear on the client, you have to make an HTTP request to the server.
The easiest way to do this is to use a form. No JavaScript is required. You can add JavaScript (although it should be layered on top of a working non-JS version). Using JavaScript to make an HTTP request without leaving the page is known as Ajax, and generally achieved with the XMLHttpRequest object. There are various libraries such as YUI and jQuery that can do some of the heavy lifting for you.
I think using an AJAX call would do sort of what you are asking. I don't know PHP very well but you can use the following example, and add another variable with the data you are passing in to the server to indicate which function you want to call on the server. On the server you can add some "IF" statements that will call a certain function based on the name passed in and return the result.
Here is what you could use on in your javascript client using the jQuery library as a helper to do the AJAX call:
<input type="button" value="Enter" onclick="output()"/>
<script type="text/javascript">
function output(){
$.ajax({
type: "POST",
url: "submit_data.php",
data: "username=" + "SomeUser"
+ "&email=" + "someEmail#google.com"
+ "&functionName=" + "theFunction1",
success: function(html){
alert('sucess! Result is:' + html);
}
});
}
</script>
and you can use code such as this to catch the data your javascript is passing in. In this example you would want to call this file name as "submit_data.php" to match the javascript above:
<?php
// Variables
$Username = $_POST['username'];
$Email = $_POST['email'];
$FunctionName = $_POST['functionName'];
//Add code here to choose what function to call and echo the result
// If $FunctionName equals 'theFunction1' then execute theFunction1
// If $FunctionName equals 'theFunction2' then execute theFunction2
echo "You called A Page!";
?>
Here I am doing nothing with the "username" and "email" simply grabbing it and storing them into holding variables. But you can easily add extra functionality here, such as checking for a name of a function that you want to run.
PHP is server side and javascript is client side. So I'm not sure if that is really what you want to be doing??
Perhaps you could explain why you want to specifically call a php function?
I googled PHP function from button and found this question on webdeveloper.com
It doesn't use Javascript.
This is PHP you're talking about, not ASP.NET. In PHP, there is no such thing as a button click event. PHP runs entirely on the server and has absolutely no knowledge of client-side events.
Your first try won't work because the PHP code only runs when the page first loads. It does not run when you call a JavaScript function. Your second example won't work because JavaScript and PHP can't talk directly to eachother like that. Trying to directly call a PHP function from JavaScript just doens't make sense. Remember, PHP only runs on the server. By the time you get to the point where JavaScript can run, the PHP code has long since completed its work.
If you want to do something when a button is clicked, you have to explicitly make a request back to the server. You can do this by just POSTing the form as CTphpnwb suggested. Just be aware that this will reload the page and you will have to manually save and restore the page state, e.g. repopulate input boxes. There is no built-in magic that will do this for you.
Alternatively, you can get all AJAXy and do the POST in JavaScript. However, you will have to write the JavaScript to send the request and process the response, and write the server-side PHP code to handle the request. This gets a little awkward to do in a single page.
From : http://www.dreamincode.net/forums/showtopic72353.htm
You cannot directly invoke a PHP function from Javascript this way :
PHP code is executed on the server
HTML / Javascript are interpreted on the client-side.
One the HTML page has been generated and sent to the client (the browser), there is nothing more PHP can do.
One solution would be to use an Ajax request :
Your onclick event would call a Javascript function
This Javascript function would launch an Ajax request : a request sent to the server
The server would then execute some PHP code
And, then, return the result of that execution to the client
And you'd be able to get that result in your Javascript code, and act depending on what was returned by the server.
There are plenty of solutions to do an Ajax request :
You can re-invent the wheel ; not that complex, I should say -- but see the next point
If already using a Javascript framework, like jQuery, Prototype, ... Those provide classes/methods/functions to do Ajax requests
Googling a bit will get you lots of tutorials/examples, about that ;-)

Categories