简体   繁体   中英

Passing a Javascript Variable to PHP When It Was Inserted By AJAX

First of all, thanks so much to everyone who has helped me on this site so far. You guys have been amazing, and really saved my life multiple times in trying to get my thesis finished.

Here's the deal. I am creating an experiment, which runs on one page and reloads content out of a php file via ajax for each trial. For each trial, I need to log the time that the subject clicks a certain button, and a couple pieces of information about the trial, because they are randomly selected, so I need to be able to link the click time to a certain trial.

So far everything has been working great. I have it set up so that I am loading and running the PHP scripts with ajax on each click, and I have injected a little script section that contains all the important variables about each trial. The PHP script that collects the time is working perfectly, and the script that collects the trial information is running, but it can't manage to $_GET the javascript identifying variables properly.

So close, yet so far! Can anyone help me out? I just need to be able to grab the javascript variables off the site, then I'm good to go.

Here's all my content, so you can observe and play around with it.

The experiment page . I have it set up to pop up an alert containing the information straight from the JS variables after each click on the trial it's going to pull up next, so you can be sure that they are loading correctly.

My backend JS logic . The important stuff is all the way at the bottom of the script, under the category "Audio Logic"

The log file . Each time the experiment is run, all the data pops up in here. You'll notice that although the PHP script runs, it just doesn't output the variables that its getting from the JS.

...and here's the PHP code I have that's supposed to get the JS variables. (loginfo.php)

$trialID = $_GET['trialID'];
$type = $_GET['type'];
$trick = $_GET['trick'];
$file = "log.txt";
$fh = fopen($file, 'a') or die("You just failed the entire experiment");
fwrite($fh, "\n Trial ID: ".$trialID." | Trial Type: ".$type." | Trick? ".$trick);
fclose($fh);

This code is called after the variables have already been loaded in, and I have shown them to be properly loaded with the little alert box. What am I missing? Why is this PHP code not picking the variables up?

Thank you so much for helping : )

Javascript does not deal with sessions, it deals with cookies (as a clientside only scripting language). As such, you need to pass parameters with GET request. Details are listed on jQuery's documentation:

$.get("test.php", { name: "John", time: "2pm" } );

好吧,除非您指定使用get(如果我没记错的话),否则jquery ajax默认会发布信息,因此请尝试将php中的$_GET更改为$_POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM