0

How my page works:

  1. The quiz php page loads and the user generates a score with a function inside quiz.js. The score is then saved in a variable score inside quiz.js
  2. After generating the score, the user has to press a button to go to the next question in the quiz inside the same page. Pressing the button would send the score to my database with a sql query I have in sendData.php, without reloading the page.

My button looks like this:

<form id="sendData" action="sendData.php" method="post">
  <button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>

sendData.php is already finished and working, but for some reason, sendAjax() doesn't work at all:

function sendAjax() {
  $.ajax({
    url:  "sendData.php",
    type: "POST",
    data: {
      score: score,
      numQuiz: numQuiz
    },
    success: function() {
      alert("Data succesfully sent");
    },
    error: function() {
      alert("There has been an error");
    }
  })
}

And my PHP file being like this:

if (isset($_POST['score']) and isset($_POST['numQuiz'])) {
    $score = $_POST['score'];
    $numQuiz = $_POST['numQuiz'];
    // SQL query and stuff goes here
}

But it seems that $_POST['score'] and $_POST['numQuiz'] aren't set. Also, I can see the error pop up inside sendAjax before it loads the PHP file. I've tried adding to the form the attribute action="" but it doesn't work either.

7
  • remove submit from button Commented Feb 20, 2019 at 10:38
  • still not working :/ Commented Feb 20, 2019 at 10:40
  • You have to do .preventDefault(). Try adding an ID to the button, remove onclick and in js: $('#my-btn').on('click', function(e) { e.preventDefault() /* $.ajax(...) */ }) Commented Feb 20, 2019 at 10:55
  • I tried it, you can see my post's edit. But it's not working either Commented Feb 20, 2019 at 11:03
  • Are you sure the url is correct? I mean, isn't it 404 error? What do you see in the Network tab in the Chrome DevTools? Commented Feb 20, 2019 at 11:05

2 Answers 2

2
<form id="sendData" action="sendData.php" method="post">
  <button type="submit" name="send" onclick="sendAjax()">Send</button>
</form>

You're running the JS when you click a submit button in a form.

So the JS runs, then the browser immediately navigates to a new page (submitting the form, with no data in it, to the PHP) and the XMLHttpRequest object is destroyed before it receives a response.

You then see the result of the standard form submission.

If you just want a button to trigger some JavaScript, then use a non-submit button (<button type="button"), and don't put it in a form.

Better yet:

  1. switch away from onclick attributes (they have a variety of issues) in favour of addEventListener providing a submit event listener on the form
  2. Use preventDefault() to stop the form submission when the JS is successful
  3. Put form controls in the form so it submits useful data when the JS isn't successful

i.e. write Unobtrusive JavaScript then provides Progressive enhancement.

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

6 Comments

Okay, so the page at least doesn't refresh now. I've chenged my button to a normal one and my function to $('#buttonID').click(function(e) { e.preventDefault(); but it does nothing now. Thanks for the links, by the way. I'm still using onlick for the button though
@ratuwipuy — Open the developer tools in your browser. Look at the Console. Click the button. See what errors come up. I expect something about $ being undefined.
Okay so after adding $(document).ready(function() { before the click handler it works. Although the error message still pops up... Nothing in the console by the way. It's an error inside the ajax function
I've edited my post with exactly what I have, if you want to check it
You mean alert("Error al pasar datos") runs? Look at the arguments to the error function. There's some reason it is failing.
|
-1

Two things:

You need to tell jQuery to use the application/json content-type:

function sendAjax() {
  $.ajax({
    url:  "sendData.php",
    type: "POST",
    contentType: 'application/json',
    dataType: 'json',
    data: {
      score: score,
      numQuiz: numQuiz
    },
    success: function() {
      alert("Data succesfully sent");
    },
    error: function() {
      alert("There has been an error");
    }
  })
}

PHP's $_POST variable is not populated as you think it is as the payload is not urlencoded as is standard with say a form submit. So we can parse the JSON payload (body) ussing:

$myData = json_decode(file_get_contents("php://input"));
var_dump($myData->score);

4 Comments

Your JS is claiming to be sending JSON, and your PHP is trying to parse JSON, but you're sending URL Form Encoded data, so that will fail.
What does json have to do with this? I get Notice: Trying to get property '' of non-object in /opt/lampp/htdocs/test/sendData.php on line 10 NULL
@quentin good catch! thank you.. we'd want to JSON.stringify(..) of course
Changing code that sends form encoded data, which claims to be form encoded data, to somewhere which expects form encoded data to code that sends JSON encoded data, which claims to be JSON encoded data, to somewhere which expects JSON encoded data … is pretty pointless and doesn't solve the problem.

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.