obtaining PHP variable in jQuery AJAX - php

In my php file 'login_success.php', I have a the variable $_COOKIE["user"]
Would it be possible to return that variable within a jQuery Ajax statment such as this one. ive made a guess with Var UserName =:
function StartAjax(NameID){
$.ajax({
type: "POST",
url: "login_success.php",
cache: false,
data: "name=Peter&location=Sheffield",
success: function(html, status){
$("#"+NameID).append(html);
//$('#status').append(status);
var userName =
}
});

login_success.php:
echo $_COOKIE['user'];
Ajax asks for the page, returns the output/content (what is echoed). Please note: Javascript is client side. PHP is server side. So you can't directly access PHP variables, but as done above, PHP can "give" the client the info it needs. If you're sending a lot of data, you can json_encode it for the ajax request. (you can learn about JSON on your own)
Also note, Javascript can access cookies, but I'm assuming this is just a sample question.

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.

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.

How do i use JQuery Ajax to call a PHP file on the server side to return and execute javascripts?

The client website needs to do a cross-domain JQuery Ajax call to a php file on my server, the php file will query the database for a bunch of stored javascripts which then need to be sent back to the client and be executed on the client's website. This is what i have so far, haven't done the grabbing javascript from database yet and it works. Is this the best way to do this (assuming i can grab the javascripts directly from the database without adding the escape sequence when echo'ing back to the client)? Thanks.
This is what i have so far:
client side:
$.ajax({ url: "http://localhost:8888/test.php",
dataType: "script",
});
server side (test.php):
<?php
echo "alert(\"WORKS!\");";
?>
Review the ajax documentation and handle the success callback option on the ajax method:
$.ajax({
url: "http://localhost:8888/test.php",
dataType: "html",
success : function(data) { alert(data); }
});
As noted by Ricardo, your PHP script should echo HTML or some other content appropriate for your scenario.
See http://api.jquery.com/jQuery.get/
And http://api.jquery.com/jQuery.getJSON/

Refer jQuery .ajax Post to function

Is it possible to refer an AJAX POST to a specific function within a PHP file?
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: "some data...",
success: function(){
alert('Success!');
}
});
Or is there a way to have functions.php receive data and know what to do with it? If not, are there any other suggestions for getting data over to mySQL (using PHP/jQuery)? Thanks!
The data sent to the php file using POST can be accessed in php using:
$datasent = $_POST['name'];
Given that you sent data as:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
Not directly. You'd need to post certain data, and have PHP check the POST variables to choose the correct function.
Perhaps have a look at some tutorials (unfotunately the jQuery links for php tutorials are broken).
Is it possible to refer an AJAX POST to a specific function within a PHP file?
No. jQuery doesn't know what PHP is, even less what a PHP function is. jQuery talks to server side urls. Whether those urls are static html files, PHP scripts, Java servlets, Python I don't know what, CGI scripts, is not really important.
So you could use the data setting to pass parameters to this server side url which based on the values of those parameters could invoke one or another function.
If you want to call a specific function, change ur jquery:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {function:"doSomething",name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
In your php add:
call_user_func($_POST['function']); // This will call what ever function name is passed as parameter
function doSomething(){
echo $_POST['name'];
}

Categories