I was just looking at the code in firebug and I can't follow it. I can't figure out how clicking "add comment" calls the jquery function that shows the comment form. On my site I am trying to mimic this behavior. I have a registration form and I want a link such as "Fill in my data" which then displays a text input below the link where they enter a code, and then a submit button that through AJAX populates the fields. I am new to js and AJAX, but am a quick learner so I was hoping to get some clarity here on the details of implementation. Seems to me the displaying of the input field should not be AJAX, but just js. And then submit would trigger the AJAX function. I know AJAX is fairly involved, in terms of having to create an xml that describes the server side data that needs to be collected and then somehow submit button will trigger call to server side php script or something. Conceptually I understand, but mechanically I don't... Thanks! Brian
I just tried implementing as described, but the url is not triggering the js. Here is what I have:
<script type="text/javascript">
$(function(){
$(".previousreg-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".previousreg-form-container").show(); // Show the form parent
});
$(".previousreg-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
</script>
<a href=# class=previousreg-link>Use previous registration data</a>
<div class="previousreg-form-container dno">
<form>
<textarea name=previousreg></textarea>
<input type=submit>
</form>
</div>
Because my site already loads jquery I didn't add the script declaration for jquery. Is anything above obviously wrong? Thanks.
Here in StackOverflow, the form is already present, but hidden initially (to save valuable space).
(StackOverflow uses a .dno class to hide elements.)
The click on the add a comment button does simply:
hide the clicked add a comment button
show the DIV holding the form
A simple way to do it:
$(function(){
$(".comments-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".comment-form-container").show(); // Show the form parent
});
$(".comment-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
.dno{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href=# class=comments-link>add a comment</a>
<div class="comment-form-container dno">
<form>
<textarea name=comment></textarea>
<input type=submit>
</form>
</div>
Regarding the $.ajax
since by submitting the form we don't want the page to refresh, AJAX is used to POST data to a PHP (let'ssay: saveComment.php page) which than stores to database. AJAX returns than a message response from the PHP code:
$.ajax({
type : "POST",
url : "saveComment.php",
data : $(this).serialize(), // `this` is our form
success : function( response ) { // Response is the PHP echo
alert("PHP says: "+ response);
// Using jQuery append the message to
}
});
The PHP stuff
in the code above AJAX will POST a serialized data to PHP like:
comment=Please, show what you tried!
The saveComment.php than might look like:
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit; // Don't allow anything but POST
$response = "";
if ( isset($_POST["comment"]) ) {
$commment = htmlspecialchars( $_POST["comment"] );
// TODO: $userId = retrieve here the user ID from the session;
// Sanitize(!!!!!) and save to database $comment and $userId
$response = $commment;
} else {
$response = "Please, enter a comment";
}
echo $response; // This will be sent/returned to AJAX
exit;
above, whatever you put in the echo, it will be returned by AJAX into the response argument.
Related
I am creating a jQuery search bar, that will asynchronously send the inputted value from a form from the client side to the same page on the server side (in PHP). Then I can search my database with the value. Unfortunately when I send this value, using $.ajax, and attempt to echo out the value, I don't get the value at all. How can I receive my value? I've tried print_r, var_dump, echo but to no avail.
Here is my form:
<form method = 'POST'>
<input id="myInput" type ="text" name ="value"
placeholder="press enter when finished" >
</form>
And here is my script to make the call. I get the value in my console when I press enter (key===13), but it seems to be the furthest my variable (value) seems to go.
$(document).ready(function(){
$('#myInput').bind('keypress', function(e){
if(e.keyCode ===13){
let value = $(this).val().toLowerCase();
console.log(value);
e.preventDefault(); //stops the damn page refreshing
$.ajax({
type: "POST",
data: value
});
};
});
});
I haven't put the URL in the AJAX call for a reason: I'm sending to the same page.
Here is the code (further up the page) that I'm using to echo out the posted value, on the same page.
if(isset($_POST['value'])) { echo $_POST['value']; exit; }
No matter what I seem to do, my value isn't sent to the page! I've tried to add in the URL, I've added "success" to the call.... nothing seems to work.
How can I successfully send my data?
I've copied a working jQuery form from one page to another, the original works as intended but the duplicate does not.
The original works like so:
So i have an onclick function attached to an image which opens up a confirmation modal window with an "OK" button (aka) my submit button, pressing this submits a post function, closing the window and creating a post on another page (the main page).
I've copied this working form to my main page so users wouldn't have to travel to the above mentioned page to accomplish this task. However, upon clicking the "OK" button on the duplicated form, it closes the window and refreshes the page, but the post function does not seem to be triggering.
The code is below:
<script>
jQuery(function (){
jQuery('#form-bumb .button-waiting, #form-bumb .waiting-updated').hide();
jQuery('#form-bumb').submit(function (e){
e.preventDefault();
//product_id
jQuery('#form-bumb .waiting-updated').hide();
jQuery('#form-bumb .button-waiting').show();
jQuery.ajax({
url : the_ajax_script.ajaxurl,
type : 'post',
data : {
action : 'product_bump',
product_id : <?php echo $product_id; ?>
},
success : function( response ) {
jQuery('#form-bumb .button-waiting').hide();
jQuery('#form-bumb .waiting-updated').show();
jQuery('#form-bumb button[type=submit]').hide();
remaining_bump = jQuery('.products-total-wrap #products-total-bumps').text();
if (remaining_bump > 0){
remaining_bump = parseInt(remaining_bump) - 1;
jQuery('.products-total-wrap #products-total-bumps').text(remaining_bump);
}
}
});
});
jQuery('#modal_product_message_confirmation h4.modal-title').html('Bump Confirmation '+
'<img src="<?php echo get_template_directory_uri();?>'+
'/assets_consumer/assets/img/bump-icon.png" width="20" />');
});
</script>
I have no idea what the problem is, if anyone would be so kind to point me in the right direction it would be greatly appreciated.
perhaps your form is generated dynamically and #form-bumb doesn't exist at time of running jQuery('#form-bumb').submit(function (e){....})
you should try instead
$(document).on('submit','#form-bumb',function(e){....})
which will also work on the form if it's dynamically created
I have a form and when you submit it, a JavaScript message appears.
$message = "Want to insert?";
echo "<script type='text/javascript'>window.confirm('$message');</script>";
And what I want to do is, if the person clicks 'OK' it inserts values in the database, if not it cancels it.
$titulo = $_POST['titulo'];
$mensagem = $_POST['mensagem'];
$ano = $_POST['ano'];
$mes = $_POST['mes'];
$dia = $_POST['dia'];
$link = " ";
Use <form> tag, and handle the onsubmit event. once he clicked 'OK' on message box submit the form.
Once the form gets submitted, In server side (PHP) write a code to get the data ( either by GET/POST which ever way you are sending) and insert into the table.
In simple words, PHP executes first, and then client side JavaScript executes. If you want it to be interactive, you must use AJAX, which will allow you to send PHP command controlled by JavaScript.
If I were you, I would do this way:
if (confirm("Are you sure?"))
$.post("path/to/php.php", {data: you_need_to_send}, function (response) {
if (response == "OK")
alert("All Done!");
});
else
alert("You cancelled the insertion.");
Note: Here, $.post() is a jQuery implementation of AJAX POST method. Just for ease of explanation I gave this. Please don't shout at me for answering a jQuery way for a JavaScript question.
Update
You can use onsubmit of the form to make this possible. Make sure you give a return inside the event:
<form method="post" action="http://example.com/" onsubmit="return confirm('Are you sure?');">
<input />
<input type="submit" value="Send" />
</form>
Run the above snippet and check it out.
You need to pass data using a request to your server. You cannot use JavaScript to write in you database directly since you already use PHP
But to confirm the user before you send your request or you can use this in your JavaScript code before you send your request.
if (confirm('Your Message')) {
// User click OK
// Send your data to server using a Request
} else {
// User click cancel
}
I want to send a string from one php page to another via a JavaScript page.
The string is sent through upon the push of a button. The name of the
button is changed each time it is displayed and the name of the button is
the one that is sent through. The problem is, it is not getting displayed in
next php page but the alert() function outputs the string as required. What
is wrong with the code?
Here is the php code in the first page
echo "<form method = 'post' action = 'passer.php'>
<input type = 'submit' value = 'play' name = '$ball'></input>
</form>";
Here's the javascript code
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
console.log(cat);
$.post("studSport.php",{input: cat}, function(data){
});
});
And the php code in the next page
{
$receiver = "";
if(isset($_POST['input'])){
$receiver = $_POST['input'];
echo $receiver;
} else{
echo " it is empty";
}
}
The output is always "it is empty" even though the alert() displays the right variable. What is wrong with the code, why wont $receiver be displayed?
Your Ajax request never runs. When you click the input you trigger it… but the input is a submit button so the Ajax request is canceled, the form submits, and a new page is loaded.
Since your form doesn't have an input named input, you'll always failed the test if(isset($_POST['input'])). (The Ajax request, which gets canceled, does input input, but you never make that request).
To stop the form submitting you need to capture the event object and prevent the default behaviour that the event would normally trigger.
$(':input').click(function(evt){
evt.preventDefault();
Note, however, that your success handler function:
function(data){
}
… does nothing, so you won't be able to see the result without inspecting the HTTP response using your browser's developer tools.
It is possible that your goal isn't to use Ajax, but is to load a new page - just with additional data in the form.
To do that, you need to modify the controls in the form instead.
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
$(this).append(
$("<input type='hidden' name='input'/>").val(cat)
});
});
But if you just want to tell which submit button was pressed then don't involve JavaScript at all. Just use a submit button with the name and value you want.
<form method='post' action='passer.php'>
<button name="input" value="<? echo htmlspecialchars($ball); ?>'>
play
</button>
</form>
How do i "SET" the action(not changing) AFTER the form has been submit?
<form id="serialize" action="newjob.php?serialize=newjob" method="post">
<button id="jobsearch" name="jobsearch">GET FROM DB</button>
</form>
AFTER the form has been submit and showing the value i need from db, SET the new action for the form, example after submit how do i get like this one so i can add the value to db?
<form id="serialize" action="newjob.php?faulty=newjob" method="post">
<button id="jobsearch" name="jobsearch">ADD TO DB</button>
</form>
as far as i know by search on the net this jquery only CHANGING(onsubmit) and not after submit
$(function(){
$('#serialize').submit(function (event)
{
var newaction = 'newjob.php?faulty=newjob';
$(this).attr('action', newaction);
});
});
it is possible to had AFTER form has been submit then set the new form action for the same form? the only thing i need to accomplish this is because i cant have a form inside a form(nested)
You can't modify form attributes inside .submit() event handler since it has been submitted using a typical submit method.After the from has been submitted, the new document is loaded and any submit event set for the form is not catched yet.
You have two options to solve the problem.
AJAX request instead of traditional form submition (recommended);
You should handle server response (data sent back from PHP) on the original page, like so (without modifying your HTML):
$('#serialize').submit(function (event){
// prevent typical submit method:
event.preventDefault();
var that = $(this), newaction;
$.ajax({
url : that.attr('action'),
method : 'GET',
data : that.serialize(),
// dataType : set accordingly to the type of data received from PHP,
success : function(data_received_from_php){
if(that.attr('action') === 'newjob.php?faulty=newjob'){
newaction = 'newjob.php?serialize=newjob';
// do something with "data_received_from_php" for that specific "action" ...
}else{
newaction = 'newjob.php?faulty=newjob';
// do something with "data_received_from_php" for that specific "action" ...
}
// set the new action attribute:
that.attr('action', newaction);
},
error : function(){
// handle errors ...
}
});
});
Simply check whether url contains specific string, and based on that modify the action attr of the form (I'd treat it as a workaround since these days, AJAX is much more "user friendly" in submitting forms):
if (window.location.href.indexOf("?serialize=newjob") > -1) {
$('#serialize').attr('action', 'newjob.php?faulty=newjob');
}
From what i see you are using jQuery and i've done something similar before.
The trick is to change your Submit button by a regular button that trigger a function to do what you have to do and finally submit the form using .sumbit()
Something like this:
<form id='changingForm' .... >
<button onclick='changingFunction()' ...>
</form>
function changingFunction(){
var newaction = 'newjob.php?faulty=newjob#tabs-2';
$('#changingForm').attr('action', newaction);
$('#changingForm).submit();
}
This code probally won't work AS IS for your case scenario but i'm sure you can fingure the logic behind it. jQuery is too far behind me to give you an absolute answer.
Hope it helps.