Passing javascript variable to PHP function - php

I have this javascript code
<Script>
function getGroupId(){
var group=document.getElementById("selectedOptions").value;
var groupFirstLetter=group.substring(2);
}
</Script>
I need to pass the groupFirstLetter to a PHP function which will count how many users in this group and return the value to the javascript function.
Any ideas please?
Thanks,

You can use jQuery for that to post an AJAX request. See this example taken out of jQuery documentation:
$.ajax({
type: "POST",
url: "some.php",
data: {groupFirstLetter:groupFirstLetter},
complete: function(data){
//data contains the response from the php file.
//u can pass it here to the javascript function
}
});
The variable will be available in your PHP code as $_POST['groupFirstLetter'].
You can manipulate it as you wish then echo a response to the browser again and it will be available in the data variable.
references:
jQuery AJAX

As javascript runs on user's browser you have to do an http request to a php page. POST or GET can be used to send parameters.
To make a http call with javascript refer to this: HTTP GET request in JavaScript?

Use jQuery (jquery.com).
Dynamically load the php-file sending the variable using ajax like so:
$.post("file.php", {variable_name: value}, function(returned_data){
console.log(returned_data); //or do whatever you like with the variable
});
and your php-file will access the variable as:
$_POST['variable_name'];

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

How can I pass a variable from JSON to PHP?

I'm using JSON to produce some data on Wordpress which I need to store in a PHP session variable. Here's the current setup that I'm messing around with but having no luck:
jQuery(document).ready(function($) {
$.ajax({
url: 'url',
type: 'POST',
dataType:'json',
data: {foo: 145},
success: function(data){
console.log(data);
alert(data);
}
});
});
and the PHP:
session_start();
$_SESSION['bar'] = $_POST['foo'];
I can see the data in the console but nothing will display when I echo my sesh var. Using vardump returns an empty array. Where am I going wrong here?
(I realize there are plenty of other questions just like this, but believe me, I've tried them all - nada.)
Answer: You can't use javascript to store server side variables.
You must save the $_SESSION var in the PHP script that this AJAX calls. Which you have put URL?? In WordPress you can use JQuery to call a special hook which can be caught he functions.php that handles all AJAX.
There's info about this everywhere, see solution to this answer:
Using AJAX in a WordPress plugin
You would have to set a global variable for both languages and then transfer them via javascript you could do this on every page using php includes.

jquery post to a php page with javascript or php

I have one quick question for experienced ones.
I have a page that does a jquery ajax post to another php page with javascript in it.
My question is, will the javascript get executed as well?
Another question.
lets say, that instead of javascript, I have another jquery ajax post request to a third php.
Will any of the 2 work?
Unless the javascript in that "another php page" is actually returned to the client and somehow inserted into the DOM, the JS cannot and will not execute. The resulting output of an AJAX operation is returned as a string to the code that performed the ajax call. It's not interpreted/parsed except in a few very specific cases.
If you're using jQuery's AJAX function to send POST variables to a PHP file, only the backend code will be executed. However, upon success of the AJAX call, you can execute some more JS code as follows
//Define whatever variables you want to pass along to the PHP file
var variable = "";
$.ajax({
url: "file.php",
type: "POST",
data: "variable="+ variable,
success: function(data)
{
//Upon success of the call, you can execute JS code here
}
});
Additional info here

PHP: Multiple ajax request

I want a code for multiple ajax request. What happens actually is my first ajax request give me the response and in that responce function i m calling another function which having another website url. I want to send data to this new website using multiple ajax request.
Please help me out...
Thanks,
Prafulla
use global variables and manipulate your data in each request.
like:
var a;
$.ajax({
url:url_one;
success: function(data){ a =data; }
});
$.ajax({
url:url_two;
data: a //sends the data from the 1st request
success: function(data){
//do something with the data from the 2nd url
}
});
You can encapsulate your ajax call in function or event handlers as you need.
You can also manuipulate the data returned in variable a before sending it to the 2nd url.
Seems sloppy to me, but sould work.

transferring a javascript value to a php variable

What is the best way to transfer the following outputted value into a php variable?
$(document).getUrlParam("id");
Through an ajax post.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You should use JSON format to send and receive data from javascript to PHP. For example
function sendData(){
//with jquery, you can use `.post()`, `.get()` or for more control `.ajax()`
$.post(
//URL to send the data
url,
//data being sent, transformed to JSON
{dataSent: JSON.stringify(clientSideData)},
//Do something after sendind the data to server
function(dataReceived){
//transform data from json format to javascript object
var dataLog = jQuery.parseJSON(dataReceived);
//Do stuff
}
)
}
PHP:
//Receive data from POST
var phpVar = json_decode($_POST['dataSent'])
//send data back to javascript
echo json_encode(phpVar)
While all of these answers will get the value from javascript into the PHP script, I'd wonder if you need javascript at all.
From what I can see from a brief google the getUrlParam plugin is useful for getting and then breaking down the URL. Have you had a look at the variables available through $_SERVER? I'm sure you'd be able to find something suitable in there.

Categories