Jquery ajax simple form not working - javascript

I'm sending form data to a PHP file via AJAX, using jquery I hoped I could send the data easily seeing as it's only one text box etc. On submit click event the form data should be serialised and sent to submit.php, then I should get an alert from the php file with the response. Why doesn't it work?
Thanks.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$('#submit').click(function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
</script>
Then the HTML:
<form id="myform" >
<input type="text" name="content" value="button should be on same line" /><input
type="submit" class="button" value="Submit" id="submit" />
</form>

You haven't initalized the DOM ?
$(document).ready(function(){
// do your work here
});
EDIT :
Try this:
$("#submit").live("click", function (e) {
e.preventDefault();
$.ajax({type:'POST', url: 'submit.php', data:$('#myform').serialize(), success:
function(response) {
alert(response);
}});
});
});

First, try to determine that the form is submitting correctly. try submitting to
url: '/submit.php'
instead, as that may not have been the correct path.
Second, try sending the value unserialized and see if you get a correct.

Related

Post variables to php file and load result on same page with ajax

I have tried searching quite a bit but can't seem to make anything work.
I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.
What I have so far:
HTML:
<html>
<form id="form">
<input id="info" type="text" />
<input id="submit" type="submit" value="Check" />
</form>
<div id="result"></div>
</html>
JS:
<script type="text/javascript">
var info= $('#info').val();
var dataString = "info="+info;
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
});
</script>
PHP:
<?php
$url = '/api.php?&info='.$_POST['info'];
$reply = file_get_contents($url);
echo $reply;
?>
When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.
I cannot get any solutions to work.
Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
return false;
});
Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(
Thanks everyone for your help, I have it working now.
I was doing a few things wrong:
I was using single quotes in my php file for the URL and also for the $_POST[''] variables.
I needed to add return false; as Steve pointed out.
I did not have a "name" for the input elements, only an ID.
I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax. The code below.
/* ... */
$('#submit').click(function (){
$.ajax({
var info= $('#info').val();
var dataString = "info="+info;
/* ... */

submit form and check for complete without submit button

I need to submit a form and check for its completion without using the submit button.
I managed to submit it trough document.getElementById('logoForm').submit();, but now I need to call a function if the form was successfully submitted.
My form:
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
Submit function:
$("#file1").change(function() {
document.getElementById('logoForm').submit();
//setTimeout(reloadImg, 2000) this was how i called the next function but its not safe at all
alert('submited');
});
The function I want to be called on a successful submit:
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
You need to submit the form using AJAX, otherwise you will have a page reload, rendering all your JS void.
This is how you could do it with jQuery
//bind to submit
$("#logoForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
ok i got it working!!
$("document").ready(function(){
$("#file1").change(function() {
//bind to submit
$("#logoForm").submit(function(e)
{
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
});
});
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
but once i click the file input i have to reload the page to make it work again... any ideas how to work around this?
As Regent said: "Amazing mix of pure JavaScript and jQuery"
if you will be using jquery first of all you will need to include the jquery library, I don't know if you did that.
Also, if you are working with jquery try to use all that jquery provide you to write less code.
Seeing your code I am assuming that you have a form with a input type file into. And when a file is loaded to the field, you want to submit the form. Also the form is targetted to a frame, so I am assuming that you have an iframe element there too.
To know if the form was successfully submitted you can use an ajax request but in this case your are sending files with the form, so you can not use an ajax request.
You can return a javascript code in your response that will be executed from into the iframe so, you can access to the parent element to do that you want
I have modified a little bit your code to integrate jQuery at all.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
jQuery("#file1").change(function() {
jQuery('#logoForm').submit();
});
});
</script>
</head>
<body>
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
<input type="file" name="file1" id="file1" />
</form>
<iframe name="frame"></iframe>
</body>
</html>
Then in your includes/uplLogo.php you need to return the javascript code to execute a similar of reloadImg()
So, in your includes/uplLogo.php you could have:
<?php
...
Your code here
...
if($all_is_ok) { ?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var id = jQuery('#AppId', window.parent.document).val();
jQuery.post("includes/step_img.php", {id: id}, function(data) {
jQuery('#imgDiv', window.parent.document).html(data);
});
});
</script>
<?php } ?>
I have not tested it because I just wrote it but I think that works.
Try to comment this line: e.unbind();
Try also to add a log just after the input file changes, and verify if you can see the log in the js console:
...
$("#file1").change(function() {
console.log('input file changed');
//bind to submit
...
for those who will need this in the future the problem was:
$("#file1").change(function()
i just changed that to:
function changed()
and add it to input on onchange method!

Form not serializing

I've got a form which is loaded through ajax, and posted using ajax.
When try to send its data, nothing is added to post, here's a short version of code
<form id="userForm">
<input type="text" name="username" />
<button type="submit">Send</button>
</form>
Javascript:
(function($){
$.fn.ajaxForm = function() {
var $form = $(this);
$form.submit(function(event){
event.preventDefault();
$.ajax({
data: $form.serialize(),
type: 'post',
});
});
}
})(jQuery);
<script type="text/javascript">
$("#userForm").ajaxForm();
</script>
Everything works fine, request is sent, but $form.serialize() is empty
And i only had to ask.....
I've also added disabling of fields to the form after submitting which was the reason for the serialize not working. Removed that and it's now fine, sorry for bothering.

jQuery Submit Refreshing Page

The following code is intended to do a purely ajax POST request, instead it seems to do the POST via ajax and then the browser navigates to the response.
The HTML...
<div id="bin">
<form class="add" method="post" action="/bin/add/">
<p>I'm interested! Save for later.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Save">
</form>
<form style="display:none;" class="remove" method="post" action="/bin/remove/">
<p>I changed my mind--I'm not interested.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Unsave">
</form>
</div>
The jQuery...
$('#bin form').submit(function() {
$.post($(this).attr('action'),{
success: function(data) { $(this).hide().siblings('form').show() },
data: $(this).serialize()
});
return false;
})
As far as I understand it, the return false; line should mean that no matter what, any calls to the submit function or clicks on the 'Submit' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add or /bin/remove. But for some reason, the browser is changing pages.
Any idea what I'm doing wrong here? Thanks.
It could be your JavaScript is failing, so the default behaviour is being executed.
Try to examine the XHR in a tool like Firebug.
Also, you could try event.preventDefault() (where the first argument to your event callback is event).
my bet it's because of the $(this), try it this way....
$('#bin form').submit(function() {
var $this = $(this);
$.post($this.attr('action'), {
success: function(data) {
$this.hide().siblings('form').show()
},
data: $this.serialize()
});
return false;
});
demo no error
demo with the error
Use event.preventDefault() to prevent the default action of the event. One benefit is that you can place this before the Ajax request, so that if it fails, you will still have prevented form submission.
Your code is failing because the value of this in your success callback is the global window object. Your attempt to hide it fails. You probably want this to refer to the form, like this:
$('#bin form').submit(function(ev) {
var _this = this;
ev.preventDefault();
$.post($(this).attr('action'), {
success: function() {
$(_this).hide().siblings('form').show();
},
data: $(this).serialize()
});
})
See a working example.
Is the $(...).submit(...) inside a $(document).ready(function(){ code here }); ?
should be like:
$(document).ready(function() {
$('#bin form').submit(function() {
$.post($(this).attr('action'), {
success: function(data) { $(this).hide().siblings('form').show(); },
data: $(this).serialize()
});
return false;
});
});

Prevent redirection when form is submitted programmatically

I've got a form on the html page which gets submitted by javascript in some cases. The problem is that browser window change its location to the action URL specified for this form. Is there any way to prevent it of working this way?
Use a javascript library to submit the form via Ajax (xhr) or submit to iframe
Full Jquery example:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#yourForm').submit(captureSubmit)
})
function captureSubmit(event) {
var frm = $(event.originalTarget);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function(results) {
// do stuff
alert(results);
},
error: function(result) {
// handle the error
alert(result.status + ' ' + result.statusText);
}
});
return false;
}
</script>
<form id="yourForm" action="foo.html" method="POST">
Name: <input type="text" name="name">
<button type="submit">Submit</button>
</form>
[EDIT] made example more complete.
Post it with Ajax
You can either:
Submit with AJAX
Submit to an iframe

Categories

Resources