Sending dynamic POST data with Javascript - 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
}
});
});

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>

Is it possible to get php echo/response to Ajax without posting through Ajax?

Ajax parsing, wondering if it is possible if i post a form with text and images through an html form. And just getting the response back through Ajax?
Steps
1.) Form is in html and submit button in html
2.) Form submitted to php, and it runs through verifying/Uploading text and images.
3.) Any echos from the php is received through AJAX.
I am not sure if its possible to do so. Thanks for your time.
Javascript
$("button#submitbutton").click(function () {
$.ajax({
url: ("submitlisting.php"),
type: 'GET',
dataType: "text",
success: function (data) {
console.log(data); // e == result from the ajax call.
$("p#result").html(data);
}
});
});
use a hidden iframe as target for the form
<form target="form_result"><!-- input elements --> </form>
<iframe name="form_result" style="display:none;"></iframe>
Then after form is submitted, check the content of the iframe to read the response.
No. Not in the way you're thinking. The server responds to a request and the cycle ends there. If you submit a form, that is one request, and the client cannot listen to arbitrary requests sent by the server. To obtain the functionality that you are thinking of (seeing some sort of progress as the user is uploading a file, for example), you would need to do everything by AJAX.
A simplistic way is to use some sort of AJAX file uploader (blueimp comes to mind: https://github.com/blueimp/jQuery-File-Upload), and then poll the server for progress updates using AJAX.

Staying on same page after the form is submitted and then process the form again

I'm integrating Marketo (3rd party marketing software) with one of our tools on our website.
There is a form that calls an action "http://info.a10networks.com/index.php/leadCapture/save" after it is submitted and the form data is saved into Marketo:
<form
class="lpeRegForm formNotEmpty"
method="post"
enctype="application/x-www-form-urlencoded"
action="http://info.a10networks.com/index.php/leadCapture/save"
id="mktForm_1225"
name="mktForm_1225">
I want to use the same form data to store it in local database(MySQL) too. Ideally, I'd like to load the same page after the form data is sent and also store this form data locally.
Is there a way to perform the following actions:
the form action is called and the data is sent to an external
database
load back the same page and store this form data locally into the database (be able to use $_POST)
I'm using PHP and plain javascript for this integration. Please advise.
You can do this using an ajax call to your own scripts, then submitting the form to marketo.
Essentially if you want to capture the data before its sent off to a remote server for processing you'll capture the data first then allow the form to submit and do its intended processing afterwards.
Here we capture the click of the form, then make sure to disable the button by adding a class to it. So that it won't let the user do multiple clicks before the processing is done. When its done gathering the information and sending if off to your php page it submits the form it its action property.
In this example I grab the value from an input that has the name property set to firstName, this value will be sent over to my PHP script and because I chose a type of POST i can see it in my as
$_POST['firstName']
to debug your post paramters to see what the data looks like so this in your receiving PHP script
echo '<pre>', print_r($_POST, true), '</pre>';
this will give you a display of the data captured.
<script type="text/javascript">
$(document).ready(function() {
$('.formSubmitButton').on('click', function(e) {
e.preventDefault();
if (!$('.formSubmitButton').hasClass('submitted'))
{
// disable the form to prevent multple clicks
$('.formSubmitButton').addClass('submitted');
$.ajax('/path/to/my/db/script', {
type: 'post',
data:{
firstName: $('[name="firstName"]).val(),
lastName: $('[name="lastName"]).val()
}
}).done(function(data) {
$('.parentForm').submit();
// enable the form
$('.formSubmitButton').removeClass('submitted');
});
}
return false;
});
});
</script>

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