Through ajax I ask for a php page which will get some information from database. When data are processed I echo them to some tag and through JS I target those tags and get their content. This is the only way how I can pass data between php and JS but I feel it's not quite right. Whats the best way to get value of php variable:
$var1 = 24515875;
into JS variable?
When calling between PHP and JavaScript using AJAX, I suggest you always encode using JSON (Javascript Object Notation).
<?php
// Set Header (Always should be first commands just in case of thrown errors)
header('Content-type: application/json');
$data = array(
'message' => 'Hello World',
'error' => false
);
echo json_encode($data);
?>
For the javascript, you can use XMLHttpRequest. I don't suggest using jQuery unless you need it for other aspects of your script.
function request(url,callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var json = JSON.parse(req.responseText);
if(typeof callback === "function") {
callback(json);
}
}else{
// Handle Error
}
}
req.open("GET",url,true);
req.send();
}
function callback_func(json) {
// Function gets called when Ajax is finished
console.dir(json);
}
request("ajax.php",callback_func);
I don't know if the following suggestion is too complex, but:
you could use jQuery Ajax Get for requesting JSON data from PHP.
This is good for passing arrays, like results sets from a database to the client-side.
On PHP side you would do a simple:
<?php
header('Content-type: application/json');
echo json_encode($myData);
?>
On JS side you would access this with:
$.getJSON( "getjsondata.php", function( data ) {
alert(data);
// do whatever, like appending to html element
// next code section is the answer to your question from the comment:
// how to iterate over the data result set?
// create new DomElement for insertion: here foreach row a new list item
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
// then insert the list items into a UL and append that to the body
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
// to access the individual properties you would do
alert(data.property);
});
http://api.jquery.com/jquery.getjson/
Related
I want to reload some data from .txt files.
The .txt files looks like this:
0;Player 1;10;Player 2;10;Player 3;0;Player 4;0;00:00:00;0;0
I tryed to reload the data "10" after Player 1 which had the PHP Value $s1s[2].
Following Code does read the whole txt file (I know), but I am not familiar with Javascript and I need to get the output of this single Value instead of the whole txt file.
PHP:
$spielfile = "data/$v/source.txt";
Javascript:
$(document).ready(function() {
setInterval(function() {
var randomnumber=Math.floor(Math.random()*100)
$("<?php echo "#staende_$v" ?>").load("<?php print $spielfile ?>");
}, 1000);
});
Any suggestion how I can do this?
you could search the string using a regex:
$(document).ready(function() {
setInterval(function() {
$.get(
"<?= $spielfile ?>",
{ "_": $.now() }, // disable response cache, multiple methods available.
function(data) {
var val = data.replace(/.*;Player 1;([0-9]+).*/, '$1');
$("#staende_<?= $v ?>").text(val);
}
);
}, 1000);
});
As Rory McCrossan mentions, you should be using an Ajax request returning data in JSON.
$(document).ready(function() {
setInterval(function() {
$.get(
"yourscript.php",
{ "_": $.now() }, // disable response cache, multiple methods available.
function(data) {
data.forEach(function(player){
$('<?= "#staende_$v" ?>').text("Player: " + player.id + " has data " + player.data);
})
}
);
}, 1000);
});
Your PHP should obviously load the text file, fetch the desired data and return in correct format:
<?php
$content = file_get_contents('./source.txt');
$content = explode(';', $content);
// The array should look like this for the js to function:
$data[] = [
'id' => 1,
'data' => $content[2]
];
// You can append more data for other players as well, easy to loop through in JS.
die(json_encode($data));
?>
There was also a little problem with browser cache, the second param in the $.get request would resolve that. You can do "<?= $spielfile ?>?time="+$.now() instead of using the second param.
I'm trying to access and display a variable within a json object on my page. Can anyone tell me why the variable gets displayed three times?
my_array.php
<?php
$my_data=array(name=>"john",age=>"30", city=>"copenhagen");
// sending output
header('Content-Type: text/json');
echo json_encode($my_data,true);
?>
My_page.php
<script>
$(document).ready(function() {
$("button").click(function() {
$.getJSON("my_array.php", function(data) {
$.each(data, function(key) {
$("#showdata").append(data.city);
});
});
});
});
</script>
//Show the data further down the page.
<div id="showdata"></div>
This displays
copenhagencopenhagencopenhagen
That's because you're iterating over 'each' data item from the json response that you receive and there are 3 key=>value pairs in my_array.php
Removing "$.each(data, function(key) {} " will return the value 'city' only once
$(document).ready(function(){
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
});
use this
my_array.php
<?php
$my_data = array(
name => "john",
age => "30",
city => "copenhagen"
);
// sending output
header('Content-Type: application/json');
echo json_encode($my_data, true);
?>
My_page.php
<div id="showdata"></div>
<button>Click Me!</button>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(e){
$.getJSON("test.php", function(data){
console.log(data);
$("#showdata").append(data.city);
});
});
});
</script>
this will give you only one copenhagen.
hope it helps...
First things first:
Set either:
header("Content-Type: application/json");
Above:
echo json_encode($my_data,true);
On your php file.
Or use the following snippet on your javascript:
$.getJSON("my_array.php",function(data)
{
data=JSON.stringify(data);
$.each(data, function(key)
{
$("#showdata").append(data.city);
});
});
Furthermore either in both ways above the returned data is an Object so in order to return correctly on your php file the data must be:
$my_data=array(array(name=>"john",age=>"30", city=>"copenhagen"));
Note: Associative arrays on php's json_encode turned into Objects. Non associative arrays on json_encode still remain an array
Im guessing because you have got three buttons on the page and the $.each takes the selector try:
$("button").click(function(){
$.getJSON("my_array.php",function(data){
$("#showdata").append(data.city);
});
});
you're iterating 3 times because of the three keys you have within the JSON object,
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
console.log( "key + " " + val" );
});
take a look at the JQuery documentation for further info.
http://api.jquery.com/jquery.getjson/
So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.
I dont know if i'm doing this the wrong way but I can't think of another way to do it.
I have a function in php that i'm calling with $.post and I want it to return an array. It sounds like I need to use a callback function and i'm trying but it just wont work.
Here is the code:
Jquery:
$("#e_del_date_btn").click(function(){
var new_date = $("#edited_del_date").val();
if (new_date == '') {new_date = $("#edited_del_date").attr("placeholder");}
var new_time = $("#edited_del_time").val();
var non = $("#non").html();
function getarray(new_date, new_time, non, callback) {
$.post('http://localhost:8080/wsad2/post.php',{'new_date':new_date,'new_time':new_time,'non':non}, function(data) {
callback(data);
});
}
getarray(new_date,new_time,non, function(data) {
alert(data[0]);
$("#odi_span").html(data[0]);
$("#e_del_date_pencil").attr("value",data[1]);
$("#e_del_date_pencil").attr("value2",data[2]);
});
$("#e_del_date").hide();
$("#e_del_date").css("z-index","0");
$("#po_main_div_test").css({ opacity : 1.0 });
});
PHP Code:
$returndata = array();
$returndate = $returntime = $returntext = '';
if ($fail == "false") {if ($row['complete'] == "no") {$returntext .= '(When Completed) ';}}
$returntext .= 'This order is scheduled to be delivered on<br>';
if ($fail == "false") {$returntext .= $new_date_2;$returndate = $new_date_2;} else {$returntext .= $orig_deldate;$returndate = $orig_deldate;}
$returntext .= ' between ';
if ($fail == "false") {$returntext .= $new_time_2;$returntime = $new_time_2;} else {$returntext .= $orig_time;$returntime = $orig_time;}
if ($fail == "true") {$returntext .= '<br>The New Delivery Date must be tomorrow or later.';}
$returndata[0] = $returntext;
$returndata[1] = $returndate;
$returndata[2] = $returntime;
//echo ($returntext);
return $returndata;
from some of the things I've read I might be trying to use $.post improperly, but basically I need to pass the date/time variables and then have the php return the value but they can be changed in the PHP code (which is the point of this, to edit a delivery date/time) so i need the value sent from the php back to the JavaScript in case it was changed, so i can update the attribute in case they decide to change it again w/out refreshing the page.
My problem is, the alert is always blank (the alert is for testing purposes) and basically it SEEMS to be working, but the 3 jquery calls in the getarray() function do not seem to be firing, or if they are they aren't working. right now the HTML field i'm updating doesn't change no matter what I do.
am I using the callback function improperly? I really need $.post to return an array, not just echo data so that I can update multiple fields instead of just one.
Also, i've left out some of the php code as I didn't think it was relevant. i just wanted to show the creation of the array and it being filled with data.
You can echo an array with PHP with JSON:
PHP:
http://php.net/manual/en/function.json-encode.php
Javascript:
http://api.jquery.com/jquery.parsejson/
Furthermore: How to send a proper POST request with JQuery:
$.ajax({
url: "test.php",
data: {my_$_Post1: "value"}
}).done(function() {
//whatever you want to do
});
Or(NOT RECOMMANDED):
Answer = $.ajax({
url: "test.php",
async: false
data: {my_$_Post1: "value"}
});
alert(Answer);
http://api.jquery.com/jquery.ajax/
One option is to print the data from your PHP code as a JSON (JavaScript) array. Then use JSON.parse() in your JavaScript code to parse the text and turn it into an array.
I am trying to do the following:
1: Load an XML file (with a list devices that has a static name, and a changing value and note) - this works
2: Load the XML (t=0) into varaiables for easy use in the HTML - this works
3: Load XML again (t=200ms) - this works (I think)
4: Check if any values have changed between the two XML's
5: If TRUE then update one or more <DIV id=>
Task 1: I guess I need to have the loadxml script run again whenever it is done or say every 200 ms
Task 2: I need to write and call a script that can update the <DIV id=>
I have made my code with only two parameters for easy understanding and put in comments where I guess I need to have something.
If this is a crazy overall architecture, please give me a direction to look to.
<?php
loadxml() ;
function loadxml() {
$feed_url = "demoxml.xml";
$xml = file_get_contents($feed_url);
$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);
for ($id=1; $id<=157; $id++) {
//dynamic
$generation='new';
$hs3device_note[$id][$generation]= $array['device'][$id]['#attributes']['note'] ;
if ($hs3device_note[$id]['current'] != $hs3device_note[$id]['new']) { ;
$hs3device_note[$id]['current'] = $hs3device_note[$id]['new'] ;
//CALL SCRIPT (like ReplaceContentInContainer) TO UPDATE <DIV id = $id> WITH CONTENT $hs3device_note[$id]['new'])
} ;
$hs3device_value[$id][$generation]= $array['device'][$id]['#attributes']['value'] ;
if ($hs3device_value[$id]['current'] != $hs3device_value[$id]['new']) { ;
$hs3device_value[$id]['current'] = $hs3device_value[$id]['new'] ;
//CALL SCRIPT (like ReplaceContentInContainer) TO UPDATE <DIV id = $id> WITH CONTENT $hs3device_note[$id]['new'])
} ;
}
//MAKE loadxml() call it self or restart in 200 ms
} ;
<script type='text/javascript' src='jquery-1.7.2.js'>
function ReplaceContentInContainer() {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
<DIV id="hs3device_note[34]['current']">...</DIV>
<DIV id="hs3device_value[34]['current']">...</DIV>
AJAX or Asynchronous JavaScript and XML is a method of sending requests to a server from JavaScript asynchronously (hence the name), with your question it would mean you can send a request to the server (at a specified interval) to see if some data has changed and if the PHP script evaluates true (ie it has) then it is sent back to the HTML page to replace the existing data that is being displayed.
function myXMLRequest() {
var request = $.ajax({
url: "script.php",
type: "POST",
data: { action:'testmyxml' },
dataType: "html"
});
request.done(function( msg ) {
setTimeout(function() {
myXMLRequest();
}, 5000);
if(msg != "") {
$( "#mydiv" ).html( msg );
}
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
$(document).ready(function() {
myXMLRequest();
});
Reference: JQuery API documentation.
http://api.jquery.com/jquery.ajax/
the script.php is your php script that does all the logic, data is sent back using PHP's 'echo' command, if not don't echo anything... (you can test if msg is empty client side). msg will hold all the information that has been echoed by PHP in script.php and can be put into a div as shown in my example.