简体   繁体   中英

How to store the input field value in PHP into database and then assign it to variable in javascript

So I'm working on Wordpress project. There are two separate pages. One is with form for user to submit where he can put his name. I then store this input value to custom table in database and redirect the user to another page where he can start taking the quiz. No problem here.

But what I want is for the user after submitting the form on previous page and after being redirected to be able to take the quiz with his latest typed in credentials that are retrieved from DB.

And the quiz is javascript based so I want to store the typed in credentials into javascript variable right before the user can start taking the quiz. I already use AJAX to access all the users in database. Here is how my code looks like so far:

script.js

jQuery.ajax({
    type:"POST",
    url: my_ajax_object.ajax_url,
    data: { 'action': 'call_my_ajax_handler' }
}).done(function(data) {
  console.log(data);
});

it consoles out all the names in database, like so:

[{"name":"laimis"},{"name":"jonas"},{"name":"jans"},{"name":"frank"},...

then I have a quiz code in javascript which inits new object for newly created user, like this:

function User (theName, theEmail) {
  this.name = theName;
  this.email = theEmail;
  this.quizScores = [];
  this.currentScore = 0;
}

var user1 = new User (theName.value, theEmail.value);

So how can I loop through the array of json objects to access the value laimis for example to assign it to variable in js?

Use JSON.parse to convert the JSON string into a real variable:

.done(function(data) {
  console.log(data);
  var parsedData = JSON.parse(data);
  var lastItem = parsedData.pop();//it will be an array, so just figure out which index you need
  user1 = new User(lastItem.name, lastItem.email);
})

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