I'm using this script to get all values from a form, in order to prepare it for an ajax request:
function saveDataAjax(){
var fd = new FormData();
var inputs = document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++) {
fd.append(inputs[i].name, inputs[i].value);
}
$.ajax({
url: '/edit.php',
data: fd,
type: 'POST',
dataType: 'html',
success: function(data){
alert(data);
}
});
}
However I'm getting a Type error from jQuery, and if I alert fd['inputname'] I get undefined, so I guess I must be doing something wrong somewhere...
Firefox debuggers tells me this: NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object # http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js:2
Add the following to the AJAX call:
processData: false,
contentType: false,
So it looks like:
$.ajax({
url: '/edit.php',
data: fd,
type: 'POST',
processData: false, //Add this
contentType: false, //Add this
dataType: 'html',
success: function(data){
alert(data);
}
});
This is probably not the reason, but just wanted to point it out: i is global here. The idea in JS is towards global abatement. Should probably be var i=...
this page help you ...:)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous">
</script>
</head>
<body>
<form method="post" id="fileinfo" enctype="multipart/form-data">
file <input type="file" name="slug"><br>
<input type="button" id="uploadBTN" value="Stash the file!"></input>
</form>
<script type="text/javascript">
$(document).ready(function()
{
$('#uploadBTN').on('click', function()
{
var form = $('form').get(0);
console.log(form);
var fd = new FormData(form);
fd.append('user_id',4);
fd.append('user_media_category_id',1);
//console.log(fd);
fd.append("user_", "This is some extra data");
$.ajax({
url: 'http://localhost/yii2/azstudio/project/api/web/v1/user-media/new',
type: 'POST',
data: fd,
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
</body>
</html>
Related
$(document).on('submit', '#color_changer_form', function(e) {
e.preventDefault();
var colorCode = $('#color_code').val();
var formData = new FormData(this)[0];
$.ajax({
headers: {
'X-CSRF-Token': "{{csrf_token()}}"
},
type: "POST",
url: "{{route('color.store')}}",
data: formData,
async: false,
success: function(data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
});
<form action="" method="POST" id="color_changer_form">
<input type="text" id="color_code" name="color_code">
<button type="submit" id="color_submit" class="btn btn-success">Save Change</button>
</form>
Controller snippet:
public function store(Request $request){
return response()->json($request->all());
}
When I try to get the whole form data using the jQuery AJAX FormData() method, I get an empty array.
In need to use this FormData() because in the near future I have to upload an image using the form data.
Send the whole formData object
Change:
var formData = new FormData(this)[0];
To
var formData = new FormData(this);
If there are no files involved it is simple to use serialize() also
$.ajax({
headers: {
'X-CSRF-Token': "{{csrf_token()}}"
},
type: "POST",
url: "{{route('color.store')}}",
data: $(this).serialize(),
success: function(data) {
console.log(data)
}
});
Never use async:false. it is a terrible practice and is deprecated
I'd like to pass a PHP session variable (called 'profileid') using FormData and AJAX. I thought this below would work, it did not. Why?
var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
imageData.append('profileid', <?php echo $_SESSION['profileid'];?>);
//Make ajax call here:
$.ajax({
url: '/upload-image-results-ajax.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: imageData,
//leaving out the rest as it doesn't pertain
You could add the profileid in the $.ajax URL parameter instead of adding it in FormData:
$(document).ready(function (e) {
$('#uploadImageForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "/upload-image-results-ajax.php?profileid=<?= $_SESSION['profileid']; ?>",
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response){
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}));
$('#uploadImage').on("change", function() {
$("#uploadImageForm").submit();
});
});
Don't forget to place session_start(); at the beginning of your code.
i want to post two items into server by using ajax in java-script; based on server-side document the post url is like this
http://example.com/h/{first-item}/{second-item}
this is my java-script code:
$('#add-order').on('click', function() {
var name = $('#name');
var drink = $('#drink');
var order = ?? // my question is this part what should i add
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: 'application/json',
success: function(data) {
console.log("Data added!", data);
}
});
});
and this is my HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="input-group">
<h4>Add a Coffee Order</h4>
<p>name: <input type="text" id="name"></p>
<p>name_space: <input type="text" id="drink"></p>
<button id="add-order">Add!</button>
</div>
<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
</html>
i am a new in ajax, thanks for your help.
You have to set the contentType to application/json in your Ajax request.
i.e as following:
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log("Data added!", data);
}
});
});
here is an example for creating and encoding a json object.
var myObj = {
"name": $('#name').val(),
"drink": $('#drink').val()
};
var order = JSON.stringify(myObj);
Hard to really understand the post here, but it seems to me you simply forgot to mark the ajax requests contentType as json. See example below.
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: 'application/json'
dataType: 'json',
success: function(data) {
console.log("Data added!", data);
}
});
<script type="text/javascript">
$(document).ready(function(){
$("#btnUpdate").click(function(){
alert($("#frm_data").serialize());
var formData = new FormData($("#frm_data")[0]);
var Desc= CKEDITOR.instances.editor1.getData();
$("#btnUpdate").attr('value', 'Please Wait...');
$.ajax({
url: 'update_job.php',
data: formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
{
$("#btnUpdate").attr('value', 'Update');
}
});
return false;
});
})
</script>
i use ckeditor for textarea field. but its can update value with new value, so i want to use another way with send textarea value with form data.
so how to send Desc data with fromData. in ajax.
To achieve this you can use the append() method of FormData to add whatever additional information you require:
$("#btnUpdate").click(function(e) {
e.preventDefault();
var $btn = $(this).attr('value', 'Please Wait...');
var formData = new FormData($("#frm_data")[0]);
formData.append('desc', CKEDITOR.instances.editor1.getData());
$.ajax({
url: 'update_job.php',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'post',
success: function(response) {
$btn.attr('value', 'Update');
}
});
});
I try to send a json object to a distant server, but I didnt receive success message. please what's wrong with this code:
function sendSMS(){
var input = '{"header":"****","****":*****,"****":"*****"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.stringify(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
// html code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript" src="sendSMS.js"></script>
</head>
<body>
<button onclick="sendSMS()">sendSMS</button>
</body>
</html>
Any help please.
You have to simple change your ajax call to this:
function sendSMS(){
var input = '{"header":"Ooredoo","msisdn":21620117297,"SMS":"Hello"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.parse(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
The main changes are JSON.stringify to JSON.parse this will help you to parse the JSON data into a JSON object, and the second change is the actual payload in which you missed a " at the end, just after Hello.
If you have any other question, just ask :)
Also I would recommend not to send the username and password as querystring parameter, use a POST request with a proper payload and last, if you can go through ssl