Call a php method from javascript - javascript

I use this simple javascript code to call a php function from javascript.
var a = new XMLHttpRequest();
a.open("GET","save.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
alert("Worked");
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
In this example I have a php function save() contained into save.php file.
I have some questions:
1) How can I call a php function that it is located into the same file where there is the javascript function? (I would to call a php method declared into the same file where there is the javascript caller)
2) Is possible to pass also an php array as parameter?

First: You are not "calling a function". You are making a request to a server. The request is "interpreted" in php, and php has a function defined that is called. Js never calls php directly (one is front side, one is back).
To answer your questions:
You need to make the request to the same page you are displaying, but your js will also be executed.
Yes, but I suggest a post not a get for this (use var_name[] for array, where var_name is the name of the array).
As side notes:
Having both php and js in the same file is usually a bad idea. Try to isolate the front-end from the back-end as much as possible (it may be hard at first, but it will save you from huuuge headaches).
The script you are using is fine for simple things, but lacks lots of things (what if destination was moved and you get a redirect state, what if is unreachable, what if you need a callback, etc.). You are also limited at GET, and for some thing you may prefer POST method. I suggest using js lib for your requests (like jQuery ajax, prototype ajax, etc.) that take care of this things. Or you can extend your script of course.

You have to use ajax call as described manner--
On javascript side on save.php page-
$.ajax({
type:"POST",
data:'demodata',
url:"save.php?action=php_function", // place your php function name here
dataType: "html",
success:function(response){
alert(response); // It will alert value returned by php function
},
failure:function(response){
alert("there is an error.");
},
});
On PHP side on save.php page-
<?php
if(function_exists($_GET['action']))
{
$_GET['action']();
}
else
{
echo 'There is some error.';
}
function php_function()
{
// some code
echo "result";
}
?>

In general, passing an array between PHP and Javascript is better done using a JSON document as interchange format.

You would have to detect the request was made via ajax so that you can run the save() function, or if not then output the page normally, with the JavaScript caller included.
There are a number of ways to detect ajax, one would be to set the X-Requested-With header, which you can check on the PHP side.
save.php
function save(){
// some PHP code here
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
// request was made via ajax, call the function
save();
exit(); // exit so no page content is sent via ajax
}
// output the page content including JavaScript caller
JavaScript:
var a = new XMLHttpRequest();
a.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // set the header
// continue with your XHR code
The best way to send an array would be to JSON encode it before sending via POST, then JSON decode on the PHP side.
JavaScript:
a.open("POST","save.php");
a.send('json=' + encodeURIComponent(JSON.encode(myArray)));
PHP
function save(){
$myArray = json_decode($_POST['json']);
}

Related

Why is the SESSION variable not accessible in the AJAX call?

I'm using an AJAX call in my script to fetch some data from my php script.
The AJAX call properly executes, I've tested that so far. But unfortunately, the SESSION variable doesn't seem to be available.
I'm currently refactoring some code and this AJAX call goes to some code which before was inside the same file as the scriptcode. There, the respective php code still executes and the SESSION variable definitely is available there, otherwise the whole page would break (probably).
So I wonder whether I forgot to include something in my php file or something of this sort?
EDIT: I'll try to give minimal example of what code is behind the described behavior.
Code in Calling.php (yeah its javascript, but the author (not me) once decided to make a php file which contains both HTML, javascript and php...):
<?php session_start(); ?>
<script>
//Lots of Code
function Caller(){
$.ajax({
type:"POST",
url:'called.php',
success: function(data){
//debugging function taking data;
},
error: function(xhr, statusText, err){
//debugging function taking xhr.status
}
}
)
}
//Lots of Code
</script>
Code in called.php
<?php
$test = $_SESSION["loggedUser"];
echo $test;
?>
Ajax calls are not the same process as the original page being served, and require session_start being called again for each request.
You can do this safely (without an error or warning if it has already been called) like so:
if ( is_null($_SESSION) || !$_SESSION )
{
session_start();
}
This should live in your bootstrap or index file, and should always be called/included/required from all requests to php, before any request-based logic runs.

on html keyup i want to call a php page and get the variable value from there and add it to an HTML content

I know its super basic and probably simple as well, but i'm really stuck.
just trying to get data from php in an event of onkeyup, and post it into the HTML page.
this is my HTML
<input id="dell" type="text" onkeyup="dell_function()"<br>
<p id="gimr">get her the php variable var.</p>
php file:
<?
$var=11;
echo $var;
?>
Now i need to write the dell_function() which i want to open the php file and get the $var value, and post it as a string in here:
<p id="gimr">get her the php variable var.</p>
i know there is ajax involved but i really tried but couldn't figure it out, so how do i write the dell_function?
Ajax is really simple, especially if you are using JQuery. Here is how it would look in jQuery:
function dell_function() {
$.ajax({
url:"test.php", // replace test.php with the name of your PHP file
success: function(data) {
$("#gimr").html(data);
}
});
}
The jQuery documentation describes loads of other cool things you can do with Ajax : http://api.jquery.com/jquery.ajax/
function dell_function() {
var xhttp = new XMLHttpRequest(); // creates a ajax request object
xhttp.onreadystatechange = function () { // will fire when the status of the request changes
if (this.readyState == 4 && this.status == 200) { // checks if the current state indicates that the content has been loaded successfully. readyState=4 means that the request has been completed and the status 200 means that the request returned http status code 200, which means the server response is OK (404 would mean file not found, 408 means timeout, etc - you get the idea).
document.getElementById("gimr").innerHTML = this.responseText; //this will put the response text as html inside the "gimr" element.
}
};
xhttp.open("GET", "YOUR_PHP_FILE.php", true); //the first parameter sets the request method, the second defines the url, and the third defines if the data should be fetched asynchronously.
xhttp.send(); // sends the requests to the specified url.
}
Replace "YOUR_PHP_FILE.php" with the url to your php file.
Btw, take a look at jquery - it makes things like this alot easier ;D

ajax not reaching php side

I want to get rid of my html form submits and replace them by Ajax ( X M L H t p Request). I have set the form return value to "false" and I have written a small test to test the Ajax mechanism.
At the Java script side I do receive the ready state 4 and status 200, so sending data succeeds apparently, but at the PHP side the variables never arrive.
I try to pick them up the usual way with the POST method, the same way like I did before when receiving html submits, of which the simplified form is:
$x = $_POST['x'];
echo $x;
'x' having been sent with Ajax, state 4 , status 200.
Can anyone tell what am doing wrong?
Thanks a lot.
most likely you are posting JSON data? Try this snippet:
switch ($httpMethod) {
case 'POST':
$rest_json = file_get_contents("php://input");
$jsonData = json_decode($rest_json,true);
foreach($jsonData as $item){
var_dump($item);
$studentsCollection->insert($item);
}
$response = $studentsCollection->find();
break;
This is from a simple rest api I was using. Just change it to suit yourself without a verb switch statement.
Perhaps your ajax request is being submitted via GET instead of POST. Try $_GET instead of $_POST, or use $_REQUEST to cover both your bases. If you're not using jQuery, I'd recommend using it, ajax is a lot easier with ajax(), post(), etc.
$('form').submit(function(e)
{
e.preventDefault();
$.post("test.php", $(this).serialize(), function(result) {
console.log(result)
});
});
I suggent check the header of your ajax requests (in the chrome or firefox), the you can see if really your data is passing to the PHP side.
To find the issue you can use debug tool Firebug is good to to debug ajax request.
using Firebug you can see the ajax call.
You can see the parameters you send.
You can see the respond of the ajax request.
My suggestion is use Jquery for your javascript function.
Jquery ajax call up code -
$.ajax({
type: 'POST',
url: 'ServerPageUrl.php',
dataType: 'json',
success: function(data){
if(data==true)
{
alert("OK");
}
else
{
alert("Error save data");
}
}
});
You can learn more about jquery ajax from jQuery.ajax()
More help full page
Thanks.

Not getting the success callback for an ajax query to my php page

Edit: changed $.alert() to alert()
I've got a file, planner.php that uses JQuery to send an ajax request to the same page.
Using the debugger, I can see that the php correctly gets the request, accesses my database, and then sends the data. However even after sending it I get no success callback in the javascript. What's wrong?
JQuery:
$(function()
{
$.post('planner.php', {"want": "keys"}, success_func, 'json');
});
function success_func(result)
{
//This is never called :(
alert("Worked");
}
PHP:
<?php
require_once "./php/couch.php";
require_once "./php/couchClient.php";
require_once "./php/couchDocument.php";
if (count($_POST) > 0 && array_key_exists("want", $_POST)) {
$couch_dsn = "http://localhost:5984/";
$couch_db = "subjects";
$client = new couchClient($couch_dsn, $couch_db);
header('Content-type: application/json');
$response = $client->getView('subject_views', 'keys');
echo json_encode($response); //This all seems to work fine
}
?>
It's that simple. All of the PHP code there is just accessing couchDB which you don't have to worry about because I know that $response is set correctly.
For knowing where the ajax call is done or faced a error
$(function()
{
$.post('planner.php', {"want": "keys"},function(){
alert( "success" );
})
.done(function(){
alert("second success");
})
.error(function(){
alert("error");
});
});
link : http://api.jquery.com/jquery.post/
This is probably be cause there is no such thing like $.alert(), use simple alert() instead.
Also your success_func is declared below the ajax call, move it up before $.post();
EDIT:
as the function is declared, there is no need to type it before executing.
you can use like that it may be your sucess function not calling
var data = 'want=keys';
$.post(
'planner.php',
data
).success(function(resp){
json = $.parseJSON(resp);
alert(json);
});
Credit to vivek for giving me a method to work out the problem.
Basically I fundamentally didn't understand how php worked. The code for sending the POST response was halfway down the page, so PHP was sending back the entire page along with any extra json I had encoded, and then JQuery attempted to parse this html page as json, failed, and then didn't run the success function because it never succeeded in its request. Read this answer for some more insight
The obvious solutions are:
Make a new page for the response
Put the php at the top of the
page.
I ended up going with option #2 for simplicity's sake.
Thanks everyone!

use javascript variable into python Block

I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).

Categories