Pass angularjs value to PHP variable - php

I am starting with angularjs with ngStorage. I can save and display data successfully.
I display value as before
{{myobj.session}}
I would like to pass whatever stored value into php variable. Shown below is my imaginary logic and I know thats not gonna work. My question is how to assign such value into PHP variable in a correct manner?
<?php
$name = {{myobj.session}}
?>

You can use this angular variable: students.tiffen_type
PHP variable : $value
<?php
$value = "{{ students.tiffen_type }}";
?>

You can do a ajax request like this:
$http({
url: "urltopost.php",
method: "POST",
data: {
data: variable
}
}).success(function(response) {
console.log(response);
});
And on the backend you can get the variable like this
<?php
$request = json_decode( file_get_contents('php://input') );
$variable = $request->data
From there you can do everything you want with that variable, still I'm not sure what are you trying to achieve.

You can't assign directly angularjs value to php variable, use the following method it will help you
$http({
method: "POST",
url: "test.php",
data: {
data: postvariable
}
}).success(function(response) {
console.log(response); //get the echo value from php page
}).error(function(response) {
console.log(response);
});
test.php
<?php
$data = json_decode(file_get_contents("php://input"));
echo $data->data;
?>

send.js
$http({
method: "post",
url: "ajax/request.php",
data: {
angular_var: $scope.angular_var // $scope.angular_var is angular variable e.g. ng-model="angular_var"
}, headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log(data)
});
ajax/request.php
$request_arr = json_decode( file_get_contents('php://input') );
$angular_var = $request_arr->angular_var;

Related

Ajax Post to PHP returning empty array

I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.
Ajax request in 'adopt.php':
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {'info': info},
success: function(data){
console.log(data);
}
});
ajax.php code:
if(isset($_POST['info'])){
$_SESSION['array'] = $_POST['info'];
}
back in adopt.php, later:
if(isset($_SESSION['array'])){
$arr = $_SESSION['array'];
echo "console.log('information: ' + $arr);";
}
in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)
Try below code i think you miss return ajax response
adopt.php
<script>
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {info: info},
success: function(data){
console.log(data);
}
});
</script>
ajax.php
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(["result" => "success"]);
}
To get the response data from PHP, you need to echo your data to return it to the browser.
In your ajax.php:
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(['result' => $_SESSION['array']]);
}
Your ajax.php is not returning any data.To get data at the time of success you need to echo the data you want to display on success of your ajax.

PHP cannot pass two parameter to another php using ajax

I need to call php and get data from another server and I am using proxy.php to call from ajax.
proxy.php
<?
header('Content-type: application/json');
$url=$_GET['url'];
$json=file_get_contents($url);
echo $json;
?>
And my code looks
function scanFunction(){
var url="http://address/scan.php?user=user1&video=video1";
console.log(url);
url = 'proxy.php?url='+url;
$.ajax({
url: url,
type: "POST",
data: {
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
}
else{
console.log(" error...");
}
}
});
}
And this code works fine when I use one parameter to the url passing to proxy.php where as second argument missing
That is
echo $url; inside proxy.php print
http://address/scan.php?user=user1
event I pass two argument like,
proxy.php?url="http://address/scan.php?user=user1&video=video1"
That is second argument video missing inside proxy.php and so I am not getting expected result.
You may be having issues with your GET variables in the GET['url'] variable.
Try encoding your url when you send it to proxy.php to avoid such issues.
var url = encodeURIComponent("http://address/scan.php?user=user1&video=video1");
url = 'proxy.php?url='+url;
Then on the PHP side you need to decode it.
$url=$_GET['url'];
if (is_string($url)) {
$url = urldecode($url);
}
proxy.php cannot know which arguments are meant for it, and which are meant for scan.php. Eg, When you call url:
proxy.php?url=http://address/scan.php?user=user1&video=video1
Your proxy scripts thinks that the query parameters are:
url:"http://address/scan.php?user=user1"
video:"video1"
But your intent was for everything after url to be one parameter. A better approach is to use POST parameters instead of URL query parameters.
$.ajax({
url: url,
type: "POST",
data: {
resource_url: "http://address/scan.php?user=user1&video=video1"
},
....
});
Now, in proxy.php:
<?php
header('Content-type: application/json');
$url=$_POST['resource_url'];
$json=file_get_contents($url);
echo $json;
?>
Use the data: property of the ajax call to pass as much or as many parameters as you like
function scanFunction(){
$.ajax({
url: 'proxy.php',
type: 'POST',
data: {
url: 'http://address/scan.php',
user: 'user1',
video: 'video1'
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
} else {
console.log(" error...");
}
}
});
}
Then build whatever you want from those parameters in the php script
Oh and you used type: 'POST' in your javascript, so you should be using the $_POST array in your PHP script.
proxy.php
<?php
$url = $_POST['url'] . '?user=' . $_POST['user'] . '&video=' . $_POST['video'];
$json=file_get_contents($url);
header('Content-type: application/json');
echo $json;
?>

$_GET the variable of javascript to php

my ajax is:
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: full_val+'='+add,
success: function(data)
{
}
});
if the javascript variable value changes depending on the conditions, then how will i $_GET[] the variable full_val? I want it to be something like:
$_GET[full_val]
is there a way to pass the variables of javascript to php?
If you want the literal index full_val, then use it in the query string:
data: 'full_val='+add,
So that in PHP, you'd be able to use $_GET['full_val']
Alternatively, you could also put an object in that field:
data: {full_val: full_val, add: add},
Here is the description:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
Your data just has the values and does not have the keys. See below for how to pass the keys and values.
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'plugins/add_friend.php',
data: {full_val:full_val,add:add},
success: function(data)
{
}
});
In your PHP use $_GET['full_val'];
send your values with data parameter correctly and add type:get to define GET method
add = 'request';
full_val = 'barrack obama';
$.ajax({
type: "get",
url: 'plugins/add_friend.php',
data: {'full_val':full_val,'add':add},
success: function(data) {
}
});
Then you will get values on php :-
use $_GET['full_val'] rather $_GET[full_val]
Try Using this
add = 'request';
full_val = 'barrack obama';
$.ajax({
url: 'add.php',
data: 'full_val='+add,
success: function(data)
{
alert(data);
}
});
You can use the .get() method. The variables you can set using an object literal. For example:
$.get("/plugins/add_friend.php", {
add: "request",
full: "Barrack Obama"
}).done(function(data) {
console.log("Status:", data.status);
console.log("Received:", data.received);
});
And the PHP could be done something like this:
$add = filter_input(INPUT_GET, 'add', FILTER_SANITIZE_STRING);
$full = filter_input(INPUT_GET, 'full', FILTER_SANITIZE_STRING);
echo json_encode(array(
'status': 'OK',
'received': "{$add} and {$full}",
));

Take html and variable with AJAX

I have this ajax code
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(html)
{
LastDiv.after(html);
}
});
I am new with this Ajax thing.
This code is to load getData.php file and send variables through type POST.
The variables are in this var ValueToPass = "lastid="+LastId+"&br="+br;.
Other thing this code does is return the getData.php's HTML after loading.
Probably with this. success: function(html)
How can I return this $br variable from getData.php after loading, so I can use it again through the next cycle. Cuz what happens here is that I can put the variable in the getData.php with the Ajax and working with it, but when the file getData.php is loaded, outside this file, the variable is not known(not declared). And I'm losing the counting :S
I want to return the HTML and the variable.
You can return json data in your php file like
$response = array ('br'=> $br, 'html'=> $html);
echo json_encode($response);
Here both html and data are returned.
And this to use it in your ajax callback :
success: function(data)
{
br = data.br;
LastDiv.after(data.html);
}
I'd consider setting a Session variable with the value from the $br variable passed via AJAX. Then when you call getData.php from another file or location, you can use the Session variable since session variables retain their value anywhere in the session.
You can try this to get the data from your `getData.php' :
$.ajax(
{
type: "POST",
url: "getData.php",
data: { ValueToPass: ValueToPass},
cache: false,
success: function(data)
{
LastDiv.html(data);
}
});
and in your getData.php you have to pass ValueToPass
maybe like this:
$ValueToPass = mysqli_real_escape_string($db, $_POST['ValueToPass']);
If I understand your question correctly, and if you want to return the $br variable then include it in a JSON object in the successs callback function. So, something like this (I'm not familiar enough with PHP so my PHP syntax might be incorrect):
// create JSON object
<?php
$result = array('br' => $br, 'html' => 'htmlContent);
echo json_encode($result);
?>
// return JSON object
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(result)
{
var $br = result.br;
LastDiv.after(result.html);
}
});

Posting data to php file

I have the following variable in Javascript. I want to know how to pass this data to a PHP so that I can display the contents of the data once redirected.
postData = {
'dates_ranges': datesAndRanges,
'action':'build',
'output_type': output_type,
'form_html': formHtml,
'width': formBuilder.width(),
'rules':validationRules,
'theme': theme,
};
Use JQuery post method to pass data to PHP file:
$.post("/path/to/script.php", postData, function(result) {
// work with result
});
In PHP use $_POST global to get the variables:
print $_POST['dates_ranges'];
print $_POST['action'];
// ...
using jquery it goes easy & clean like this:
$.post('script.php', postData, function(response){
// process/display the server response
});
you can use:
$.post("YOUR_URL", postData, function(response) {
// handle with response
});
OR:
$.ajax({
url: YOUR_URL,
data: postData,
type: 'post',
success: function(response) {
// handle with response
}
});
And In your PHP file:
if(isset($_POST) && !empty($_POST)) {
$d = $_POST;
echo $d['date_range']; // and so more
}

Categories