Tom
Tom

Reputation: 1

php not receiving data from ajax from jquery

I cant get the data from my jquery to php file. I have tried multiple solutions, i dont get any errors but the data is not showing up on my database. This is the first time using ajax. I need an external php submit code, becouse if i include the php code on my index.php the values are remembered and they get submited when I refresh the page. Thanks in advance.

This is my html

<form  class="form-inline" method="post" >          
     <div id="div_id_value" class="form-group"> 

        <input  class="numberinput form-control"
          id="value" name="value" 
          placeholder="Value (mmol/L)"
          required="True" type="number" step="any" min="0"/> 
        </div>


      <div id="div_id_category" class="form-group"> 

          <select  id="id_category" name="category"> 
            <option value="Breakfast">Breakfast</option>
             <option value="Lunch" >Lunch</option>
              <option value="Dinner">Dinner</option> 
              <option value="Snack">Snack</option> 
              <option value="Bedtime">Bedtime</option>
               <option value="No Category" selected="selected">No Category</option> 
             </select> 
           </div> 

           <input  type="submit" name="submit" value="Quick Add" id="quick"> 
       </form>

This is my jquery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">


  $("#quick").click(function() {

      var sugar2 = $("#value").val();
      var category2 = $("#category").val();

      $.ajax({         
        type:'POST',
        url:'quick.php',
        data:{ 'sugar': sugar2, 'category':category2},
        dataType:'json',
        success: function(output) {
    alert(output);
         };
      });
  });

and this is my php

<?php
  session_start();
  include 'conn.php';

  if (isset($_POST['sugar'])) {     

    $sugar = $_POST['sugar'];
    $category =  $_POST['category'];
    $email= $_SESSION['email'];

    $query = "INSERT INTO data (email, sugar, category) 
            VALUES($email, $sugar, $category )";


   if(mysqli_query($link, $query)) {

                header("Location: index.php");


          };   
         };
        ?>

Upvotes: 0

Views: 206

Answers (2)

stev
stev

Reputation: 29

you have to return a response from you php script to the ajax, this would be in json or other format else, but i see in your code that you do not echo nothing in the php. But your ajax part it is specting something to put in yor output variable and make an alert. Try to make you php to

<?php 
  echo "my response";
?>

if you see your alert box that mean your problem is some php error, like conection or syntax .

Upvotes: -1

Chris
Chris

Reputation: 4810

Quite a few things you could update here. First, it will be tough for anyone here to debug why the data is not in your database. That could be a connection error, setup error, etc. You will need to provide error information in order for us to help. With that being said...

First thing, I would tie into the submit event instead of the click event. The click event will not account for users pressing enter on the input field. The submit event will catch both clicking the submit button, as well as submitting the form via the enter key.

$("#quick").submit(function(evt) { ... });
//or
$("#quick").on('submit', function(evt) { ... });

Next, your AJAX call. You specify the dataType parameter. According to the documentation, this is to tell jQuery what you expect back from the server. Not what you are sending to the server. So in your case, you should be sending JSON back to your AJAX success function, which you are not. I would remove the dataType parameter, as it is not required.

Finally, the success function expects a response. In your PHP file, you are attempting to redirect the user, which will not work here. You need to return a response to the AJAX function. This would be a great opportunity to check for errors, or even simply debug your code an ensure it is working as expected. So perhaps something like this,

<?php
session_start();
include 'conn.php';

if (isset($_POST['sugar'])) {     

  $sugar = $_POST['sugar'];
  $category =  $_POST['category'];
  $email= $_SESSION['email'];

  $query = "INSERT INTO data (email, sugar, category) 
            VALUES($email, $sugar, $category )";

  //save the output of the result
  $result = mysqli_query($link, $query);

  //according to the docs, mysqli_query() will return false on failure
  //check for false

  if( $result === false ) {

    //the query failed
    //provide a response to the AJAX success function
    echo "Query failed. Check the logs to understand why, or try enabling error reporting.";

  }else {

    //the query worked!
    echo 'All good!'; //provide a response to the AJAX success function

  }

  //Kill PHP. Good idea with an AJAX request.
  exit;
}

Again, this may not solve your issue, but hopefully gets you moving in the right direction.

Upvotes: 2

Related Questions