Can't get values from form? - javascript

I can't get the value from the form. Due to Firebug the form is submitted tho and when I delete the js it works so it has something to do with it.
$ok= $_POST['ok']; //this doesnt work
if($ok== "ok" ){
echo "works";
}
<script type="text/javascript">
$(document).ready(function() {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
});
ev.preventDefault();
});
});
function submitForm2() {
$('#form').submit();
}
</script>
<div onclick='submitForm2();'></div>
<form action='' method='post' id='form'>
<input type="hidden" name='ok' value="ok">
</form>

When the form is submitted, your first set of JavaScript kicks in. It:
Stops the normal submission process running
Takes the data from the form and submits it via Ajax
Since the normal form submission doesn't run, the page doesn't reload, so you don't load a new document, so you don't see the document with the ok in it loaded in the main browser window.
Since you don't have a success handler for the Ajax request, you completely ignore the response the server sends back to the JavaScript … so you don't see that document (with the ok in it) either.
If you want to see the results of an Ajax request, then you have to write JS to show you the results (or examine the Net tab of your developer tools).

Related

Javascript to Post Inside a Div

I have this code bellow and I need it to make a post inside a div.
<script type="text/javascript">
$(function() {
$(".loader").click(function(event) {
event.preventDefault(); // stop the link loading the URL in href
$('#content').load($(this).attr('href'));
});
});
</script>
<form method="post">
some random inputs and checkbox's goes here
<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">
</form>
When submiting, the javascript is sucessfully loading the consulta_produto.php inside a div called "content", however, I need to adapt the script to make it possible to POST too
Someone at other topic said to Use $(".loader").parent("form").submit instead of $(".loader").click, however i didnt understood what he meant, I tried changing it in a lot of different ways, but none of them worked
I researched a few topics about how to post with javascript, but I could adapt none of them to keep the function to load consulta_produto.php inside the div "content"
So I wonder, how can I adapt my javascript to keep loading consulta_produto.php inside content div while posting the data from some inputs and check boxs?
First of all, you need to either:
Place all of your <script> code after the relevant HTML has been loaded, OR
Wrap it all in a $(document).ready(function() {...}); to achieve the same effect
Then, instead of executing code at your inputs click() event, you can do it upon your forms submit() event. (This is basically what you mentioned someone told you in another topic). I changed your submit input to a submit button, doesn't really matter.
So, instead of loading the href attribute, you load the action attribute of the form itself into the div.
Of course you want to submit actual data along with the form - no problem. You just use an AJAX method. This is in order to stop the page from reloading.
First you do the preventDefault() to stop the usual page reload. Then you initialize the $.ajax() method.
Data: The first parameter 'data' contains all the form data to pass
along.
Type: Represents the type of request (POST)
URL: This is the form action (/consulta/consulta_produto.php).
Success: Finally, the 'success' parameter contains a function
which loads it all into the specified <div>.
AJAX is essential when avoiding page reloads in PHP, play around with it!
<script type="text/javascript">
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
$.ajax({ //AJAX Method
data: $(this).serialize(), //Gets data from form
type: $(this).attr('method'), //Gets the method, in your case POST
url: $(this).attr('action'), //Gets the form action
success: function(r) {
$('#content').html(r); //Loads data into div
}
}); //End of AJAX Method
}); //End of form submit event
});
</script>
And here is your HTML:
<div id="content" style="width:100%; height:500px; ">
</div>
<form id="form" action="/consulta/consulta_produto.php" method="post">
some random inputs and checkbox's goes here
<button type="submit">Consultar<button>
</form>

AJAX load-eventlistener fires before getting response from server

I'm writing an snippet to upload images through AJAX. A user selects the image in a form file-input. The form has a onsubmit-function which prevents default, so that the page doesn't reload after submitting. In this function the formdata is captured and than send through a XMLHttpRequest which has some event listeners appended. Also the "load"-eventlistener. This "load"-function consists of things like hiding a loader and echo something like "finished uploading". The page where the data is transmitted through ajax has a php-script which scales the image, copy it, rename it and so on. To it creates various copies in different sizes of the image.
The Problem: If I submit the form NOT through ajax, everything is fine. The php-needs some seconds, till everything is saved and the page is loaded. Through Ajax, directly after submitting the form, it says "finished", but the php-script is not executed! It feels like AJAX stops PHP running the script. The "load"-function IS FIRED! But way to early! Almost directly after submitting...
Here's the JS-Code:
loader("show");
window.event.preventDefault();
var data = $(form).serializeArray();
var src = form.getAttribute("action");
$.post( src, data )
.done(function( data ) {
loader("hide");
});
I have also tested with clean JS, but same problem:
var formdata = $(form).serializeArray();
var page = form.getAttribute("action");
loader(show);
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function(event) { completeHandler(event);}, false);
ajax.open("POST",page);
ajax.send(formdata);
completeHandler:
function completeHandler ( evt ) {
alert("finished");
loader("hide");
}
Thanks for help! :)
EDIT: The HTML:
<form method="post" action="create.php" onSubmit="uploadForm(this)" enctype="multipart/form-data">
<input id="file1" type="file" name="image">
<input type="submit" value="Add" name="submit">
</form>
I have a feeling the reason why it is being fired too quickly is you are not canceling the default action of whatever is triggering the function. You either need to call preventDefault or return false to stop the default action from causing the page to exit which aborts the Ajax calls.
function uploadForm () {
//function uploadForm (event) {
//event.preventDefault(); //cancel the default action
loader("show");
//window.event.preventDefault(); <-- get rid of this
var data = $(form).serializeArray();
var src = form.getAttribute("action");
$.post( src, data )
.done(function( data ) {
loader("hide");
});
//or
return false;
}
EDIT:
You posted you are calling it onsubmit so you need to cancel the submission. Add the return to the onsubmit and the above return false from your method.
<form onSubmit="return uploadForm(this)" ...>

Sending dynamic POST data with Javascript

So basically, I'm trying to send some data to a remote PHP page, via POST, with 4 static parameters and one random parameter, a number.
So far what I have done is created an HTML page with a form with 4 hidden fields and 1 empty field, in which a random number is inserted as the value via Javascript (using Math.random). Now whenever I submit this form, it takes me to the remote PHP page, and so I have to click back again (in the browser) and then submit.
So, I decided to load this form in an iFrame in another HTML Page, so after clicking submit, I can just hit refresh, and then submit again.
I want to know, is there a way I can use Javascript in the parent HTML to automatically submit the form in the iFrame, then create a new random value and submit it again?
Here is my code so far
a.html
<html>
<body>
<form method="post" action="http://awebsite.com/remotefile.php">
*some hidden fields with the static values*
<input type="text" id="mytext" name="mobile_no">
<input type="submit">
</form>
<script>//don't remember the exact code, use javascript to generate a random number which is put in the value for mytext via getElementById</script>
</body>
</html>
now this was the form which was to manually send data to the server
this is to load an iframe:
b.html
<html>
<body>
<iframe src="a.html">
</body>
</html>
Can I use javascript in b.html to resend the form multiple times, but with the value of mobile_no different each time?
Or can I simply send POST data with the parameters to the server via simple Javascript (or PHP)
You question isn't 100% clear, but it sounds like you want to asynchronously post form data. You could easily do this with a JavaScript library like jQuery without the need for an iframe. First you should add an ID attribute to your form to make it easier to reference in your jQuery code. Then you can attach an event listener to the form's submit event where you can customize the form before submission and handle the response
$('#myForm').submit(function(e) {
// prevent default form submit action from occuring
e.preventDefault();
// load values need to make AJAX request
var method = $(this).attr('method');
var action = $(this).attr('action');
// Process Ajax request
$.ajax({
type: method,
url: action,
dataType: 'html',
data: $(this).serialize(),
beforeSend: function() {
// generate and assign per form submit random number
// show loading gif
},
success: function(response) {
// AJAX POST success, insert the HTML response into the DOM
},
error: function(jqXHR, textStatus, errorThrown) {
// console.log any errors for debugging here
},
complete: function() {
// Post completion tasks, such as hide loading gif
}
});
});

form within AJAX jQuery toggle, submits at parent onClick not from submit button

Basically mysimplewebform.php form submits when the toggle is clicked, as opposed to after the form is loaded, used by user and SUBMITTED via submit button at form. Obviously I need to have form operate functionally; user fills it out, and clicks submit. I simply used AJAX to bring in the form on the template page. Now everytime toggle button is clicked 'Form is submitted with empty values' and then appears in the toggle. Making it pretty useless at this point, I have been struggling with this forever. I think this is a matter of toggling the data: below --
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(), // This was a recent suggestion
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
Branched out from: How to send external form POST data through AJAX
Ok, so you want to display an html form when a user clicks a button? In that case you can use the simplified jquery load method:
$('#yourbutton').click(function(){
$('#somediv').load('/mysimplewebform.php');
});
I know this doesnt handle your toggle requirement, but i dont think that is where you are having issues.
Now onto the php. I dont know exactly what should be in mysimplewebform so heres an example
if(isset($_POST['fname'])){
//we have a post request, lets process it
echo 'hello'.$_POST['fname'];
}?>
<form action="absolute/path/to/mysimplewebform.php" method="post" id="mysimplewebform">
<input type="text" name="fname" placeholder="Enter Name">
<input type="submit" value="submit">
</form>
Notice the action is an absolute path to the file, because a relative path will be wrong if the form is loaded into another page via ajax.
Now when this form is submitted, the browser will be redirected to mysimplewebform.php.
I expect you want to stay on the same page, in which case you could submit the form via ajax:
$('#mysimplewebform').submit(function(ev){
ev.preventDefault();//stop normal redirecting submit
$.post( $(this).attr('action'), $(this).serialize(), function(data){
$('#somediv').html(data)
});
This replaces the whole form in the dom with the output, so the hello message would be displayed.
All of the above is an attempt to help you understand where you have been going wrong in your attempts. It is not the best solution to your overall problem - i would separate the html form and processing into seperate files for a start, but it should be familiar to you.

Getting some problem with apply event to dynamic added form in Jquery

I am loading the form in dialog box via jQuery
The code is like
<form class ="form1" action="" method="post" enctype="multipart/form-data" >
...
</form>
I am using jQuery form plugin to submit form like this
$(".form1").live('submit', function(e) {
var options = {
target: '.ajaxMessage',
beforeSubmit: showRequest,
success: showResponse,
type: 'POST'
};
alert('test');
$(this).ajaxSubmit(options);
return false;
});
Now
If i load the form directly without AJAX and then i submit the form then form gets submiited successfuly without any problem. It works 10 out of 10 times
In second case I load the form dynamically. When i click on form link then i load the form dynamically in a jquery dialog box then if i click on submit form then i can see the alert but form is not submitted. But it works sometimes but sometimes not. I would say it work 2 times out of 10.
Firebug console is also not showing any error
Is there any way i can find whats problem
Firebug will usually (I actually think not at all) won't show any errors for a ajax call, instead the error will be in the ajax request(still in firebug). Click the request and then response.
My guess is that there is a problem with the params you are sending or there is something wrong with what you a returning(i.e. you return html when ajax is expecting json, this will cause success never to be fired)
Also, try to pass an error:function(jqXHR, textStatus, errorThrown){} to the ` ajaxSubmit params and see what happens.

Categories