Getting values for javascript from form


For a project that I'm working on, I'm building a plugin that calculates test scores.

For that, I'll build forms that the users will enter the number of correct answers, total number of questions, etc. then calculate the score with Javascript and return the score with Ajax.

Suppose a Js like this:

testScore = function (correct,total) {
this.correct = correct; = total;
this.percentage = function () {
return (this.correct/;

var quiz1 = new testScore (c,p);

In this example, I'd like to collect the values c and p from the form and return quiz1.percentage with Ajax on the same page.

Could you help me with how to do this. Thanks a lot.

  • Adam Czajczyk

    Hello Alp,

    I hope you're having a nice day!

    Assuming that you got a form similar to this one on your site:

    <form id="myform">
    <input type="text" name="c" id="my_form_c" placeholder="put C value"><br>
    <input type="text" name="p" id="my_form_p" placeholder="put P value"><br><br>
    <input type="submit">

    You can use jQuery to retrieve its values upon form submission and also prevent form from being "really" submitted so the site doesn't get reloaded:

    <script type="text/javascript">
    $('#myform').submit(function(e) {
    	var p = $('#my_form_p').val();
    	var c = $('#my_form_c').val();
    	/* you should sanitize P and C values here also before proceeding */
    	/* CODE */

    In a place of "/* CODE */" your custom JS should be put. I suppose that you would want to call your functions via AJAX now so at this place you should trigger AJAX call.

    I understand that this form should work within WordPress, is that right? WordPress includes a nice internal AJAX handling tools that you should use in that case. Take a look here please:

    Let me know if you have any additional questions on this :slight_smile:

    Best regards,

  • Alp

    Hi Adam,

    Thanks for the detailed feedback. Yes, it's supposed to work in Wordpress. With your feedback, now I'm quite clear what to do up until Ajax.

    But since I have no knowledge of Ajax yet, the codex got me a bit confused. It would be very nice of you if you could give me a very simple example of how to return a variable from a form with Wordpress Ajax handler. Then I can manage it from there.

    Thanks for the great support.

  • Adam Czajczyk

    Hello Alp!

    I'm glad I could help :slight_smile:

    As for example. I think checking this article on our blog may actually be even more helpful for you than a rough example that I could give :slight_smile:

    You will find there pretty much "step by step" guide on how to trigger Ajax call from your plugin using - exactly as you need it - a JS script :slight_smile:

    Take a look there please and still - if you come across any doubts, let me know here, please.

    Best regards,

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.