0

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");


          };   
         };
        ?>
3
  • You are not returning JSON at all, jquery ajax expect you to return a valid json object while you are redirecting to another page,. Commented May 25, 2018 at 22:33
  • it still doesn´t send the data to php, it don't make a difference Commented May 25, 2018 at 23:11
  • @Tom, is your problem is solved or not? Commented May 26, 2018 at 6:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

//Kill PHP. Good idea with an AJAX request. Why is exiting at the end of the PHP file a good idea, specifically for an AJAX request? The script will exit when it reaches the end anyway.
I get no error messages on console log, and still no data in database.I have this other code that acctualy submits my data but it keeps on adding data on refresh page, even if there are no values inputed. I checked, it somehow saves the last input. Can I send you that code, at least to try to fix that?
@Nathan this is mostly a WordPress habit for me. If using Admin Ajax, WordPress will output a 0 at the end of an AJAX request. So to prevent that from happening, I simply exit at the end of the request. I think it is good practice, as that is your intention, but really just my opinion.
@Tom, check your conn.php file. Output your mysqli_connect() response to ensure you are connected to the database.
@Chris Ah ok that makes sense. I haven't worked with wordpress before so haven't dealt with that.
-1

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.