Using AJAX to submit a dynamically filled form to two locations - javascript

I am submitting a form that will need to go to 2 different locations. The form is hidden and auto filled with the jquery .val method. How would I write the ajax to submit this in 2 different locations? Am I able to do this if I don't have access to my server side settings?
Here is the Form I am submitting
<form action="x" method="post" class="form-inline">
<input type="hidden" name="players_name" class="form-control" id="playersFullName_submit">
<input type="hidden" name="players_email"class="form-control" id="playersEmail_submit">
<input type="hidden" name="players_score" class="form-control" id="playersScore_submit">
<input type="hidden" name="redirect_url" class="form-control" id="redirectURL_submit" value="x">
<input id="submit endGame" type="submit" class="btn btn-default" value="Submit Your Score">
</form>
Here is my jquery filling it out
$(function () { // fill form fields
$('#playersFullName_submit').val(playersFullName);
$('#p_name').append(playersFullName);
$('#playersEmail_submit').val(playersEmail);
$('#dateSubmitted').val(submitDate);
});
Here is how I think I need to set it up
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg){
// get response here
}
});
Would I need to enter anything into data, or will it pull it from my <form>?

You need to get the form data and inject it into the AJAX calls in the data property. You can do this with JQuery's serialize() method:
// Get your reference to the form:
var theForm = document.getElementsByTagName("form")[0];
$.ajax({
type: "POST",
url : "url1.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});

b/c you are submitting ajax not form, you need to prevent form form action submitting, declare you server side route in ajax instead.
$('#submit_btn').on('click', function(e) {
e.preventDefault(); // you need this so the form don't submit
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg1){
var msg1;
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg2){
var msg2;
}
});
});

$.ajax({
type: "POST",
url : "url1.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});

In case you have to find yourself having to send to many urls...
var theForm = document.getElementsByTagName("form")[0],
urls = ['url1.com','url2.com', ....];
$.each(urls, function(index,value){
$.ajax({
type: "POST",
url : value,
data: $(theForm).serialize(),
success: function(msg){
// get response here
}
});
});

Related

Submit an ajax-created form via ajax

I'm having trouble getting an ajax-loaded form (#ajaxLoadedForm) to submit via ajax. The formData object gathers no data. I figure I've got to attach an event-handler to the form so the DOM recognizes it, but I can't figure out how.
A couple of notes: I'm bypassing the 'submit' method and using a button (#button), so I can't attach the handler to that. The form itself is a sibling to #button, not a child.
<form id="ajaxLoadedForm" enctype="multipart/form-data" action="destination.php" method="POST">
<input type="hidden" name="state" value="1" />
<label for="fullname">Your Full Name</label>
<input type="text" id="name" autocapitalize="off" autocorrect="off" name="fullname" placeholder="your name" value="" />
</form>
<div id="button">Submit me!</div>
$('#button').click(function(){
var uploadData = new FormData($("#ajaxLoadedForm")[0]);
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
Try using the submit handler on the form itself
$('#ajaxLoadedForm').submit(function(e){
e.preventDefault();
var uploadData = new FormData(this);
});
Then make your button for submit a submit type
<button type='submit'>Submit</button>
In your php side, test the data coming by doing this:
print_r($_POST);
you can use serialize function for sending form data . Like below
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script >
$('#button').click(function(){
var uploadData = $('#ajaxLoadedForm').serialize();
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
</script>
Try below code..
$('#button').click(function(){
var uploadData = new FormData();
uploadData.append('fullName',$('#fullName').val());
jQuery.ajax({
url: 'destination.php',
data: uploadData,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
}
});
});
And try to access full name in php

AJAX jQuery doesn't display returned data

I have a script to fetch data and load it in a div, the code works fine and display the user id list if I don't use any form value and if I don't use type="POST", but it doesn't work (no result and no console error message) when I use $_POST values :
HTML :
<form name='newUser' id="searchForm" method="POST">
<input type="text" name="look_for" id="look_for">
<input type="text" name="lookage_from" id="age_from">
<input type="text" name="age_to" id="age_to">
</form>
fetchusers.php
$look_for = $_POST['look_for'];
$age_from = $_POST['age_from'];
$age_to = $_POST['age_to'];
$array = getProfilePicsList($look_for,$age_from,$age_to); //a function that select * from ...
echo json_encode($array);
jquery code:
$("#searchForm").submit(function(event)
{
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
return false;
});
In your ajax request, you are missing the data. just add this:
data: $("#searchForm").serialize(),
Example:
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
data: $("#searchForm").serialize(),
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
Without using data param, you can't get the values in $_POST array.
Some References:
https://api.jquery.com/jquery.post/
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

How to pass selected file to php script using jQuery?

The following form is what I use:
<form id="form-attachment" action="" method="post" enctype="multipart/form-data">
<input name="attachment" type="file" />
<input type="submit" />
</form>
This is what I do with jQuery:
$('body').on('submit', '#form-attachment', function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log('fine', data);
var url = 'imageupload.php';
$.ajax({
type : "POST",
url : url,
data : data,
success : function(response) {
console.log('success: ' + response);
},
complete : function(response) {
console.log('complete: ', response);
},
error: function(response) {
console.log('error: ', response);
}
});
});
And this is my imageupload.php file:
$response = array();
$response["c"] = isset($_FILES["attachment"]);
echo json_encode($response);
And this is result on console on submit():
success: {"c":false}
So, what is wrong? Why my file is not visible at all?
You can use FormData object, as shown below..
$('body').on('submit', '#form-attachment', function(e) {
var data = new FormData(jQuery('#form-attachment')[0]);
jQuery.ajax({
type: "post",
contentType: false,
processData: false,
url: jQuery(this).attr('action'),
dataType: "json",
data: data,
success: function (r) {
// Success Handeling
}
});
});
NOTE:- No need to append anything as other answer suggests.
This method shall pass all the input fields just like they would in a normal http form POST method.
Use FormData object.
Here's the example how to send file via jQuery ajax request:
$(document).on('change', 'input[type=file]', function() {
formData = new FormData;
formData.append('file', $(this)[0].files[0]);
$.ajax {
url: '/upload-url',
data: formData,
type: 'post',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
}
});
In your case you should serialize form first, append serialized data to the formData object. Then get file (or files) from a file field and append it to the same formData object. And finally send the formData object via ajax.

How to append json type data to new FormData

I have an php file like this
<form id="f-comment" class="form" method="post" action="submit_img_comment.php">
<textarea name="comment"></textarea>
<input type="submit" value="Publish" data-params='{"imageid":<?php echo $imageid; ?>}'>
</form>
I'm sending the form using jQuery ajax
$(document).on("submit", ".form", function(e) {
e.preventDefault();
// what form are you submitting?
var form = $("#" + e.target.id);
// parameters to send along with data
var params = $(this).data("params");
$.ajax({
type: form.attr("method"),
url: "include/" + form.attr("action"),
data: new FormData(this),
dataType: "json",
contentType: false,
processData: false,
cache: false
}).done(function(data) {
alert(data['msg']);
}).fail(function(data) {
alert("Error: Ajax Failed.");
}).always(function(data) {
// always do the following, no matter if it fails or not
})
});
So far so good.
The only thing missing is how to add the params to FormData. Any ideas?
Use .append(), see Using FormData Objects ; adjusting selector at declaration of params to $(input[type=submit], this) , where this is the form and .data() references .data() at input type="submit" element
$(document).on("submit", ".form", function(e) {
e.preventDefault();
var data = new FormData("form", this);
var params = $("input[type=submit]", this).data("params");
data.append("params", params);
$.ajax({
type: form.attr("method"),
url: "include/" + form.attr("action"),
data: data,
dataType: "json",
contentType: false,
processData: false,
cache: false
}).done(function(data) {
alert(data['msg']);
}).fail(function(data) {
alert("Error: Ajax Failed.");
}).always(function(data) {
// always do the following, no matter if it fails or not
})
})
The object FormData are the method append which add new parameters to the object.
For example:
var FD = new FormData('id-form');
FD.append('name','value');

File upload using Jquery ajax without form

Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);

Categories