I have this javascript in my page.
function save() {
// submit the dataform
s = document.dataform.action.split('?');
d = s[1]+'&'+$("#dataform").serialize();
$.ajax({
url: s[0],
data: d,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: handleReply
});
}
It is called when I want to submit the form (and handle the reply using AJAX). However although $_SERVER['REQUEST_METHOD'] is indeed "POST" when it arrives at the server, all the data arrives in the $_GET variable! :(
I have screens with more than 2K of data so I have to find how to POST the data using the normal (and unlimited) POST method.
I had a version with the url and data lines as
url: document.dataform.action,
data: new FormData(document.dataform),
This worked superbly with some data arriving from the action in $_GET and the rest from screen fields arriving in $_POST. Then I tested it using IE8 and IE9, which don't support FormData.
Can anyone suggest how I can modify the code to work in IE8 and IE9 and use POST transfer logic.
Thanks
Related
Using one site I became bored with clicking every time I want to change some data, so I want to send this data automatically. I found that data which is send is next:
But I don't know how to send data correctly. I'm using ajax and it looks like this:
$.ajax({
url:(some url),
type: 'POST',
data: ({
is_ajax:'true',
module:'check_yourself',
action:'check',
nums[2]['board'][1]:'false',
nums[2]['board'][2]:'false',
nums[2]['board'][3]:'false'
}),
success:function(data){
alert()
}
});
But it doesn't work, so what the matter is?
Im creating a simple upload script. I use a simple form to let people upload a picture and then a external php script will upload the picture and return some vars to the upload page.
But I cant get the part to return some vars to work. currently im using this:
The page that also contains the form:
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
document.getElementById("titel" + amount).innerHTML = response['naam'];
});
The upload page that should return some data:
echo json_encode(array('naam'=>$naam));
This scripts returns undefined..
If I remove the ['naam'] after response on the form page it will print out:
{"naam":"test.png"}
Hope someone know what im doing wrong.
Thanx in advance!
You said:
dataType: 'text', // what to expect back from the PHP script, if anything
… so jQuery will ignore what the server claims the data is (which seems to be HTML as you haven't changed the Content-Type header in your PHP) and process the response as if it was plain text.
response will therefore be a plain text string and not the results of parsing JSON.
Change dataType to "json".
The response you get from the server is the string. To use it as object, you need to parse it to JSON format using JSON.parse().
var obj = JSON.parse(response);
Then you can use:
obj.naam;
to get the value of naam from the object.
Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value ").
Var jsonObject = JSON.parse("Ajax Response object");
then use it jsonObject.keyName and it will return the value.
I am using the plugin jquery.form.js and I want to programmatically submit a form and include a file with it. The code and options I have set up with work with $.ajax but not .ajaxSubmit. According to the jquery.form.js documentation you can pass any standard $.ajax options to .ajaxSubmit but I can't seem to get it to work. I'd like to use .ajaxSubmit if possible so I can utilize some of the other features it offers.
$(document).ready(function() {
$('#file-form').submit(function(event) {
event.preventDefault();
var form = $("<form style='display:none;' method='post' action='video_upload.php' enctype='multipart/form-data'></form>");
var fd = new FormData();
fd.append('uploadedfile', $('#file')[0].files[0]);
var options = {
url: 'video_upload.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
beforeSend: function(xhr){
alert('start');
},
success: function(data){
alert(data);
}
};
$.ajax(options);
//form.ajaxSubmit(options);
return false;
});
});
Running $.ajax(options) works but form.ajaxSubmit(options) doesn't. What am I missing?
Thanks!
If you check the source code of the method ajaxSubmit - http://malsup.github.io/jquery.form.js you can see that the property data of the options is serialised/deserialised and converted several times. So most likely the content really submitted will be quite different from what happens in .ajax call. Later on the ajaxSubmit collects the files from form and submits them differently.
Basically, for me the specifying data while submitting with ajaxSubmit goes against the concept of this plugin, which is described as "The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process." Idiomatic way of using ajaxSubmit would be applying this method for the form with controls.
I have xml data fetched from a file on the server side, successfully accessed without use of server-side scripts (e.g. no php).
I'd like to write that xml data back to the file on the server side after some minor changes, again without use of server-side scripts (e.g. no php). Here is what I have so far:
<button id='WriteToXml'>Write to XML</button>
<script>
$('#WriteToXml').click(function () {
var output_xml;
$.ajax({
type: "GET",
url: "/data/testdata_input.xml",
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find('input').remove();
$(xml).find('test').append('<output></output>');
output_xml = xml;
}
});
// Alternative code?
// $.post( "/data/testdata_output.xml", $(output_xml), "xml" );
$.ajax({
type: 'POST',
url: "/data/testdata_output.xml", //url of receiver file on server
data: $(output_xml) , //your data
contentType: "text/xml",
dataType: "xml",
cache: false,
async: false,
success: function(xml) {console.log( 'success\n'+ $(xml).find('test') );}
});
});
</script>
In another SO thread, I read that it was necessary to use a server-side script due to the design of javascript (for security reasons). But then in another thread, I saw code that didn't involve php, so I'm hoping I could use that code to write to the xml file on the server:
$.ajax({
type: 'POST',
url: "/data/testdata_output.xml", //url of receiver file on server
data: "<test></test>" , //your data
contentType: "text/xml",
dataType: "xml",
cache: false,
async: false,
success: function(xml) {console.log( 'success\n'+ $(xml).find('test')
So far I get a success message, but the xml file on the server remains intact. It would be great to understand where I misunderstood. In the meantime I will use this php code on the server-side and try to have it work:
//javascript
$.post('savedata.php', {data: "<test></test>",filename: "/data/testdata_output.xml"}, function(){/*Save complete*/});
//savedata.php
$data = $_POST['data'];
$filename = $_POST['filename'];
$f = fopen($filename, 'w+');
fwrite($f, $data);
fclose($f);
But it would still be nice to understand.
Also, I'd love some notes on using xml file types in the $.post code rather than a php file (based on the $.post jquery doc):
$.post( "/data/testdata_output.xml", "<test></test>", "xml" );
Thanks
You need a server side script to handle anything that modifies the server. That script should set out the restrictions on who is allowed to write what and where. It's not due to the design of javascript; it's just that otherwise, anyone could write any file to any web server, which is clearly unsafe.
When the URL of the request is a script that responds to user input, you'd use an HTTP POST. When the URL of the request represents a file to be written (as in your case), you would typically use an HTTP PUT. (You don't really have to use PUT -- you're the one writing the handler script, after all -- but writing to a file on the server is what PUT is for.)
In terms of the jquery request, without server-side scripting, the POST request is not significantly different from a GET request, in that the content of the file found at the URL is returned as the body of the response. (There are differences -- e.g. the POST would not be cached -- but I think that's the gist of the jquery example you mention.)
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.