Post not sent immediately with ajax - javascript

<script src="http://www.ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<form>
<label>Campo</label>
<input id="campo" name="campo" placeholder="Campo" required="" type="text">
</form>
<script language="JavaScript" type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "control.php",
type: "POST",
data: "campo=" + $("input#campo").val(),
success : function(data) {
if (data == 1) {
$("#div").html("Campo non disponibile");
}
else {
$("#div").html("Campo disponibile :)");
}
}
});
});
</script>
I saw with Firebug that the POST contains the value of the input field is sent only updating the page and not immediately. Why?

You don't have a proper click/submit handler registered for the form submission. Instead, you call $.ajax only on document ready. That's why you only see the submission on page load (or to be more accurate, document ready).
You need to listen to the submit event, so change your code to something like the following
$(document).on("submit", "form", function(e) {
e.preventDefault();
$.ajax({
…
});
});
You don't need to wait for the document to be ready if your javascript is at the end of the page (it's always ready at that point). And I noticed that you include both v1.9 and v.1.10 of jQuery and that's generally not needed nor advisable.

Related

Submit form input value on page load with ajax

I have form and a input in it and I want to send its value to my controller.I wanna send its value when a page load or refresh current page using ajax and jquery because my page reload when I write submit function in body tags onload event.
Here is my code:
<form method="post" id="counterForm" name="counterForm">
#csrf
<input type="number" name="count" id="count" value="{{ $visit->counts }}">
</form>
Script code:
$(window).load(function(){
var n=document.getElementById("count").value;
$.ajax({
type:'POST',
url:'/count',
data:n,
});
});
My controller file :
public function count(Request $request)
{
$value=($request->count)+1;
DB::table('visitorcounter')->update(['counts'=>$value]);
}
That was my code but its not working...Thanks.
you can use .submit() :
Bind an event handler to the "submit" JavaScript event, or trigger
that event on an element.
you code would be like :
$(window).load(function() {
$('#counterForm').submit(function(){return true;});
});
Check out this example: :
$(window).load(function(){
// this is the id of the form
var url = "results.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data:$( "#myformR" ).serialize(),
dataType: "html", //expect html to be returned
success: function (response) {
$("#prores").html(response);
}
});
});
I found it ... We can create a visitor counter very very simply by using a table with one integer column and a DB::table('test')->increment('count'); in AppServiceProvider Boot function.

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

HTML Links do not work after AJAX POST

Background: I am working on a small web application. AJAX will successfully POST the data to the action(create.php) and create.php will execute the necessary mysql query. Once AJAX is done, I append a message to the div id="container"></div> informing the user of a successful execution then clear the content "container" for future use; however, here in lies the problem.
Problem: After AJAX executes, I can not click on any HTML links already loaded onto the page(page.php). I have to refresh the page in order to click on any links and follow them to their destination. What is causing this to happen and how can I fix it?
AJAX does not need to return a result. It only needs to execute the specified jQuery code once the request is done. On a hunch, I altered create.php to echo the $_POST array and have AJAX return that as a result. Once AJAX loads the result into the "container" I still can not click on any links loaded on page.php
Answer: The DOM was not being reloaded after AJAX calls causing bootstrap dropdown menus to not function properly. The bootstrap dropdown class had to be manually reinitialized after each call. This has already been answered in detail here
create.php
<?php
if($_POST){
//run mysql query
}else{
//do nothing
}
?>
form.php
<form id="new-items">
<input type="text" name="item" />
<input type="button" onclick="create_item()" name="Submit" value="Submit" />
</form>
page.php
<html>
<head>
<script>
$(document).ready(function(){
$("#add_items").click(function(){
event.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow");
}, 5000);
setTimeout(function(){
$("#content").empty();
}, 8000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>
Link1
Link2
Add New Items
</nav>
<div id="content"></div>
</body>
</html>
After you fadeOut the #content element, it remains hidden. The next time you call your AJAX function, it's loading create.php into an invisible element.
Try:
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
Other issues: <div class="content"> should be <div id="content">; you didn't include jquery.js at the top of your script; you didn't pass the event object e to your click handler.
page.php should now look like:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#add_items").click(function(e){
e.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>Add New Items</nav>
<div id="content"></div>
</body>
</html>
The anchor links in the <nav> will natually 'refresh' the page with the new content.
If you want to load the content via an ajax request then you should try the following:
Add a common class to the links
<nav>
Link1
Link2
Add New Items
</nav>
Then attach a click event to each link which intercepts the default page refresh with e.preventDefault(). The you can perform the ajax request using the href attribute of that link.
$(function(){
$(".anchor").on('click', function(e){
e.preventDefault();
var $this=$(this);
$("#content").load($this.attr('href'));
});
});
The DOM was not being reloaded after AJAX call. Boostrap dropdown module has to be manually reinitialized after each call. Detailed answered here: answer

Foundation Form in Reveal Modal - Abide Validation Events not firing

I'm working on a login/registration for a simple web app. I'm using Foundation to do so. The index page shows a login screen and a register button, if the user clicks this a Reveal Modal appears which includes the register form. This form uses abide to do the data validation (email address, matching passswords etc.). I want the 'register' submit button to be disabled if there are any validation errors and then not disabled when everything is good.
I have used the code on the Foundation Docs where it says:
$('#myForm')
.on('invalid.fndtn.abide', function () {
var invalid_fields = $(this).find('[data-invalid]');
console.log(invalid_fields);
})
.on('valid.fndtn.abide', function () {
console.log('valid!');
});
For some reason (that I can't find after much searching) these events aren't firing. My form has the correct ID, my js file is loading correctly (I put console.log messages either side of that jquery code) and I've tried calling:
$(document).foundation('abide','events');
as suggested here. But I'm still not getting any events.
Any ideas? Could it be because I've got it in a modal or something?
Thank you for your time.
EDIT: I found this page here which says to add:
$('#your_form_id').foundation({bindings:'events'});
instead of:
$(document).foundation('abide','events');
But that doesn't seem to change anything either.
Try using $.getScript after loading the form to run the javascript.
eg:
$('#myModal').foundation('reveal', 'open', {
url: 'form.html',
close_on_background_click:true,
success: function(data) {
$.getScript( "form.js", function() {});
}
});
I had the same problem with fancybox and ajax check before submit.
This is my solution that works for sure
<form id="my_form" action="...." method="POST" class="popup" data-abide="ajax">
<input type="text" name="check_this_field_with_ajax" id="check_this_field_with_ajax">
....
</form>
<script type="text/javascript" src="..../js/foundation.min.js"></script>
<script type="text/javascript" src="..../js/foundation/foundation.abide.js"></script>
<script type="text/javascript">
$('#my_form')
.on('invalid.fndtn.abide', function() {
console.log('NOT Submitted');
})
.on('valid.fndtn.abide', function() {
console.log('VALID');
})
.on('submit', function(e) {
var ajaxRequest = $.ajax({
type: 'GET',
url: "....",
data: {xxx: yyy},
cache: false,
dataType: 'json',
});
....
ajaxRequest.done(function() {
if (ok) {
$('#check_this_field_with_ajax').parent().removeClass('error');
$('#my_form').attr({'submit_this_form': 'yes'});
$(document).foundation('abide', 'reflow');
$('#my_form').trigger('submit.fndtn.abide');
}
});
}
</script>
in foundation.abide.js search line "validate : function (els, e, is_ajax) {" and add:
if (
is_ajax &&
form.attr('submit_this_form') === 'yes'
) {
return true;
}
before
if (is_ajax) {
return false;
}

Send HTML form post data to file with Jquery?

I am trying to send post data to my post data file handler called postinfo.php with jQuery but so far I can make it.
Here is my post.php code:
<HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<script type="text/javscript">
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "http://www.vemvo.com/test/postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
</script>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" id="submit" name="submit" value="Send">
</form>
You can see the page here: http://www.vemvo.com/test/post.php
Here is the code from my postinfo.php:
<?PHP
$ime = $_POST['ime'];
echo "Your name is $ime";
?>
Here is located postinfo.php - http://www.vemvo.com/test/postinfo.php
So where is my mistake and how I can make it work?
Now it's not sending the data and not giving me the success alert.
Your jQuery selector isn't going to find that form, since the selector is running before the form tag exists in the DOM. Try wrapping it in the jQuery function to wait for the document to be ready:
$(function () {
$('#form_id').on('submit', function(e){
// the rest of your code
});
});
It also might be a good idea to return false at the end, to further suppress the form's default post action:
e.preventDefault();
$.ajax({
type: "POST",
url: "./postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
return false;
Currently the form is posting as normal. Since the AJAX handler is never attached (because the element doesn't exist when the selector executes), it's just doing a normal document-level form post. And since there's no action attribute specified in the form tag, the page is posting to itself by default. Which just responds with the current page.
Edit: You also have a typo which may be preventing the browser from executing your JavaScript code at all:
<script type="text/javscript">
You're missing the second "a". This should be:
<script type="text/javascript">
You MUST spell text/javascript correctly
You need to assign the event handler on load
There should not be any need to return false as posted by some other people here
NEVER call anything submit in a form
Wrap your html in body tags
Use a correct DOCTYPE
For files you can have a look at uploadify or How can I upload files asynchronously?
Fixed code for point 1 to 6
<!DOCTYPE html>
<html>
<head>
<title>Test Ajax</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "./postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
});
</script>
</head>
<body>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" value="Send">
</form>
</body>
</html>

Categories