Javascript get output from separate php script - php

I want javascript to be able to call a php script (which just echos a string) using jQuery.
I think $.get is the right way, but not too sure.
I then want to use the returned string as a javascript variable.

$.get() is the way to go, indeed.
First of all, you will need a page / url that outputs the result of the function you want to use (for example, *www.yoursite.com/test_output.php* ). You should create that page and call the function you want to use there.
Also keep in mind that I said output, not return, because .get will fetch the output of the http response, not the returned value of the php function.
So if you have the following function defined in your site (you can also define it in test_output.php, of course):
<?php
function say_hello() {
return 'hello world';
}
?>
In test_output.php, you will need something like this:
<?php
echo say_hello();
?>
Then on the client side, you need some JavaScript / jQuery:
var data_from_ajax;
$.get('http://www.yoursite.com/test_output.php', function(data) {
data_from_ajax = data;
});
Now you have the output of the ajax .get() function stored in data_from_ajax and you can use it as you please.

$.get() is the right way.
$.get('ajax/test.php', function(data) {
// use the result
alert(data);
});

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.

call a php function from jquery

I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

Using a php function in javascript

I need to use a php function inside this script which converts the ID into a required format.
function onlineStatus() {
$.getJSON('updateusers.php', function(data) {
$('#users').html('');
$.each(data, function(i, item) {
$('#users').append('[<span>'+ item.userid +'</span>]');
});
});
setTimeout("onlineStatus()",30000);
}
I have tried the following in various ways but I either get nothing or it fails with a missing ) after the argument list.
$('#users').append('[<span>'<?php nameFormat('+ item.userid +') ?>'</span>]');
I would appreciate your assistance.
PHP functions can only be executed on the server-side. You should probably translate the nameFormat function into javascript so you can use it on the client-side.
If you are trying to run this command on the server side before sending the script to the user, you have forgotten to echo the statement. Either type
$('#users').append('[<span>'<?php echo nameFormat('+ item.userid +'); ?>'</span>]');
or
$('#users').append('[<span>'<?=nameFormat('+ item.userid +')?>'</span>]');
... unless ofcourse the function nameFormat allready does an echo.
It's one side connection. You can use javascript in php, but you can't use php in javascript.
For example:
You can assign variable in php, and than use it in JS.
var a = <?php echo $a ?>;
The same thing you can do with functions ;)

getting a value from a php return in javascript

I'm using jquery's $.get() to find out how many entries are in a table. I want the returned value to be an Int but it seems to be something else. How do I work with this? this is the code I have. I'm sure I'm just going about this wrong. My background is many java.
var num = checksize();
function checksize(){
$.get("../php/checktablezie.php", function(data){
return data;
});
}
You cannot do it like that. $.get is an asynchronous request, so your checksize() function will return instantly. Your anonymous function will be executed when the Ajax call is done, but that will be after checksize() has been returned.
Instead, you'll have to put whatever should be done with num inside your anonymous function, like this:
function checksize(){
$.get("../php/checktablezie.php", function(data){
num = data;
//The code that is in need of num should be put in here.
//e.g., if you're updating the GUI with the value, put that code here.
});
}
Can we write functions like that for ansycronous ajax calls , as it may complete the call in parallel.

Categories