I have a script in which I need to process a file using ajax. Everything in the script works, except I can not get the right variable. I have tried everything and I currently have this in its place
title = "<?php echo $_FILES["file"]["name"] ?>";
I was wondering if anyone could tell me how to successfully set whatever is in this field
<label for="file">Thumbnail Pic:</label>
</td>
<td>
<input type="file" name="thumbnail" id="thumbnail" />
As a variable in the ajax script that I have. All help is extremely appreciated, thanks for the help!
<script language='javascript' type='text/javascript'>
function ajaxupload(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try{
ajaxRequest = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e){
// Something went wrong
alert('Your browser broke!');
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('response');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var songtitle = document.getElementById('songtitle').value;
var thumbnail = document.getElementById('thumbnail').value;
var name = document.getElementById('file').value;
var title = "<?php echo $_FILES["file"]["name"] ?>";
var description = document.getElementById('description').value;
var params= 'songtitle=' + songtitle + '&thumbnail=' + thumbnail + '&title=' + title + '&description=' + description + '&name=' + name;
ajaxRequest.open("POST", 'ajaxupload.php', true);
ajaxRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajaxRequest.send(params);
}
</script>
<div id="centered2">
<h1>Music Upload</h1>
<div id="centered">
<table>
<tr>
<td>
<h4><br><?php
echo $echovar10;
echo $echovar20;
echo $echovar40;
echo $echovar50;
echo $echovar60;
echo $echovar120;
echo $echvoar130;
?><div id='response'></h4>
<table>
<tr>
<td>
<label for="file">Choose a song:</label>
</td>
<td>
<input type="file" name="file" id="file"/>
</td>
</tr>
<br />
<tr>
<td>
<label for="file">Thumbnail Pic:</label>
</td>
<td>
<input type="file" name="thumbnail" id="thumbnail" />
<br />
</td>
</tr>
I would really recommend you use jQuery. It'll make your life alot easier. Here's the ajax function documentation. jQuery also provides some wonderfully simple wrapper functions for get and post methods. Google hosts the code (minified) which is convenient.
$.post(
'ajaxupload.php', // url
$("#form_id").serialize(), // data
function(data) { // return function on success
alert(data);
}
);
But as for the real reason you are here, looks like a simple typo.
title = "<?php echo $_FILES['thumbnail']['name'] ?>";
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I have a form in which i use to insert data using ajax and php
I have gotten it to work the way i want but i wanted to make some adjustments to it, below is what i am trying to say
Initially
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!--AJAX-->
<script>
$(document).ready(function() {
<!--#my-form grabs the form id-->
$("#<?php echo $row_trx['jobid']; ?>").submit(function(e) {
e.preventDefault();
$.ajax( {
<!--insert.php calls the PHP file-->
url: "in.php",
method: "post",
data : { name: "<?php echo $row_user['Username'];?>" , jobid: "<?php echo $row_trx['jobid']; ?>" },
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$("#<?php echo $row_trx['jobid']; ?>")[0].reset();
}
});
});
});
</script>
<form id="<?php echo $row_trx['jobid']; ?>" name="<?php echo $row_trx['jobid']; ?>" id="form<?php echo $row_trx['jobid']; ?>" action="" method="post">
<button type="submit" id ="<?php echo $row_trx['jobid']; ?>">Add as favourite</button>
</form>
which works when the button is loaded on the page by default,
Adjustments i wanted to make was to display using ajax for some reason using below in the div with id='ajaxDiv'
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
setInterval(ajaxFunction<?php echo $row_trx['jobid']; ?>, 1000);
function ajaxFunction<?php echo $row_trx['jobid']; ?>(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay<?php echo $row_trx['jobid']; ?> = document.getElementById('ajaxDiv<?php echo $row_trx['jobid']; ?>');
ajaxDisplay<?php echo $row_trx['jobid']; ?>.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age<?php echo $row_trx['jobid']; ?>').value;
var wpm = document.getElementById('wpm<?php echo $row_trx['jobid']; ?>').value;
var queryString = "?age=" + age + "&wpm=" + wpm;
ajaxRequest.open("GET", "favourite.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form style="font-size: 1px;" name='myForm<?php echo $row_trx['jobid']; ?>'>
<input type='hidden' value="<?php echo $row_user['Username'];?>" id='age<?php echo $row_trx['jobid']; ?>' /> <br />
<input type='hidden' value="<?php echo $row_trx['jobid']; ?>" id='wpm<?php echo $row_trx['jobid']; ?>' />
<br />
</form>
<div id='ajaxDiv<?php echo $row_trx['jobid']; ?>'></div>
the button submit my data wen i try to display in the div via ajax, please i need help on this
Use jquery on :
$("body").on("submit", "#<?php echo $row_trx['jobid']; ?>", function(e) { ...
I don't like you selectors btw you can always set class for the form, for example something like this :
<form class="my_form"><input name="id" value="1" />...Some code here ..</form>
<form class="my_form"><input name="id" value="2" />...Some code here ..</form>
<form class="my_form"><input name="id" value="3" />...Some code here ..</form>
and lose the php in the javascript, like this:
$("body").on("submit", ".my_form", function(e) { ....
In a module of my PHP application, there are multiple forms, generated with unique id's and names by server side as "formToProcess1, formToProcess2, ... , fromToProcessN". However, there are two ajax functions that handles the request of each form, which both of them gets form name in string as argument, like following:
function ajaxReject(formToProcess)
{
var ajaxRequest;
//document.getElementById('divUploadResultAjax').style.display = 'none';
try
{
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e)
{
alert('Something is wrong with your browser, AJAX not working!');
return false;
}
}
}
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
var ajaxDisplay = document.getElementById('divUploadResultAjax');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
//document.getElementById('loadingAjaxIcon').style.display = 'none';
document.getElementById('divUploadResultAjax').style.display = 'block';
}
}
var updName = document.forms['formToProcess'].getElementById('userName').value;
//i'll get other elements values for query string to send if i can get this one first :)
var queryString = '?name=' + updName + '&lastname=' + updLastname + '&bio=' + updBio + '&country=' + updCountry + '&cams=' + updCams + '&fb=' + updFacebook + '&twitter=' + updTwitter + '&processRequest=' + RequestProcess;
alert (queryString);
return;
ajaxRequest.open('GET', 'dashboardUpdateProfile.php' + queryString, true);
ajaxRequest.send(null);
}
#Every form in the php page is generated like following:
echo '
<div id="divUploadResultAjax">
<form name="profileUpdater'. $formCounter .'">
<input type="hidden" id="uluid" name="uluid" value="'.$UL_UploadID.'" />
<table class="tg" style="width: 100%">
<tr>
<td style="font-weight: bold; width: 250px; color: #000000;" colspan="3">
<h3>Upload ID #'.$UL_UploadID.' </h3> (Uploaded On '.$NewCreateDate.')
</td>
...
...
bla bla bla
...
...
----> this is where i call functions in each form.
<input type="button" class="btnRegister" name="updateProfile" onclick="ajaxReject(\'profileUpdater'. $formCounter .'\')" value="Reject" />
<input type="button" class="btnRegister" name="updateProfile" onclick="ajaxApprove()" value="Approve" />
I'm not really sure what is wrong. When i call the function with button click, it works perfectly until end of if(ajaxRequest.readyState == 4), after that, when i'm trying to get the var updName = document.forms['formToProcess'].getElementById('userName').value; function crashes. What i'm doing wrong?
Thanks.
Can't you use something like var updName = document.getElementById('userName').value;.
I don't find username element in the form? Is it there in your actual code?
I am a newbie in web base applications development and Im learning AJAX. Here is my problem, I'm trying to make an AJAX request with some variables (user inputs) and get the php file with the same variables. Below is my code, if there something I am missing or I am doing wrong please let me know, I will appreciated any help! Thank you.
Javascript code:
<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
document.getElementById("Alert").innerHTML= "*Your browser broke!";
document.getElementById("Alert").style.color = '#E00000 ';
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('display');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
var input_building = document.getElementById('building').value;
var input_room = document.getElementById('room').value;
var queryString = "?building=" + input_building + "&room=" + input_room;
ajaxRequest.open("GET", "map.php" + queryString, true);
ajaxRequest.send();
}
</script>
HTML:
<select id="building" name="building">
<option value="#" default >Select</option>
<option value="Luis C. Monzon">Luis C. Monzon</option>
</select>
<input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" >
<input id="submit" type="button" value="submit" onclick="ajaxFunction()" >
<p id="display"></p>
PHP file:
<?php>
$building = $_GET['building'];
$room = $_GET['room'];
echo "<h1>".$room." ".$building."</h1>";
?>
You are setting a value property on a <p> element. You should be setting its innerHTML. Value is used for input fields.
document.getElementById('display').innerHTML = ajaxRequest.responseText;
As requested, I will post my comment
In your code you need to change ajaxDisplay.value to ajaxDisplay.innerHTML - as elaborated by Juan, form fields have values and container tags have innerHTML.
To defend the use of jQuery a little - I basically agree that for simple JavaScript, loading an external library can be overkill - in the case of Ajax, I trust jQuery to cover all browsers needs.
Your code with jQuery:
<!DOCTYPE html>
<html>
<head>
<title>Get building</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() { // run onload
$("ajaxbutton").on("click",function() {
var input_building = $('building').val();
var input_room = $('room').val();
var queryString = "?building=" + input_building + "&room=" + input_room;
$("#display").load("map.php" + queryString); // get the room
});
});
</script>
</head>
<body>
<select id="building" name="building">
<option value="#" default >Select</option>
<option value="Luis C. Monzon">Luis C. Monzon</option>
</select>
<input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" />
<input id="ajaxbutton" type="button" value="Find Building" />
<p id="display"></p>
</body>
</html>
NOTE: for more control over the result you can change the load to
$.get("map.php" + queryString,function(data) {
// do something with data here - for example if you use JSON
$("#display").html(data);
});
How to send looping data from html page to php page using ajax. I am trying so hard but i don't get any way passing looping data into php page.
order.html page code are described in the below:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age[]').value;
var queryString = "?age=" + age ;
ajaxRequest.open("GET", "example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='age[]' Name='age[]' /> <br />
Name: <input type='text' id='age[]' Name='age[]'/>
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>result will display here</div>
</body>
</html>
example.php page code are described in the below:
<?php
$len = count($_GET['age']);
for($x=0;$x<$len;$x++)
{
echo $service[$x]=$_GET['age'][$x];
}
?>
the [] should be append to the query string, not to the input name
var queryString = "?age[]=" + age1 + "&age[]=" + age2 + "&age[]=" + age3 ;
ajaxRequest.open("GET", "example.php" + queryString, true);
I have, with the help of the SO community written a javascript and php page that allows me to pass a value from the popup page back to the parent page.
This works 100% on internet explorer but not in google chrome or on my ipad / galaxt tablet.
Any idea on how this can be corrected? Any help appreciated as always.
Below is portions of my code from the parent page(newsale.php) and the popup page(sku.php). I know that other methods are recommended over using popup but I need to get this solution working with the popup page for application reasons.
newsale.php Parent Page (Code snippets, not entire page)
<script type="text/javascript">
function selectValue(id)
{
// open popup window and pass field id
window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
'width=1000,toolbar=1,resizable=1,scrollbars=yes,height=200,top=100,left=100');
}
function updateValue(id, value)
{
// this gets called from the popup window and updates the field with a new value
document.getElementById(id).value = value;
}
</script>
<table>
<tr id="r1">
<input size=10 type=number id=sku1 name=sku1 onchange="showUser(1, this.value)" <? if($rows>0){echo "value=".mysql_result($resultorder,0,1);} ?>><img src=q.png name="choice" onClick="selectValue('sku1')" value="?">
</td>
</tr>
<tr id="r2">
<td>
<input size=10 type=number id=sku2 name=sku2 onchange="showUser(2, this.value)" <? if($rows>1){echo "value=".mysql_result($resultorder,1,1);} ?> ><img src=q.png name="choice" onClick="selectValue('sku2')" value="?">
</td>
</tr>
</table>
sku.php Popup Page (entire page)
<?
$con = mysql_connect('localhost', 'username', 'password');
if (!$con)
{
die('Could not connect to server: ' . mysql_error());
}
$db=mysql_select_db("DBName", $con);
if (!$db)
{
die('Could not connect to DB: ' . mysql_error());
}
$sql="select packcode,category,description,grouping,packconfig,sellingunits,eottpoints from skudata order by category, packcode";
$result=mysql_query($sql);
?>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<script type="text/javascript">
function sendValue(value)
{
var e = document.getElementById("subcat");
value = e.options[e.selectedIndex].value;
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<script type="text/javascript">
function updateinput(){
var e = document.getElementById("subcat");
var catSelected = e.options[e.selectedIndex].value;
document.getElementById("copycat").value=catSelected;
}
</script>
<form name="testform">
Category: <select name=cat id=cat onchange="AjaxFunction(this.value);" style="width=300"> <br>
<option value='' style="width=300">Select One</option>
<br>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<br><br>
Pack Code:
<select name=subcat onchange="updateinput();" >
<br><br>
</select>
<br><br>
<input type=hidden name=copycat id=copycat >
<td><input type=button value="Select" onClick="sendValue(document.getElementById(copycat))" /></td>
</form>
dd.php (for dynamic drop down list)
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select concat(packcode,', ',description) as details from skudata where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . "\"$nt[details]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>
I dont think dd.php has any influence on the functionality of the parent popup relationship but have included it so you can follow the code.
As mentioned this works 100% on Internet explorer but not in google chrome or my ipad.
When you use
document.getElementById("subcat");
then you should also have an element with such an id. Your
<select name=subcat onchange="updateinput();" >
won't do with browsers like chrome, firefox, konqueror and probably lots of others. Use
<select id="subcat" onchange="updateinput();" >
instead.
Unfortunately, I can't get your code to work so I can't test this, but changing
window.opener.updateValue(parentId, value);
to
window.opener.contentWindow.updateValue(parentId, value);
or
window.opener.window.updateValue(parentId, value);
may solve this.
If it doesn't, maybe you can post the errors that are showing from the Chrome console and explain better what exactly doesn't work.
In below function also,you called for subcat.
function sendValue(value)
{
var e = document.getElementById("subcat");
}
along with one mentioned by Themroc.
You should first have an id="subcat".
Still you getting some problem , post the error.
Thanks.