Send Ajax Variables with POST to PHP - javascript

I am trying to find the best way to send variables from Javascript to PHP without GET method. I found a way to send through POST method with AJAX:
<form method="POST" id="post" enctype="multipart/form-data">
<input type="file" name="image_upload[]" id="img1" />
<input type="file" name="image_upload[]" id="img2" />
<input type="file" name="image_upload[]" id="img3" />
<input type="text" name="description" id="description" />
<textarea class="intext" name="editor" id="editor"></textarea>
<input type="text" name="state" id="state" disabled="true" />
<input type="text" name="city" id="city" disabled="true" />
<input type="submit" id="submit" />
</form>
And I am trying to submit the form with jQuery:
$('#post').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "cpage.php",
data: {
'variable1': 'content var1',
'variable2': 'content var2'
},
success: function () {
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
NOTE: the variable "position" has been declared before and works fine.
Result: I get "Internal Server Error" in the alert. Any ideas?

First of All - show us what is going on the server side.
And now about the files being sent:
You should use FormData element for file submit threw Ajax, its not supported by old browser, the browsers that would support this are : ie>9, chrome > 7, opera > 12 safari >5, android > 3 gecko mobile > 2, opera mobile >12.
Use something like this:
$('#post').submit(function (event) {
event.preventDefault();
if( window.FormData !== undefined ) //make sure that we can use FormData
{
var formData = new FormData($('form#post'));
$.ajax({
type: "POST",
url: "cpage.php",
data: formData ,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data); // <- for debugging
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
} else {
//fallback
}
});
As you can see I added console.log(data), try looking at the returned data to identify any other problems.

Related

how to send form data in ajax with multiple files without refreshing?

in my form code there is text input, checkbox input, file input type...etc,
everything working fine except the file input it's only taking one value ( multiple files upload isn't sending through ajax call ) how can i send arrays inside the serialize() function ?
Code :
<form action="#" id="postAdd" enctype="multipart/form-data">
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file[]" multiple required>
<input autocomplete="off" type="text" class="form-control bg-white" name="discName[]">
<button id="postAdbtn" class="btn btn-primary d-block mt-2">Submit</button>
</form> $(document).ready(function() {
$('#postAdbtn').click(function() {
var form = $('#postAdd').serialize();
$.ajax({
url: 'add-product-done.php',
method: "POST",
data: {
form: form
},
success: function(data) {
$('.fetchData').html(data);
}
})
});
});
one more thing, how can i get the files in PHP ?
and thanks
Can you try something like this?
var form = new FormData($("postAdd"));
$.ajax({
url: 'add-product-done.php',
data: form,
contentType: "multipart/form-data",
type: 'POST',
success: function(data){
console.log(data);
},
error: function(err){
console.error(err);
}
});

AJAX form - post result data to correct DIV

Can someone help a JS newbie?
Almost everything is working, results are returned, nothing opens new tabs, forms submit to MC database....however I cannot get the result html to post to the correct DIV. All results are being posted to the footer div.
I am guessing my selectors are not specific enough? But I do not have the knowledge on how to structure correctly.
2 forms on page using AJAX submit.
1 pop up form and 1 form in footer..... but all the result html is posting the the div in the footer.
I have adjusted the function register names as suggested (and updated the code below), but form result data is still going to the footer div
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};
<!--HTML POP UP FORM-->
<form
action="mailchimp url"
method="post"
name="pop-form"
id="pop-mc-embedded-subscribe-form"
class=""
target="_blank"
novalidate
>
<div class="form-group">
<input
type="email"
name="EMAIL"
class="form-control required"
placeholder="Enter your e-mail"
id="pop-mce-EMAIL"
/>
<input
type="submit"
value="SUBSCRIBE HERE"
name="pop-subscribe"
id="pop-mc-embedded-subscribe"
class="button"
/>
</div>
<div id="pop-subscribe-result"></div>
</form>
<!--FOOTER FORM HTML-->
<form
action="mailchimp url"
method="post"
id="footer-mc-embedded-subscribe-form"
name="footer-form"
class=""
target="_blank"
novalidate
>
<div class="mc-field-group">
<label for="mce-EMAIL"
>Email Address <span class="asterisk">*</span>
</label>
<input
type="email"
value=""
name="EMAIL"
class="form-control required email"
id="footer-mce-EMAIL"
placeholder="Email Address *"
/>
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name </label>
<input
type="text"
value=""
name="FNAME"
class="form-control"
id="mce-FNAME"
placeholder="First Name"
/>
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name </label>
<input
type="text"
value=""
name="LNAME"
class="form-control"
id="mce-LNAME"
placeholder="Last Name"
/>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input
type="text"
name="b_dc51fb25cd808abedc98e3ff2_ea4d259202"
tabindex="-1"
value=""
/>
</div>
<div class="footer-btn">
<input
type="submit"
value="Subscribe"
name="footer-subscribe"
id="mc-embedded-subscribe"
class="button"
/>
</div>
<div id="footer-subscribe-result"></div>
</form>
You have two functions with the same name "register" so when you press the submit button in either forms it runs in the register function in the footer since it has the same name as the one dedicated to the popup form
Use this code and your form will work as expected:
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register1($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register1($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};
You are defining the register() function two times with the same name. The second one overwrites the first and everytime you call the function with that name you call the second function. An easy solution is to change the name of the functions (i.e registerPopUpForm() , registerFooterForm() ) and use them accordingly.

How to post form data as JSON?

I'm trying to build a registration site for a group project we are working on but can't figure out how to send the form data as json. I've tried googling a lot and changing the code but nothing seems to work. The problem I have is that when i press on the submit button I get an error like this from the API:
{"":["The input was not valid."]}
I think the reason is that my form does not send the data as JSON and it's they format they require according to their API documentation. My form code looks like this:
<form id="register_form" action="https://https://url.com/users/register" method="post">
<input type="text" pattern="[A-Za-z]{1,20}" placeholder="Name" name="name" title="Up to 20 alphabetical characters" required>
<input type="email" placeholder="Email" name="email" title="Must be a valid email address" required>
<input type="password" pattern="[a-zA-Z0-9-]+{8,20}" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
<input type="text" pattern="[a-zA-Z0-9-]+" placeholder="Homeadress" name="homeadress">
<input type="text" placeholder="Postnumber" name="postnumber">
<input type="text" placeholder="City" name="city">
<br>
<button value="Submit" type="submit">Register</button>
</form>
And the script i've been trying to get to work looks like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
<script type="text/javascript">
$('register_form').on('submit', function(event){
var obj = $('register_form').serializeJSON();
$.ajax({
type: 'POST',
url: 'https://url.com/users/register',
dataType: 'json',
data: JSON.stringify(obj),
contentType : 'application/json',
success: function(data) {
alert(data)
}
});
return false;
});
</script>
Any help would be greatly appreciated since I'm not very familiar with coding stuff like this.
Edit:
I also tried it with a script like this but still getting the same response:
<script>
$(document).ready(function(){
$("#submit").on('click', function(){
var formData = {
"name": $('input[name=name]').val(),
"email": $('input[name=email]').val(),
"password": $('input[name=password]').val(),
"homeadress": $('input[name=homeadress]').val(),
"postnumber": $('input[name=postnumber]').val(),
"city": $('input[name=city]').val()
};
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: 'https://url.com/users/register',
type : "POST",
dataType : 'json',
data : JSON.stringify(formData),
success : function(result) {
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
I tested it with our teachers test api also and the response is this:
{"message":"Bad Request","reason":"val: nil fails spec: :user-system.spec/login-request predicate: map?\n"}
There's a couple problems here.
Invalid start tag for script element. This was probably a copy and paste error, but worth mentioning:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
missing greater than symbol ^
Selecting register_form instead of #register_form in two places, the second was unnecessary regardless because you could reference this instead. This also resulted in the form submission not being cancelled.
You didn't include a $.serializeJSON plugin, again I'm assuming this is a copy and paste error.
$.serializeJSON (whichever you choose) should return a JSON string, but you run JSON.stringify on the result, which will be a string inside a string.
https://https:// This isn't a huge issue because it is in the action attribute of a form that should never submit, but worth mentioning.
In the example below I've provided a simple replacement for $.serializeJSON, and corrected the rest of the issues listed above. serialize_form in the code below can be replaced with whatever $.serializeJSON plugin you choose to use.
I have commented out the ajax request as what is really of concern here is getting the JSON from the form data, so I just log it to the console instead so that you can see it is a JSON string. I also removed the pattern attributes and required flags from the input for ease of testing.
const serialize_form = form => JSON.stringify(
Array.from(new FormData(form).entries())
.reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
);
$('#register_form').on('submit', function(event) {
event.preventDefault();
const json = serialize_form(this);
console.log(json);
/*$.ajax({
type: 'POST',
url: 'https://url.com/users/register',
dataType: 'json',
data: json,
contentType: 'application/json',
success: function(data) {
alert(data)
}
});*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="register_form" action="https://url.com/users/register" method="post">
<input type="text" placeholder="Name" name="name" title="Up to 20 alphabetical characters">
<input type="email" placeholder="Email" name="email" title="Must be a valid email address">
<input type="password" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter">
<input type="text" placeholder="Homeadress" name="homeadress">
<input type="text" placeholder="Postnumber" name="postnumber">
<input type="text" placeholder="City" name="city">
<br>
<button value="Submit" type="submit">Register</button>
</form>

How to solve this jQuery ajax post method undefine index problem while uploading images?

I want to Upload photos by using Ajax Post method,
Here is my html and javascript code
<script>
$(document).ready(function(){
$('#multiple_upload_form').submit(function(e){
e.preventDefault();
var upload = $('#images').val();
$.ajax({
type:'POST',
url:'album.php',
data:
{
upload : images
},
cache:false,
contentType:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
},
error:function()
{
$('#image_preview').html('error');
}
});
return false;
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="album.php" name="upload_form" id="multiple_upload_form" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="email">Album Name</label>
<input type="text" name="aname" class="form-control" id="aname">
</div>
<div class="form-group">
<label for="file">Upload Photos:</label>
<input type="file" id="images" name="images" />
</div>
<div id="images_preview"></div>
</div>
<center class="feedback" style="display:none">Loading...</center>
<button id="submit" name="submitt" class="btn btn-default">Submit</button>
</form>
and this is my PHP CODING
if(isset($_FILES['images']['name']) )
{
$img = $_FILES['images']['name'];
if(!empty($img))
{
echo 'MaxSteel';
}
}
else
{
echo 'Same Problem';
}
I am having undefine index : images
it works fine with input type="text" but when it comes to "file" type is shows error help me solving this problem
Go through this code, it may help
var data = new FormData();
data.append("Avatar", file.files[0]);
$.ajax({
url: "http://192.168.1.1:2002/,
type: "POST",
data:data,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
Its posible that the file is not upload becouse of some error. You should review the parameters related to file upload as UPLOAD_MAX_SIZE, etc.
You can use var_dump($file) to see the $_FILE content.
You need to be sending your data through FormData().
Try something like this:
var images = $("#images").get(0).files;
var formData = new FormData();
$.each(images, function(i, image) {
data.append("images[]", image);
});
Then send formData as your $.ajax data.

How to upload image using ajax request

I'm search in the internet for a solution. I find some of them but they didn't work for me. Basically I have an input form on a laravel project where I want to upload an image with ajax request.
On the Get request instead of sending the image is sending the following parameter value [object%20FormData]
I know that I'm doing something wrong but I don't know what it is. Can anyone help me? Here is my Html code
<form class="form-horizontal" id="upload" enctype="multipart/form-data" action="{{{ URL::route('upload') }}}" autocomplete="off" onsubmit="return false">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="file" name="image" id="image" />
<button type="button" id="upload_image_btn" class="btn btn-default">Upload!</button>
</form>
And here is my ajax code
var image = $('#image')[0].files[0];
formdata = new FormData();
formdata.append( 'image', image );
formdata.append( 'action', 'image' );
$.ajax({
type: "GET",
url: '{{{ URL::route('upload') }}}',
data: formdata,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var errors = data.responseJSON;
$.each(errors, function (key, data) {
$.each(data, function (index, data) {
$(".upload_error").text(data);
})
})
}
});
Can anyone help me to find what I'm doing wrong? Thank you
SOLUTION: as the comment says, I changed the GET request of ajax to POST and it work. Thank you for your help

Categories