0

After hours of playing with this, it hit me that my JQuery simply isn't executing.

I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.

Here is my main page:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $(document).ready(function(e) {
       $('submitpicks').on('submit','#submitpicks',function(e){
            e.preventDefault();  //this will prevent reloading page
            alert('Form submitted Without Reloading');
       });
    });

</script>
</head>

<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
    var userPick = confirm("You picked " + thepick + ". Accept this pick?");
    //var theid = "finalpick" + v;
    var removebtn = "btn" + removepick;
    //alert(theid);
    if(userPick==1){
        document.getElementById("finalpick").value=removepick;
        document.getElementById(removebtn).disabled = true;
        document.getElementById("submitpicks").submit();
        v=v+1;
    }
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
    while($setrow = mysqli_fetch_array($setresult)){
        //shuffle($setrow);
        echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
        $u=$u+1;
    }
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results">&nbsp;</div>
</body>
</html>

Here is my PHP:

<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>

enter image description here

5
  • do look at your console Commented Nov 7, 2015 at 2:08
  • RTM developer.mozilla.org/en-US/docs/Web/API/Document/… - You're getting warnings but not checking for them. Commented Nov 7, 2015 at 2:14
  • I'm not getting a console error. Commented Nov 7, 2015 at 2:15
  • you mean to say that this isn't throwing you a warning document.getElementById(removebtn)? it's probably not even making it there. sendpick() where is that being called? Commented Nov 7, 2015 at 2:15
  • Please see image above. Commented Nov 7, 2015 at 2:19

2 Answers 2

1

you can use e.preventDefault(); or return false;

<script>
$(document).ready(function(e) {
   $('#submitpicks').on('submit',function(e){
        e.preventDefault();
        $.post('submitpick.php', $(this).serialize(), function(data) {
            $('#results').html(data);
        });
        // return false;
    });

});

</script>

Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php

<?php
    echo 'File connected';
?>

and then alert(data) in js .. if everything works fine .. go to next step

Explain each Step..

before everything you should check you install jquery if you use

<script type="text/javascript" src="jquery-1.11.3.min.js"></script>

from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then

1st to submit form with js and prevent reloading.. and you used <script> in your main page

<script>
    $(document).ready(function(e) {
       $('#submitpicks').on('submit',function(e){
            e.preventDefault();  //this will prevent reloading page
            alert('Form submitted Without Reloading');
       });
    });
<script>

output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step

2nd add $.post to your code

<script>
        $(document).ready(function(e) {
           $('#submitpicks').on('submit',function(e){
                e.preventDefault();  //this will prevent reloading page
                $.post('submitpick.php', $(this).serialize(), function(data){
                     alert(data);
                 });
           });
        });
    <script>

and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory

<?php
    echo 'File connected';
?>

output: alert with File connected

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

6 Comments

@SinTekSolutions see updated answer .. and read the console for error .. in your case and this code submitpick.php should be in the same path with your main page ... and comment all your php code and echo out something like I said ..
I'm not getting a console error. But alert(data) does nothing.
@SinTekSolutions ok I will update my answer .. and explain everything .. so please check all steps I will write .. Ok?
Step 1 did not work...no -- alert('Form submitted Without Reloading');
@SinTekSolutions please comment all your scripts code and just use this code
|
0

Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.

Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.

Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp

And here's an example of how you can set it up with Jquery:

$(document).ready(function() {
     $.ajax({
        method: "POST",
        url: "/something.php"
        dataType: "JSON",
        data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
        success: function(data){
            if (data["somevalue"]) == something {
                dosomething;
            } else {
                dosomethingelse
        },
        error: function() {
            alert("Error message");
        }
     });

});

This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:

Method

POST

POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.

GET

GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.

There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.

Url

The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:

<?php
   $form_data = $_POST['data'];
   $array = json_decode(form_data, true);
    do something with your data;
    $jsonToSendBack = "{status: 1}";
    $response = json_encode($jsonToSendBack);
    echo $response;
 ?>

So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.

DataType

Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.

Success and Error Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.

Anyway, I hope my explanation is sufficient, and that you can take it from here.

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.