How to send multiple data from PHP to JavaScript - javascript

I don't know how to make a script for sending multiple variables from external php to javascript (jQuery)
For exemple:
<?php
$test = "tets"; -->this, I want something this, no echo
$dock = "dock"; --
echo $test; -->no, I don't want echo in PHP script
echo $dock; -->no, I don't want echo in PHP script
?>
and JS
<script>
function(){
$.post("url", {Some_Thing: "Some_Thing"}, function (data) {
alert(data); --> no, I don't want echo in PHP script
alert($test); --> this, I want something this, no echo
alert($dock);
}
}
</script>

Use a data structure, e.g:
<?php
$data = array('test', 'dock');
echo json_encode($data);
Then in your JS
$.post('url', {...}, function (data) {
alert(data[0]);
}, 'json');
^^^^^^^^--- tell jquery you're expecting back some json

you can just output your data in JSON format and then load the data to JavaScript using ajax like so:
<?
$arrayWithData = array('data1' => 123, 'data2' => 555);
echo json_encode($arrayWithData);
then call load the data using ajax:
$.ajax({
'url' : 'php-data-script.php',
'method' : 'get',
'dataType' : 'json'
}).done(function(data) {
// do whatever you want with the data
console.log(data);
});

Related

How do I run a php function and display the contents on page using javascript/jquery?

I have a php script which gets all my movies from a specific category and echos the html output using foreach loop placed inside of a function.
Instead of displaying the entire library at once I'd like to display it one category at a time by clicking a button (without page refresh) for example:
User clicks "Action" button:
<li>Action</li>
Which activates Action();
function Action()
{
jQuery.ajax({
type: "POST",
url: 'index2.php',
dataType: 'json',
data: {functionname: 'Movies', arguments: ['Action']},
success: function (returnData) {
data = returnData;
document.getElementById("Action").innerHTML = returnData;
console.log(data);
}
});
}
Action Div:
<a id="Action"></a></div>
<h3><span>Action</span></h3></center>
<div id="detail[19]">
</div>
The PHP function is Movies($var) when passing "Action" into it, it runs fine. So what do I do in order to get "Movies(Action)" to print to "detail[19]"
The PHP function:
function Movies($category){
$movies = glob('./uploads/Videos/Movies/'.$category.'/*/*.{mp4,m4v}', GLOB_BRACE);
global $images,$temp,$emtyImg,$actual_link,$dir,$rmvd;
foreach ($images as $image) {
$lookup[pathinfo($image, PATHINFO_FILENAME)] = $image;
}
foreach ($subs as $sub) {
$lookup2[pathinfo($sub, PATHINFO_FILENAME)] = $sub;
}
echo '<div id="detail['.$rmvd.']">';
include($_SERVER['DOCUMENT_ROOT']."/scripts/amzn.php");
foreach ($movies as $movie) {
*Lot's of useless code that echos div's with videos in them* }
echo '</div>';
$rmvd++;
}
I know I'm missing what I need for the PHP side and likely messed up the jquery bit. I'm at a loss at how to continue successfully.
You need to return a json object in php so that javascript can read it. For example:
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

Saving data into a text file sent as JSON with Ajax

I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)
jQuery code:
var users = [];
$.ajax({
type: "POST",
url: hostURL + "sendto.php",
dataType: 'json',
data: { json: JSON.stringify(users) },
success: function (data) {
alert(data);
}
});
PHP Code:
<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>
You must know that in PHP json_decode generates an Array that you can't write into an text file.
So only remove the json_decode command.
Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line
<?php
$json = $_POST['json'];
$data = json_decode($json, true);
file_put_contents('test.txt',implode("\n", $data));
?>

How to get data from one php page using ajax and pass it to another php page using ajax

I am trying to get data from one php page and pass it to another page using Ajax.
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id=data"
}
});
action.php :
<?php
$test= 1;
?>
data.php :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
<?php
$id = $_GET['id'];
echo $id;
?>
First of all, you need to echo your data in action.php, and second, use data parameter of AJAX request to send data to data.php.
Here's the reference:
jQuery.ajax()
So the organization of pages should be like this:
JS :
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php",
data: {id: data},
success: function(data){
// your code
// alert(data);
}
});
}
});
action.php :
<?php
$test = 1;
echo $test;
?>
data.php :
<?php
$id = $_GET['id'];
echo $id;
?>
Try to use $.get() method to get/send data :
$.get("action.php",{}, function(data){
//data here contain 1
$.get("data.php", {id: data}, function(id){
alert(id);
}
});
Just echo $test since just the data printed in page will return as responce to the query request.
action.php :
<?php
$test=1;
echo $test;
?>
Hope this helps.
For example,
Test
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="" src="action.js"></script>
action.js
$('.dataClass').click(function(){
var value=$(this).attr('data-value');
$.ajax({url:"Ajax_SomePage.php?value="+value,cache:false,success:function(result){
alert("success");
}});
});
Ajax_SomePage.php
<?php
$value = $_GET['value'];
echo $value;
?>
To get data as response in ajax call, you need to echo the result from your php page; action.php page.
echo $test = 1;
In your provided code
$.ajax({
url: "data.php?id=data"
} // closing bracket is missing
you are sending the string data as id to data.php page. Instead you have to append the result with the url using + symbol like shown in the below code.
$.ajax({
url: "action.php",
success: function(data){
$.ajax({
url: "data.php?id="+data
})
}
});

Accessing PHP JSON response using Javascript

Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.

do not receive the POSTed data in php code ( cakephp)

I am trying to use ajax for retrieving data from my server. I use cakephp and jquery.
The ajax code is as follows:
<script>
$(document).ready(function(){
$(".viewMode").click(function(){
$.ajax({
type: "POST",
url:"viewModeSwitching",
data: {
mobileViewCookie:12,
},
success:function(result){
// window.location.href = result;
}
}
);
});
});
</script>
...
<?php
echo "<br>";
echo $this->Form->button(__('Desktop View'), array('type' => 'button','class' =>"viewMode",));
echo "<br>";
?>
This works well, in firebug I see that the POST is sent with value mobileViewCookie=12.
The point is that my cakephp controllerfunction 'viewModeSwitching' cannot retrieve that data.
I checked $this->data, $this->params, $_POST, etc but no sign of the data that had been send in the POST message.
Any suggestions?
/Antoine

Categories

Resources