0

I am trying to use Axios within Vue to POST data set by the user to PHP. I am creating a JSON object using PHP and want to add filtering it to the object. I created filtering inputs for the user to apply and I want to take those user inputs and pass the values to PHP using Axios.

So what I have so far is:

onSubmit () {
axios.post('http://website.com/index.php', {
  'region': this.selectedRegion,
  'jobType': this.selectedJobType,
  'category': this.selectedCategory,
}).then(response => {
  if (response.data.error) {
    console.log('error', response.data.error)
  } else {
    this.postStatus = true;

    console.log('success', response.data.message)
  }
}).catch(error => {
  console.log(error.response)
});

}

So the data variables of selectedRegion, selectedJobType, and selectedCategories are set in Vue based on what the user sets in the input. The user then would need to click a submit button to run the onSubmit function. The trouble I am having now is taking that data and adding it into PHP.

Edit: Trying to clarify I little more. I want to take the data from JS and then be able to output that data in PHP after it is posted.

Edit2: I tried adding:

<?php
if(isset($_POST['region'])) {
  $region = $_POST['region'];
echo $region
    }

 ?>

to the PHP file to output the region value, but that then gives me an error saying the variable is undefined

user9664977
  • 789
  • 2
  • 15
  • 28
  • "taking that data and adding it into PHP"...it's not really clear what you mean. Are you asking how to write PHP code to receive the data in the request? It's essentially the same as receiving a normal postback, except you generally want to make sure it doesn't execute any other code or output any HTML (normally you might make the request to a PHP script specific for this action, or for a group of actions, rather than just your main index.php). But beyond that, you just receive the values as $_POST values in the normal way and process them. Then output JSON at the end instead of HTML. – ADyson Nov 05 '18 at 14:53
  • @ADyson Yeah I guess that's really what I mean. Sorry I'm more familiar with JS over PHP and just don't know the proper way to then take the posted data and output it in PHP – user9664977 Nov 05 '18 at 14:55
  • Any basic AJAX/PHP tutorial should show you the general idea. Have you done any research yet? – ADyson Nov 05 '18 at 14:57
  • 1
    Duplicate: https://stackoverflow.com/questions/18866571/receive-json-post-with-php – Quentin Nov 05 '18 at 15:20
  • "that then gives me an error saying the variable is undefined"...what does? PHP or, JavaScript? Bear in mind you simply echo the "region" variable back again, but your JS is expecting a complex JSON object from which it can extract a message (i.e. an object containing another object called "data" which itself contains a string property called "message"). If you simplify it to `console.log("success: " + response);` that might help – ADyson Nov 05 '18 at 15:57

0 Answers0