I'm having some trouble with Jquery as of late. I wanted to get a little more skillful with it and create a login form using Jquerys $.post method but I've hit a little snag.
For some reason When I click the button to submit, the data I want to post instead gets put into the URL of the current page I'm in. Furthermore, the Jquery will only work when this data is in the url.
I don't want to show the website visitors their username and password in the url. Why isn't it just posting the data as intended?
EDIT: IT seems even with all the changes i've made, I still need to submit the form twice for it to actually log me in.
// WHERE MY REQUEST IS MADE AND SENT
<script>
$( document ).ready(function() {
$( "#loginbtn" ).click(function() {
var u = $("#loginform input:text" ).val();
var p = $("#loginform input:password" ).val();
$.post( "http://www.gameandshame.com/auth/login.php", { username: u, password: p}).done(function( data ) {
//alert("Data Loaded: " + data);
location.href = "http://www.gameandshame.com/";
});
});
});
</script>
//DATA POSTED TO HERE
<?php
session_start();
include_once("".$_SERVER['DOCUMENT_ROOT']."/auth/class_loader.php");
echo "STARTING LOGIN";
$login = new login();
$login = $login->startLogin($_POST['username'],$_POST['password']);
?>
//END OF MY STARTLOGIN FUNCTION
$_SESSION['t'] = $t;
$_SESSION['u'] = $u;
echo "SUCCESS";
return;
// The Login Form
<form method="post" id="loginform">
<table>
<tr>
<td><input name="username" type="text" maxlength="24" placeholder="Username"></td>
</tr>
<tr>
<td><input name="password" type="password" maxlength="24" placeholder="Password"></td>
</tr>
<tr>
<td><input id="loginbtn" type="submit" name="submit" value="Go!" /></td>
</tr>
</table>
</form>
I'm honestly at a miss as to why it would stick the arguments in the URL. there seems to be no logical reason for it, even more .
NOTE: The "STARTING LOGIN" only gets returned when I try to login and all the form data is in the url. The login script isn't even ran if there is no data in the url. very weird... :S
I see two problems.
[NO LONGER VALID AFTER FULL CODE ADDED BY POSTER] Check your javascript console. None of your javascript is getting executed because you're msising a }); to close your .click.
[HTML CODE ADDED BY POSTER, STILL VALID POINT BUT NOT THE SOURCE OF ERROR] Without your html, I'm talking a guess here. But I see a problem with the absence of e.preventDefault() in your click event. If your button is type="submit", your form will submit normally.
Wrap everything in
$(document).ready(function(){ [ALL YOUR JS CODE ] });
Otherwise jQuery tries to attach your click event before the DOM is fully loaded.
I found the problem.
In my form i had
<input id="loginbtn" type="submit" name="submit" value="Go!" />
when what I really needed to do was take out the submit from the button, and just grab the form details on-click. Because this type="submit" was still in there, it was posting the form normally, then attempting to post again from the JS, and as a result completely screwed up the ajax request.
Related
My if(isset) validation is returning false after I have submitted the form through jQuery ,however works fine when done without jquery. Reason I am using jQuery is because I need to submit multiple forms:
Button
<input class="btn btn-primary" type ="submit" id="myButton"
name="create_record" value="Submit 1">
jQuery:
<script>
$(document).ready(function () {
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
// $("#form2").submit();
});
});
</script>
PHP
<?php
if(isset($_POST['create_record'])){
$ecode = $_POST['ecode'];
$ename = $_POST['ename'];
$date = $_POST['date'];
$jobRole = $_POST['jobRole'];
}else{
echo "did not receive anything";
}
?>
Always getting "did not receive anything" . Can someone please help.
The submit button value only gets sent if the form is submitted in the traditional way by a button click. Since you are submitting the form via javascript, you'll need to explicitly include the submit button's value or validate your post data in some other way. If you need the value of the specific button that was clicked, something like this should work:
$("#myButton").click(function (event) {
event.preventDefault();
var el = '<input type="hidden" name="' + $(this).prop('name') + '" value="' + $(this).val() + '">';
$("#form1").append(el).submit();
});
As for your objective of submitting multiple forms at once, I believe it's impossible without using ajax as discussed here. If you need guidance on how to do that, better to open a new question.
Your code, isset($_POST['create_record']) maybe false or it didn't receive any values. If your query is only in one PHP file together with your jQuery, you need to check first your algorithm or use var_dump() for testing. Second, If it didn't work, make an alternative solution for it. Do the proper HTML code when using form or make another PHP file for receiving post purpose only.
<form action="directory_to_another_file" method="POST">
<!-- SOME INPUTS HERE -->
<input type="submit" value="Submit 1" name="create_record">
</form>
Try to test all of your codes.
You have to set form method as "POST" type and if you want to receive the form data in same page then empty the "action" key otherwise give the target link.
<?php
if(isset($_POST['create_record'])){
print_r($_POST);
}
?>
<form action="" method="POST" id="form1">
<input type="text" name="create_record" value="Submit 1"/>
</form>
Submit
<script>
$(function(){
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
});
})
</script>
Let me know if it's work for you.
<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/
I have php code that echos a form that was inserted into my html by another jquery code. This all works fine. I am trying to submit this form with ajax.
echo '<form id="comment_form" action="commentvalidation.php?PhotoID='.$_GET['PhotoID'].'" method="POST">';
echo '<label>Comment: </label>';
echo '<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>';
echo '<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >';
echo '</form>';
The form works fine when submitted traditionally. The problem is I cant get it to be be submitted with ajax. The .submit just wont prevent the default action.
<script>
$(function(){
$('#comment_form').submit(function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
</script>
You're probably binding the submit event handler before the form is in your page. Use event delegation instead of direct binding, for example
$(document.body).on('submit', '#comment_form', function(e) {
e.preventDefault();
alert('We are in');
// and the rest, no need for return false
});
As an addendum, try not to echo out great chunks of HTML from PHP. It's much more readable and you're less likely to run into problems with quotes and concatenation if you just switch to the PHP context when required, eg
// break out of the PHP context
?>
<form id="comment_form" action="commentvalidation.php?PhotoID=<?= htmlspecialchars($_GET['PhotoID']) ?>" method="POST">
<label>Comment: </label>
<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>
<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >
</form>
<?php
// and back to PHP
The problem seems to be from the fact that form that was inserted into my html by another jquery code. From what I understood from this, the form was dynamically created after the page was loaded.
In that case when the submit handler registration code was executed the element was not existing in the dom structure - means the handler was never registered to the form.
Try using a delegated event handler to solve this
$(function(){
$(document).on('submit', '#comment_form', function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
Demo: Problem
Demo: Solution
I have a problem with my page refreshing after ajax posts, I've tried like 6 differing variations and at one point I was getting the proper result but couldn't stop the page from refreshing and after searching the net and around on this site now none of it is working and it's still refreshing...
current code is:
$('#submit_btn').click(function() {
/*event.preventDefault();*/
var curPassword = $("input#curPassword").val();
var newPassword = $("input#newPassword").val();
var new2Password = $("input#new2Password").val();
/*var params = 'curPassword='+ curPassword + '&newPassword=' + newPassword + '&new2Password=' + new2Password; */
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
$.ajax({
type: "POST",
url: "testAjax.php",
data: params,
success: function(msg){
alert(msg);
}
});
return false;
});
the form is:
<form method="post" action="" name="confirmChange" class="confirmChange">
<label for="curPassword">Current Password:</label>
<input type="password" name="curPassword" id="curPassword" value="" />
<label for="newPassword">New Password:</label>
<input type="password" name="newPassword" id="newPassword" value="" />
<label for="new2Password">Confirm New Password:</label>
<input type="password" name="new2Password" id="new2Password" value="" />
<br />
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change" />
Appreciate any help in getting this to work =/
Update:
Took out the other non-directly-related code as it kinda cluttered the question. Also updated code to refelect latest revision.
I changed the ajax url to a simple textAjax.php with a simple echo hello world nothing else, where I'm still getting nothing.
Update 2
Tried changing javascript code to:
$('#submit_btn').click(function() {
alert('Button Clicked');
});
And I'm getting nothing... If that is the form below how is it possible the click function isn't working at all?
You don't need to use the type="submit" for your input. Just use type="button" and call the ajax function on the button's click event.
<input type="button" name="confirmChange" class="confirmChange" id="submit_btn" value="Change">
$('#submit_btn').click(function() {
(ajax code here)
});
preventDefault() would also work, but, in my opinion, why prevent an event from naturally occurring when you can just avoid using the submit button altogether?
Update: I just realised that using the submit would allow users to hit enter to trigger your actions, so perhaps there's also some merit in that. In any case, here's a similar question that contains elaborations into preventDefault().
Update 2: You need to fix your parameters in the ajax function. Use an array instead of trying to build a query string:
var params = {
curPassword: curPassword,
newPassword: newPassword,
new2Password:new2Password
};
Encapsulate your AJAX call within the following code block
$('form.confirmChange').submit(function(event) {
event.preventDefault();
#Rest of your code goes in here
});
preventDefault() will prevent the default action of an event from triggering.
Try this
<script>
function refreshpage(){
(ajax code here)
return false;
}
</script>
<form onsubmit="return refreshpage();">
<input type = "submit" value="submit_btn">
</form>
I think I fixed it by using:
$('#submit_btn').live('click', (function() {
I at least started getting a response when clicking, but I'm not updating or getting any echo's back from the php file but hopefully that'll be easier to debug. :)
I had the same problem. Just like you, I had wrapped my <input> tags inside a <form> tag pair. Even though there was no <submit>, I found that when I clicked my button to trigger the Ajax call, it was refreshing the page - and actually submitting the form to the page.
I ended up removing the <form> tags and this behaviour stopped, but the Ajax still works as expected. I hope this helps anyone else that is experiencing this.
Use a loop to run the ajax call only once.
var i;
for(i=0;i<1;i++){
//ajax code here
}
So, then it will not call again and again..
I have a simple application here (QandATable2.php) where when the user clicks on the plus button, it will open a modal window and it displays the details which is stored in another page (previousquestions.php).
Now the problem I have is that if you straight away click on the "Search" button when the textbox is blank, you will see that it loads the page on its own page, displaying the message to enter in a phrase for the search and it also displays all of the features previously from the modal window into that page as well. This is incorrect.
What I want it to do is that if the user has clicked on the search button, then when it post's the form and outputs the message, it does it within the modal window, not on its own whole page. So does anyone know how this can be acheived?
The modal window I am using is known as SimpleModal and it's website is here
Below is the QandATable2.php code where it displays the plus button and where it opens the modal window, linking the content of the modal window to the previousquestions.php page:
<script type="text/javascript">
function plusbutton()
{
$.modal( $('<div />').load('previousquestions.php #previouslink') );
return false;
}
</script>
<h1>CREATING QUESTIONS AND ANSWERS</h1>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
Below is the previousquestions.php code, where it displays the details in the modal window and where the search feature is stored:
<?php
foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<?php
//...connected to DB
if (isset($_POST['searchQuestion'])) {
$questionquery = "SELECT QuestionContent FROM Question
WHERE(QuestionContent = '".mysql_real_escape_string($questioncontent)."')";
if (empty($questioncontent)){
echo "Please enter in a phrase in the text box in able to search for a question";
}
?>
You'll probably want to use AJAX, since you're already using jQuery you'll just need something like this:
// override the "default" form submitting behavior with a callback function
$("form").submit(
// this is the callback function for your form submit function.
function(e)
{
// this prevents the page from reloading -- very important!
e.preventDefault();
// get the search data from the input textbox
var s = $("input[name='questioncontent']").val();
// see annotation
$("#simplemodal-data").html("loading...")
.load("previousquestions.php #previouslink",
{
questioncontent : s,
searchQuestion : "Search"
}
);
}); // end submit wrapper
This will send the value to the server and load it in the div with id simplemodal-data
Annotation:
The last line in the code does several things. First, it replaces the simplemodal DIV with a "loading" message. At the same time, it makes a POST request to your previousquestions.php page. This part { questioncontent : s, searchQuestion : "Search"} is where the data from the form gets passed to the PHP page, (remember the variable var s assignment above. Lastly, the results from the previousquestions.php page should be loaded in the simplemodal-data modal window.
One thing that's missing is to add #previousquestions in the load method so that only a portion of your HTML document gets inserted in the modal. It's never a good idea to load an entire HTML page inside another HTML document, and "load" is designed to allow you to just pick the part of the document you want to insert, which is just that DIV.
I added "#previouslink" after the php filename. This is where the magic happens. The browser knows to extract that DIV from your PHP file and insert just that part on the page, no <head> <body> or any of the unneeded markup.
You can achieve what you're looking for by using AJAX to submit the form instead of using the default behavior where the page reloads with the new content. You can't use modal.load because you need to POST data in the request in order to get the appropriate response.
However, when using AJAX to post your data, you can take the response as HTML and add that HTML to a DIV on your page, and then invoke the SimpleModal command on that DIV container.
First, modify the submit button on your form so that it's type="button" instead of type="submit". This will prevent the form from submitting and redirecting the page. Alternatively, you could add event.preventDefault(); and return false to the form submit click handler (see the second step), but it's probably easier to try this method while you're making the changes:
Step 1:
<!-- change type to button -->
<input id="searchquestion" name="searchQuestion" type="button" value="Search" />
Step 2:
Create a handler for the form button, which uses serializeArray to serialize the form into a string and then POST it to the server. In the success callback handler, you'll then take the HTML response and replace the content in the modal window with the new HTML. This also catches errors, if any, and alerts them and writes them to the console:
$('form[type="button"]').click(function() {
var dataString = $('form').serializeArray();
$.ajax({
url: "/previousquestions.php?t="+new Date().getTime(),
type: "POST",
data: dataString,
context: document.body,
success: function(data){
alert(data); // results from server, either the HTML page, or JSON/XML
$('simplemodal-data').html(data); // if HTML, just insert into div#results
},
error: function(jqXHR, textStatus, errorThrown) {
if(window.location.hostname == "localhost") {
alert("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
console.error("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
});
});
Step 3:
Lastly, be sure that your previousquestions.php code returns only a partial HTML document, not a full HTML document. Since you're injecting HTML into an existing page, you don't need the <html>, <head>, or <body> sections. These will just cause your page to not validate, and may cause undesired behavior in legacy browsers. Here is an example of what your response might look like:
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="test" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<p>
Your Search: 'test' </p>
<p>Number of Questions Shown from the Search: <strong>0</strong></p><p>Sorry, No Questions were found from this Search</p>
I have found out from an answer on another page to a similar question to this that like Bergi has stated, it is easier using an iframe than using ajax to keep content displayed within a modal window. So the best answer for this question is below where it shows how an iframe is used for the question above:
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}