I have a basic messaging service on a web Node / Express web app, and I'm trying to submit the form via Ajax, using the FormData object.
If I submit the form without AJAX, then everything works fine, but with AJAX the req.body. are all undefined.
On the server, I need to look for the data somewhere other than req.body when using AJAX??
Creating the FormData object:
var ajaxData = new FormData;
ajaxData.append('newMessage', $('.new-message').val()) // I've console.logged these, and their values are correct
ajaxData.append('senderId', $('[name="senderId"]').val())
ajaxData.append('senderName', $('[name="senderName"]').val())// I've console.logged these, and their values are correct
ajaxData.append('recipientId', $('[name="recipientId"]').val())
ajaxData.append('recipientName', $('[name="recipientName"]').val())// I've console.logged these, and their values are correct
And this is the POST request:
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: false,
cache: false,
contentType: false,
processData: false,
complete: function() {
console.log('message created');
},
success: function(data) {
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(errorThrown);
}
});
EDIT
Thanks to G. Mansour for his answers below. In case anyone else gets here, the issue was the line:
contentType: false,
I tried this line at some point, which also doesn't work
contentType: 'application/json',
But when I remove the line entirely, everything is working as normal... If anyone can tell me why this line was breaking everything, I'd be interested to know.
This is the html part
<form id="form" action="" method="post">
<input type="text" name="msgID" id="msgID">
<input type="text" name="senderId" id="senderId">
<input type="text" name="senderName" id="senderName">
<input type="text" name="recipientId" id="recipientId">
<input type="text" name="recipientName" id="recipientName">
<input type="submit" name="dsq" value="dsqdsq">
</form>
this is the JavaScript part
<script type="text/javascript">
$(document).ready(function(){
$("#form").submit(function(){
$.ajax({
url: "test.php",
data: $("#form").serialize(),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
return false;
});
});
</script>
And this is the php code
<?php
die(json_encode(array("status"=>true)));
?>
Hope that will helps you.
I checked your code it says that's
Illegal invocation
So i'll give a solution you can use
data: $form.serialize(),
dataType: 'json',
And then you can catch your returned result by
console.log(JSON.stringify(e));
Wish that helps. If you have some errors i can help you.
Related
I'm trying to submit a google doc form through AJAX, but it's not working. It keeps trying to send the form to the page I am on as a GET, rather than the google form POST url request I am trying.
My form looks like
<form id="ss-form" target="_self" onsubmit="" action="">
.....
<input type="submit" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action ">
</form>
and my JS looks like:
<script>
$('#ss-form').submit(function(e) {
e.preventDefault();
$.ajax({
url: "https://docs.google.com/a/example.com/forms/d/e/1FAI324B_-XUt0dQ-0AmlfwdfUu5dbEefwjVNud_hNlOKQ/formResponse",
data: $(this).serialize(),
type: "POST",
dataType: "xml",
success: function(data) {
console.log('Submission successful');
},
error: function(xhr, status, error) {
console.log('Submission failed: ' + error);
}
});
});
</script>
But this just reloads my page like example.com?entry.1850833=test and it's as a GET request.
Any ideas why this is happening? How do I get it to send it through the AJAX code, and stop the form just refreshing on the current page as a GET?
try add return false
$.ajax({
url: "https://docs.google.com/a/example.com/forms/d/e/1FAI324B_-XUt0dQ-0AmlfwdfUu5dbEefwjVNud_hNlOKQ/formResponse",
data: $(this).serialize(),
type: "POST",
dataType: "xml",
success: function(data) {
console.log('Submission successful');
},
error: function(xhr, status, error) {
console.log('Submission failed: ' + error);
}
});
return false;
Remove "_self", there should be no target since you're submitting the form through AJAX.
I am trying to send images on server using jquery and ajax method. I want to upload multiple files but I am not able to get it properly.
My html codes,
<input type="file" name="imgs" multiple class="form-control floating-label" placeholder="">
my jquery codes,
var imgData = new FormData();
imgData.append('uid', user_id);
imgData.append('o_img', $('input[name="imgs"]').get(0).files);
$.ajax({
url : CDN_HOST + "index.php?action=upload",
type: "POST",
data : imgData,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
success: function(data, textStatus, jqXHR)
{
if(jqXHR.status == 200){
if(data.error == 'true'){
alert'(true');
}else
if(data.error == 'false'){
alert('false')
}else{
alert(JSON.stringify(data));
}
}else{
alert('Some error');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//$('html').html();
$('html').html(jqXHR.responseText);
//$('html').html(JSON.stringify(jqXHR));
}
});
my php codes are,
if($_POST["o_img"]){
$_response = $_POST['o_img'];
}
header('Content-Type: application/json');
echo json_encode($_response);
The response in json I am getting is "[object FileList]". If I use $_FILES['o_img'], I am getting undefined variable. Can anyone tell me how can I use jquery or javascript to get multiple files and send it to server via ajax post?
Thank you for your time in advance. :D
Just use following method to simplify your post method
var formData = new FormData($("form#Form Id")[0]); // Mention here your form ID
function save_from() {
$.ajax({
type: "POST",
url: "/", // url goes here
data: formData,
success: function(data) {
//Your Code Goes here
},
cache: false,
contentType: false,
processData: false
});
}
Sample Form
<form action="" id="Form ID" method="post" enctype="multipart/form-data">
<input type="file" name="imgs" multiple >
<input type="button" value="submit" onclick="save_from()" >
</form>
How are you going to send REST's action words to the server if javascript is disable from your browser?
Below is my simple test for sending RESTful verbs to the server. It tightly relies on ajax's type: 'GET', etc.
jquery,
$( document ).ready(function() {
$(".rest-get").click(function(){
$.ajax({
type: 'GET',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
$(".rest-post").click(function(){
$.ajax({
type: 'POST',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
$(".rest-put").click(function(){
$.ajax({
type: 'PUT',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
$(".rest-delete").click(function(){
$.ajax({
type: 'DELETE',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
});
html,
<ul>
<li>Get</li>
<li>Post</li>
<li>Put</li>
<li>Delete</li>
</ul>
php,
<?php echo $_SERVER['REQUEST_METHOD'];?> // you get PUT, DELETE, GET, or POST
I know we can send POST from html's form,
<form method="POST">
...
</form>
But what about PUT and DELETE? If there is no way to send them from HTML's form, then your webservice or API would fail when the javascript is killed off the browsers then?
You would use POST but in addition send the following:
PUT
<input type="hidden" name="_method" value="PUT"/>
DELETE
<input type="hidden" name="_method" value="DELETE"/>
There is sadly no standard way to do it with a <form> tag.
Source: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.1
HTML forms only support GET and POST due to various reasons relating to caching, whether or not it's safe to repeat failed requests, etc (PUT and DELETE support were in a HTML 5 draft, but dropped for these reasons).
It could be possible to work around these by using a hidden field in the form to specify the actual method, and then look for that field on the server.
<form method="post">
<input type="hidden" name="actualMethod" value="PUT" />
</form>
On the server you'd have something along the lines of:
$formMethod = isset ($_POST ['actualMethod'])? $_POST ['actualMethod']: $_SERVER ['REQUEST_METHOD'];
switch ($formMethod) {
case "PUT":
// ...
Of course there's a lot of limitations to using this trick, but it should suffice for simpler cases.
I have a form, with a file input, that submits just fine when I use the default action to submit the form. But, when I use JQuery and AJAX to make the call to the PHP file, it does not seem to get the file. Is there something that I need to add for sending files through JQUERY/AJAX?
My HTML:
<form id="photo-form" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" class="upload-input" name="upload-new-input" autocomplete="off"/>
<input type="submit" name="submit" value="submit/>
</form>
My JQuery:
$(document).ready(function() {
$("#photo-form").submit(function(e) {
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "uploadcover.php",
data: dataString,
async: false,
success: function(data) {
alert(data);
}
});
});
});
You can use FormData to upload file with data
Here is sample code
JQuery
$("#photo-form").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "uploadcover.php",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
return false;
})
You can get it on PHP
PHP CODE
$Img = $_FILES['upload-new-input'];
You can see tutorial Uploading files with jquery ajax
Hope It helps you :)
You cannot access file directly.
You can use a plugin, to do this for you, i.e. https://github.com/blueimp/jQuery-File-Upload
Also, in html5 it is possible to access a file from file input as a blob. You can than send it using formData.
More info here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
HTML
<input type="file" id="file1" />
SCRIPT
file=$("#file1");
$.ajax({
type: "POST",
url: "Allcammand.aspx?cmd=EnterProduct&idCompany="+getParam("idCompany"),
type:"post",
data: {
file: file
},
async: false ,
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); ShowMessage("خطا در انتقال اطلاعات شرکت","fail");}
});
This is true whether the file transfer.
in Allcammand.aspx how can get file?????
Uploading files via AJAX is a complex process that you probably aren't going to want to write yourself. I'd recommend using something like this: http://jquery.malsup.com/form/