I am trying to submit a form then update some values and submit it again. However, when I do this only the LAST version is being submitted. I get one error for Unsafe Javascript attempt to access frame with URL domain2.com from frame with URL domain1 . Domains, Protocols and Ports must match.
form code:
<form id="hiddenform" method="post" enctype="multipart/form-data" action="http://www.actonsoftware.com/acton/forms/userSubmit.jsp" accept-charset="UTF-8" target="tintest">
the target is a hidden iframe with the id="tintest"
This is my code:
var tbody = $("#vmMainPage table:first tbody");
var lng = tbody[0].rows.length - 1;
var mnstr = "items: ";
$("#vmMainPage table:first tbody tr").each(function(i){
if ((i>0) && (i<(lng-3))) {
item = $(this).children("td").children("a").children("strong").html();
// quantity = "
console.log(item);
$("#hiddenform input#fld_0").val(item);
var $tsta = "";
for ( j=2; j<6; j++)
{
$tst = $("table:eq(2) tr:eq("+j+") td:eq(1)").html();
$tsta = $tsta + $tst +", ";
}
$email = $("table:eq(2) tr:eq(6) td:eq(1)").html();
$("#hiddenform input#fld_2").val($email+"_"+i);
$("#hiddenform input#fld_1").val($tsta);
$("#hiddenform").submit();
}
});
To make sure your requests are not interfering with each other, you can create an iframe for each request and target that.
this can be done with DOM
var cnt=0;
var ifr = document.createElement("iframe");
ifr.name="ifr"+(cnt++);
ifr.style.display="none"
document.getElementById("iframeContainer").appendChild(ifr);
document.forms[0].target=ifr.name;
document.forms[0].submit()
or jQuery
cnt++
$("#iframeContainer").append('<iframe src="about:blank" name="ifr'+cnt+'"></iframe>');
$("#hiddenform").attr("target","ifr"+cnt);
$("#hiddenform").submit();
Related
I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;
<body>
<form>
<label for="txtLength">Length</label>
<input type="text" id="txtLength" name="txtLength"><br><br>
<label for="txtWidth">Width</label>
<input type="text" id="txtWidth" name="txtWidth"><br><br>
<input type="hidden" name="submitted" value="1">
<input type="button" name="Calculate" value="Calculate" onclick="calArea();">
</form><br><br>
<div id="showArea">Enter Values and click Calculate.</div>
<script type="text/javascript">
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.readyState == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.send(len&wid&sub);
}
</script>
</body>
This code is for the server side.
<?php
print_r($_POST);
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
?>
Even tried so many codes, It doesn't send the data to server side.
I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.
Client-side code;
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
}
Server-side code;
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
len&wid&sub
Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.
You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.
PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.
The URLSearchParams API will generate URL Encoded data for you.
e.g.
xhttp.send(new URLSearchParams({ len, wid, sub }));
Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.
You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.
You also need to set the content type so this data will be parsed correctly.
So change
xhttp.send(len&wid&sub);
should be:
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);
Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>
I have a page that dynamically creates (using jQuery) Input boxes for the user. The user can then enter values in each input box he created. On clicking the save button a call is made to a javascript function that iterates through all the input boxes user created and sends these values using an XMLHttpRequest to the process.php file which inserts these values into the DB.
This code works fine if i send only one Request at a time. But if i loop it and send the value from each box on each iteration (means, send multiple requests using loop), only the last Request finds success. All the other calls except the last call gets aborted (found it using firebug).
Any idea why is this happening?
My code:
<script>
function saveTimeSlots(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch(e){
alert('Issue with browser.')
}
ajaxRequest.onreadystatechange = function(){
if( ajaxRequest.readyState==4 ){
alert(ajaxRequest.responseText); //This returns empty except for last call
}
}
var timeSlots = document.getElementById('formSlots').childNodes;
var date = $.datepicker.formatDate('dd-mm-yy', new Date($('#datepicker').datepicker("getDate")));
for(j=0; j<timeSlots.length; ++j){
var time = timeSlots[j].getElementsByTagName("input")[0].value;
var status = 1;
var queryString = "?date=" + date + "&time=" + time + "&status=" + status;
ajaxRequest.open("GET", "process.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
<input type="button" value="Save time slots" class="custom-button" onclick="saveTimeSlots()"/>
Following is the code of process.php
<?php
mysql_connect( $dbhost,$user,$pwd );
mysql_select_db( $dbase ) or die( mysql_error() );
$date = mysql_real_escape_string( $_GET['date'] );
$time = mysql_real_escape_string( $_GET['time'] );
$status = mysql_real_escape_string( $_GET['status'] );
$query = "INSERT INTO time_slots (`date`,`time`,`status`) VALUES ('" . $date . "','" . $time . "'," . $status . ")";
echo $query;
if( mysql_query( $query ) ){
echo "Success";
}else{
echo mysql_error();
}
mysql_close();
}
?>
This is what Firebug shows:
GET http://localhost/process.php?date=24-06-2012&time=1&status=1 Aborted
GET http://localhost/process.php?date=24-06-2012&time=2&status=1 Aborted
GET http://localhost/process.php?date=24-06-2012&time=3&status=1 200 OK 31ms
You cannot use an instance of XMLHttpRequest for more than one request. Create a new instance for each request.
Since you're already using jQuery, I recommend to use $.ajax (or $.get) to fetch the request.
function saveTimeSlots(){
$('#formSlots').children().each(function() {
var time = $(this).find('input:first').val();
var status = 1;
var queryString = "?date=" + date + "&time=" + time + "&status=" + status;
$.get("process.php" + querystring, function(responseText) {
alert(responseText);
});
});
}
You are using the same XMLHttpRequest object for all the requests, so as soon as you start the request, the next one starts another request on it which aborts the previous one.
Make a new XMLHttpRequest object for each request or just use jQuery's ajax. It's not good to have jQuery and not use it.
I am developing a php ajax-based application, and one of it's components is an image upload.
I know ajax is incapable of posting files, since it's Request based, but i did find a nifty iframe work around.
My goal is to send multiple files, but post them individually so i can process the upload and validate serversided, send the result, and then move on to the next file.
I would like to achieve this with a:
<input name="files[]" type="file" multiple=""/>
It all works all fine and dandy, but when it comes to sending them individually.. there doesn't teem to be a possible way.
My original idea was to treat the (element.files) as an array.. So i create duplicate form, and attempted to copy over the input to the other form (that was successfull)
but then when i tried to splice, or remove the unwanted elements so i can submit the form, i couldn't find a way to do it. Nothing worked...
Trying to alter the element.files.length to 1, didn't work
Trying to splice it didn't work..
Trying to just clear the indexes didn't work either...
If anyone could shed a green light, or just blast the ultra red light letting me know that this is not possible w/ an html input, it'll be greatly appreciated.
p.s: Flash isn't an option.
Here's some examples of my failed attempts:
<form name="image_upload" id="image_upload_form" action="image_uploader" method="POST" enctype="multipart/form-data">
<input name="userfile[]" id="filesToUpload" type="file" title="Select Your Files" multiple=""/> <br /><br />
<input type="button" id="imageUploadButton" value="Upload" onclick="valif('image_upload'); return false;" />
</form>
<!-- Hidden Form and File Input -->
<form name="single_image_upload" id="single_image_upload_form" action="image_uploader" method="POST" enctype="multipart/form-data">
<input name="userfile[]" id="fileToUpload" type="file" style="visibility: none; position: absolute; top: 0; left: 0;/>
</form>
<script type="text/javascript">
//This happens on submit
var multi_input = getElementById("image_upload");
var single_input = getElementById("single_image_upload");
single_input = multi_input;
//Assuming there are 2+ files chosen for upload, attempt to only upload the first one.
//Attempt 1
multi_input.files.length = 1;
//Attempt 2
multi_input.files.splice(1);
//Attempt 3
for (x = 1; x < multi_input.files.length; x++) { //skip 0, we wanna keep that one
multi_input.files[x] = null; // or ''.. same difference in this scneario.
}
</script>
Below is the actual code right now, working w/ 1 iframe.... This code works great, however it actually unfortunately sends every single file, every time.. And i just validate the right one on the serverside, but it's not practical, as i shouldn't have to send every single file all the time.
function ajaxUpload(form,url_action,id_element){
var detectWebKit = isWebKit();
form = typeof(form)=="string"?$m(form):form;
//Error Validator
var error="";
if (form==null || typeof(form)=="undefined"){
error += "Invalid Form.\n";
} else if(form.nodeName.toLowerCase()!="form"){
error += "Element Exists but it is not a form.\n";
}
if (id_element==null){
error += "The element of 3rd parameter does not exists.\n";
}
if (error.length>0){
alert("Error in image upload attempt:\n" + error);
return;
}
//Create Frame On The Fly
var iframe = document.createElement("iframe");
iframe.setAttribute("id","ajax-temp-"+rt_img);
iframe.setAttribute("name","ajax-temp-"+rt_img);
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
form.parentNode.appendChild(iframe);
window.frames['ajax-temp-'+rt_img].name="ajax-temp-"+rt_img;
//Upload Image
var doUpload = function(){
removeEvent($m('ajax-temp-'+rt_img),"load", doUpload);
var cross = "javascript: ";
cross += "window.parent.upload_result(document.body.innerHTML); void(0);";
$m('ajax-temp-'+rt_img).src = cross;
if(detectWebKit){
remove($m('ajax-temp-'+rt_img));
}else{
setTimeout(function(){ remove($m('ajax-temp-'+rt_img))}, 250);
}
}
//Post Form
addEvent($m('ajax-temp-'+rt_img),"load", doUpload);
form.setAttribute("target","ajax-temp-"+rt_img);
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();
}
function upload_run() {
var send_index = rt_img;
rt_img += 1;
var li = $('#fileList li:nth-child('+rt_img+')');
var filetype = li.html().substr(-3).toLowerCase();
var skip_mod = '';
//validate file type
if ((filetype != 'jpg') && (filetype != 'png') && (filetype != 'gif')) {
li.append(' - <b>invalid image file</b>');
} else {
li.append(' <img src="'+base_url+'sds_ajax/upload-ani.gif">');
//Initiate File Upload
ajaxUpload($m('image_upload_form'),base_url+'includes/core.php?post_action=image_upload&si='+send_index,li);
}
}
//Get the input and UL list
var button = document.getElementById('imageUploadButton');
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//Empty list for now
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//Populate List w/ files
rt_max = input.files.length;
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'Image ' + (x + 1) + ': ' + input.files[x].name;
list.appendChild(li);
}
//Run through created list
rt_img = 0;
upload_run();
//Disable Submit Button
button.disabled=true;
bump
It sounds like you need an iframe per file upload. So what I would do is have hidden fields for every other field in your normal form (in each iframe). Then when you click the submit button, you take all the visible fields and place the values in the corresponding hidden fields for each image. Then call post on each iframe now that they all have the data they need.
I have a simple setup to allow a user to change his content on a page.
It calls up a query and populates the area with the results. My goal is to have the user enter in some new information, insert that info into the table, and requery the results.
Here is my Javascript function that is called:
function addLink(){
var ajaxRequest;
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
}
}
Those PHP functions merely spit out the HTML, the displayContent() specifically for the actual table data.
Here is my HTML for adding some info to the database:
<center><br /><br />
Image URL: <input type='text' id='links_img' />
Link URL: <input type='text' id='links_link' />
<input type='button' onclick='addLink()' value='add' /></center>
Here is my PHP for adding the information:
<?php
mysql_connect([sensitive information]) or die(mysql_error());
mysql_select_db([sensitive information]) or die(mysql_error());
$result = mysql_query("INSERT INTO linksMod (Image URL, Link URL) VALUES ("$_GET['imgURL']","$_GET['linkURL']") or die(mysql_error());
mysql_close();
?>
Thee page does nothing when I click the 'Add' button.
Thanks for your help!
These lines:
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
need to be outside the "readystatechange" handler function. The way it's written now, they're inside the handler function and, since it isn't called, they'll never happen.
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
I don't think it's possible to embed php in javascript .