Jquery post variable to php and then send to .txt file?

391 Views Asked by At

My apologies 1st of all for the code Im about to post... What I want to do is use the JQuery post method or similar to post 2 variables to a php file and then have the php post it to a .txt file I need the post method to be in a function and when that function is called have jquery post the 'score' this is the function:

function onGameOver(){
if (-1 < score && score < 6) { doStuff(); }
 if (5 < score && score < 9) { doStuff2(); }
if (8 < score && score < 15) { doStuff3(); }
if (14 < score && score < 21) { doStuff4(); }           
if (20 < score && score < 27) { doStuff5(); }
if (26 < score && score < 31) { doStuff6(); }
if (30 < score && score < 36) { doStuff7(); }
if (35 < score && score < 51) { doStuff8(); }
if (50 < score && score < 69) { doStuff9(); }
//post method here
}

I've no idea how to go about this and I've tried but failed any ideas on how to set this up the vars I want to be posted are var hiScore and var userip

Thank you for any help sorry for no code to start off ! I dont have any exp with php nor the jquery post method. Thank you are reading.

2

There are 2 best solutions below

1
On BEST ANSWER

Here's a little inside in a jQuery ajax call and the php functions fopen, fwrite and fclose. You need to fetch var hiScore and var userip in your first file, create a new php file and put the contents for php in there.

AJAX CALL: SEE JQUERY AJAX

$.ajax({
    url:'file.php',
    type:'post',
    data:{hiScore:hiScore,
          userip:userip},
    success:function(data){
    alert('Success');}
});

WRITE TO FILE IN PHP: SEE PHP.NET

$hiScore = $_POST['hiScore'];
$userip = $_POST['userip'];
$file = fopen('file.txt','w+');
fwrite($file, $hiScore.'\t'.$userip);
fclose($file);
0
On
$('#mybutton').click(function(){
var hiscore = //define high score here
var ip = //same thing;

$.ajax({
type:"POST",
url: "process.php",
data:{ajax: 'true', ip:ip, hiscore:hiscore},
cache:false,
success: function(data){
 //do something with the success 
}
});
});

php

if(isset($_POST['ajax']) && $_POST['ajax'] == 'true'){
    $ip = $_POST['ip'];
    $hiscore = $_POST['hiscore'];
    $file = fopen('file.txt', w+);
    fwrite($file, $ip.", ".$hiscore);
    fclose($file);
}