jQuery on submit issue - php

For some reason my submit event is not working, however, if i change it to click on the form, it works, this is my code:
JQUERY:
<script>
(function(){
$('form').on('click',function(){
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
});
})();
</script>
REGISTER.PHP:
<?php
if(isset($_POST['username'])){
echo $_POST['username'];
}
?>
This works perfectly fine, it appends the username whenever I click on a form text input, however, when I try to use the submit method, it doesnt output anything:
<script>
(function(){
$('form').submit(function(){
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
});
})();
</script>
As a matter of fact, it doesn't even work when I use button.on('click')

You are using an immediately invoked function instead of document ready handler, also you should prevent the default action of the event, try the following:
$(function(){
$('form').on('submit',function(event){
event.preventDefault();
$.post("../includes/register.php", $(this).serialize(),
function(data){
$('body').append(data);
});
});
});

The form will submit to the form's action by default. You need to prevent this from happening. You are waiting for a server response via ajax, so it is most likely you will never witness your callback executing before the default action occurs.
$('form').submit(function(e){
e.preventDefault(); // put this first
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
});

This is speculation right now since I do not know what your HTML code looks like.
But on submit the form will be submitted, and any active ajax requests will be cancelled.
Try something like
<script>
(function(){
$('form').submit(function(){
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
return false;
});
})();
</script>
That will stop the submit event and you should get the post event to occur. Though it will NOT actually submit the form. So you'll have to do that manually.

Related

run php file on button click ajax

Entry level user here. I've seen countless AJAX\PHP examples with data being passed via POST or GET and modified one of their examples. When clicking the button (id="clickMe) I want it to execute advertise.php and nothing more (no variables need to be passed) without refreshing the page and a notification that says success. When I click the button with my current code nothing happens.
<button type="button" id="clickMe">CLICK ME TO RUN PHP</button>
<script type="text/javascript">
$(document).ready(function(){
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({
url: 'advertise.php',
data: {
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
});
</script>
Updated, but still isn't executing.
Here is your editted version code:
$(document).ready(function(){
$('#clickMe').click(function(){
$.post("PHP_FILE.php",{ajax: true},function(data, status){
alert(data);
});
});
});
2 things - you need a document ready handler and to prevent the default click action.
$(document).ready(function() {
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({ // remainder of code...
});
When loading jQuery scripts at the top of the page you need to make sure they do not run until the DOM has loaded, that is what the document ready handler is for. The you capture the click event by including it as an argument for your click's callback function and handle the click with the preventDefault() method.
Since this request is "simple" you may want to consider using one of the shorthand methods, like $.post()

jQuery AJAX post to PHP for PDO INSERT not working with variables $('#id').val()

I am showing 3 code-snippets.
Approach 1 and 2 do NOT work
The 3rd code IS WORKING.
********* not working1 start **************
<script>
$(document).ready(function() {
$('#sending').click(function(){
// just 4 testing:
//var txtBoxVal = $('#TextBox1').val();
// alert(txtBoxVal); ==> ok: showing the value I want to send & INSERT into database via PDOinsertpost.php
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + $('#TextBox1').val(),
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* not working1 end **************
now the approach with the variable inside the $.ajax (not working as well):
********* not working2 start **************
<script>
$(document).ready(function() {
$('#sending').click(function(){
var txtBoxVal = $('#TextBox1').val();
// an alert - just 4 testing:
// alert(txtBoxVal); // ok: showing the value I want to send & INSERT into database via PDOinsertpost.php
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + txtBoxVal,
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* not working2 end **************
and now the "hardcoded", working version (?courious for me, that this one is working - but the others do not...)
********* the working1 start **************
<script>
var txtBoxVal = "some hardcoded string for testing";
$(document).ready(function() {
$('#sending').click(function(){
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + txtBoxVal,
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* the working1 end **************
Additional Info.: in the meantime I figured out, that an empty value is working with the two "not-working" code-snippets with $('#id').val(),
this means: a blank value is inserted in the database.
Am I searching at the wrong place?
Do I need to do some htmlentities - stuff or something within the .php file with the PDO-INSERT?
I hope, some useful information can be gathered by this post - for me, as well as for others.
Thanks in advance,
-Flow.
I see 2 big problems here:
You are reloading the page (in all your examples...) while the ajax request has not yet finished. That is a very risky and buggy approach as you cannot be sure that your php script will finish correctly. And if you reload any way, you don't need ajax.
You are not escaping your value so user input can break the query string. The easiest solution for that is to use an object so that jQuery encodes it correctly automatically:
data: { 'postVal1': $('#TextBox1').val() },
I also don't see you cancelling the default form submit, but as the third example works, I assume that the button / #sending element is not a submit button. If not, you would need to take care of that as well.
Edit: As you are using a submit button, you need to prevent the regular form submit:
$('#sending').click(function(event){
// prevent the default form submit
event.preventDefault();
...
without the "window.location.reload();" it seems to work!
#jeroen had probably the right explanation: the reload disturbed the process!
(but it didn't on my virtual home-server ... (may be, because of other processing-times... ))

Using preventDefault() in Jquery and Ajax

I,m using PHP, Jquery and Ajax to submit user info, to validate the input fields and submit the info I use this
$(document).ready(function(){
$("#contact_form").validate({
... my validation code goes here ...
submitHandler: function(form) {
$.ajax({
type: $(form).attr("method"),
url: $(form).attr("action"),
data: $(form).serialize(),
dataType : "json",
success: function(result){
$("#contact_form").fadeOut(1000, function(){
$("#success_message").fadeIn();
});
}
})
}
});
});
I know it is very simple but I have a question: do I need to add the preventDefault() method? If the answers is yes, could you please help me with an example?
Thanks.
No you are not required to put e.preventDefault(); since jquery validator does that for you. when the form is submitted the default action of form is prevented by the Jquery validator.

Submit form to two places

I have an issue where I need a simple contact form to have an action to post to a data collection service, AND to a thank you page for conversion tracking.
The data collection service page does not allow for any sort of redirection unfortunately, so my best bet is to submit to BOTH a thank you page, and to the data collection service.
I just don't know how to to this though... can someone please steer me in the right direction? I've done a lot of searching, but can't really get anything to work with jquery or javascript.
Any advice / feedback / methods would be greatly appreciated.
Per the reply below, I'm trying to get the AJAX to redirect after it sends data to the collection service like this, but I can't get it to work:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
// Shorthand for $( document ).ready()
$(function() { $("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
window.location.replace("http://example.com");
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}); });
</script>
<form name="ajaxform" id="ajaxform" action="https://secure.velocify.com/Import.aspx?Provider=IdealHomeLoansWebPOST&Client=IdealHomeLoansLLC&CampaignId=46"method="POST">
Using jQuery, you could send everything to your data collection service and wait for an answer. If it was successful, redirect to the thank you page.
Everything you need to know can be found in this article: http://hayageek.com/jquery-ajax-form-submit/
$(function() {
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
});
This replaces the default form-submission with an AJAX-Request.
Then just use the following code to redirect to the thank you page:
window.location.replace("http://example.com");
Submit to the Thank You page and have the Thank You page do a CURL request to the data collection service.
Or, submit to an intermediate page that submits the CURL request and then redirects to the Thank You page.
The most straight forward way I can think of doing this would be to have a onClick handler for your submit button and then using JavaScript fire off some sort of XHR post request to your data collection service containing the form data. You would then return true and the browser would post to the Thank You page.
For example using JQuery (your code will need more check and complexity)
HTML:
<form id="form" action="somewhere.php" method="post">
<!-- form stuff here -->
<input type="submit">
</form>
JS:
$('#form').submit(function() {
$.post('somewhereElse.php', {data: $('#form-element').val()});
return true;
});
JQuery Ajax Post, might have to set it to async.
On the success submit from the first one, you can submit to the second. Then on the success you can redirect to the the thankyou page.

jquery load interval div flash

So, I have a div that im using the following code on, but it will flash when it reloads. I understand 1000 is ridiculous - it's simply set at that while im testing. Is there anyway to avoid the "flash" as if that div were a page reload?
Thanks, so much!!
<script type="text/javascript">
$(document).ready(function(){
$("#timelinerContainers").load("jquery_timeline.php");
var refreshId = setInterval(function() {
$("#timelinerContainers").load('jquery_timeline.php');
}, 1000);
$.ajaxSetup({ cache: false });
});
</script>
If I click ANYWHERE on the page it then will stop flashing... Rather odd.
Thanks so much for any help!!!
have you tried
$("#timelinerContainers").fadeOut().load('jquery_timeline.php').fadeIn();
or
$("#timelinerContainers").fadeOut().load('jquery_timeline.php',function(){
$(this).fadeIn()
});
Try this code:
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$.ajax({
url: "jquery_timeline.php",
success: function(data) {
$("#timelinerContainers").html(data);
}
});
});
</script>
The change is that I've used the jQuery.ajax() function for loading the contents. What I've done here is to first load the contents and then update the div, instead of clearing the contents, before making the ajax request.

Categories