Jquery reload php value from .txt file - javascript

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.

Related

Exchange data php javascript

I have to select a file locally and use it in a python script.
I can't get the filename in order to have it in my ajax script that i use to call a php function.
This is my javascript, called onclick over Ok button:
function myAjax () {
$.ajax( { type : 'POST',
data : {},
url : 'action.php',
success: function ( data ) {
alert( data );
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
},
complete: function (data) {
setImg();
}
});
}
This is the php script used to call python script:
<?
function bb(){
$out = shell_exec( 'python heatmap.py');
echo "ok";
$fp = fopen('log.txt', 'w');
fwrite
($fp, $out);
fclose($fp);
}
bb();
?>
I have to take filename from Browse button and send it to ok button, where the python is called.
What is the correct way to exchange data from input="file" html, javascript and php?
I'm making a lot of assumptions here as the question is not entirely clear...
But presumably you're wanting the name of a file that has been selected from the OS. In JS you can do this using the following.
var fileName, oForm = document.getElementById('my-file');
oForm.onchange = function(){
fileName = this.files[0].name;
}
Then in your AJAX call, add the fileName variable to your data property.
data : {"filename":fileName},
And then in your PHP access it via the $_POST variable. So...
echo $_POST['filename'];

Passing a PHP variable to JavaScript For AJAX Request

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.

ajax recive variable value from php page

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/

ajax to post data and run php sql query on click

I'm trying to get it so when a button is pressed it runs a PHP function without reloading the page.
I have this button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button>Reserve Book</button>
</div>
Which I want to run:
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reserbook.php', 'book_id');
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
</script>
The PHP file is, reservebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES
('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
The js runs fine and makes the modal box fade then out displaying the variable passed to it, I just don't know how to get the post working.
I've been trying to udnerstand looking at other answers on questions such as calling php function from jquery? and How to pass jQuery variables to PHP variable?
I'm also not sure if I need a ajax specific script to be called at the start as right now all I have is
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
for my jquery.
It is probably something very simply, a rookie mistake, so all help is appreciated.
<script>
//called when button is clicked
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
//set parameter which you want to pass, url to be requested
$.ajax({ url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function(result) {
//after success it will be here and server have to send some data to be handled
alert(result);
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
What are you posting to reservebook.php? book_id is a string.You should send data in json or xml format to the server or using a query like key1=value1&key2=value2. $.post is a shortcut function i think it's better to use $.ajax and specify the type attribute POST.
You have to add a parameter to the post function to get the postdata in your php
{ jqbookID: book_id }
Try this :
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reservebook.php', { jqbookID: book_id }, function() {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
});

Passing session variable through AJAX to PHP file

My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;

Categories