I have a jquery file that dynamically creates input elements. One of the elements is for uploading an image file. When the user clicks save it will add it to a database via ajax. I want the ability to be able to upload on the same save click. I am not able to get the file element to submit.
Below is my jquery:
var trcopy;
var editing = 0;
var tdediting = 0;
var editingtrid = 0;
var editingtdcol = 0;
var inputs = ':checked,:selected,:text,textarea,select,:hidden,:checkbox,:file';
var notHidden = ':checked,:selected,:text,textarea,select,:file';
$(document).ready(function(){
// set images for edit and delete
$(".eimage").attr("src",editImage);
$(".dimage").attr("src",deleteImage);
// init table
blankrow = '<tr valign="top" class="inputform"><td></td>';
for(i=0;i<columns.length;i++){
// Create input element as per the definition
//First elements in array are hidden fields
if(columns[i] == '_fk_PO_Req_ID'){
input = createInput(i,'');
blankrow += input;
}else{
input = createInput(i,'');
blankrow += '<td class="ajaxReq" style="text- align:center;">'+input+'</td>';
}
}
blankrow += '<td><img src="'+saveImage+'"></td></tr>';
// append blank row at the end of table
$("."+table).append(blankrow);
// Add new record
$("."+savebutton).on("click",function(){
// alert('save clicked');
var validation = 0;
var $inputs =
$(document).find("."+table).find(inputs).filter(function() {
// check if input element is blank ??
//if($.trim( this.value ) == ""){
// $(this).addClass("error");
// validation = 0;
// }else{
// $(this).addClass("success");
// }
validation = 1;
return $.trim( this.value );
});
var array = $inputs.map(function(){
console.log(this.value);
console.log(this);
return this.value;
}).get();
var serialized = $inputs.serialize();
alert(serialized);
if(validation == 1){
ajax(serialized,"save");
}
});
createInput = function(i,str){
str = typeof str !== 'undefined' ? str : null;
//alert(str);
if(inputType[i] == "text"){
input = '<input class="input-small" type='+inputType[i]+' name="'+columns[i]+'" placeholder="'+placeholder[i]+'" value="'+str+'" >';
}else if(inputType[i] == "file"){
input = '<input class="input-small" type='+inputType[i]+' name="new_receipt" placeholder="'+placeholder[i]+'" value="'+str+'" >';
}else if(inputType[i] == "textarea"){
input = '<textarea name="'+columns[i]+'" placeholder="'+placeholder[i]+'">'+str+'</textarea>';
}else if(inputType[i] == "hidden"){
input = '<input type="'+inputType[i]+'" name="'+columns[i]+'" value="'+hiddenVal[i]+'" >';
}else if(inputType[i] == "checkbox"){
input = '<input type="'+inputType[i]+'" name="'+columns[i]+'" value="'+str+'" >';
}else if(inputType[i] == "select"){
input = '<select class="input-medium" name="'+columns[i]+'">';
for(i=0;i<selectOpt.length;i++){
// console.log(selectOpt[i]);
selected = "";
if(str == selectOpt[i])
selected = "selected";
input += '<option value="'+selectOpt[i]+'" '+selected+'>'+selectOpt[i]+'</option>';
}
input += '</select>';
}
return input;
}
ajax = function (params,action){
// alert(params);
// alert(action);
$.ajax({
type: "POST",
url: "ajax.php",
data : params+"&action="+action,
dataType: "json",
success: function(response){
switch(action){
case "save":
var seclastRow = $("."+table+" tr").length;
// alert(response.success);
if(response.success == 1){
var html = "";
html += "<td>"+parseInt(seclastRow - 1)+"</td>";
for(i=0;i<columns.length;i++){
if(columns[i] == '_fk_PO_Req_ID'){
html += '';
}else{
html +='<td style="text-align:center" class="'+columns[i]+'">'+response[columns[i]]+'</td>';
}
}
html += '<td><img src="'+editImage+'"> <img src="'+deleteImage+'"></td>';
// Append new row as a second last row of a table
$("."+table+" tr").last().before('<tr id="'+response.id+'">'+html+'</tr>');
if(effect == "slide"){
// Little hack to animate TR element smoothly, wrap it in div and replace then again replace with td and tr's ;)
$("."+table+" tr:nth-child("+seclastRow+")").find('td')
.wrapInner('<div style="display: none;" />')
.parent()
.find('td > div')
.slideDown(700, function(){
var $set = $(this);
$set.replaceWith($set.contents());
});
}
else if(effect == "flash"){
$("."+table+" tr:nth-child("+seclastRow+")").effect("highlight",{color: '#acfdaa'},100);
}else
$("."+table+" tr:nth-child("+seclastRow+")").effect("highlight",{color: '#acfdaa'},1000);
// Blank input fields
$(document).find("."+table).find(inputs).filter(function() {
// check if input element is blank ??
this.value = "";
$(this).removeClass("success").removeClass("error");
});
}
break;
}
},
error: function(){
alert("Unexpected error, Please try again");
}
});
}
You cannot upload a file like a regular form field when you use ajax.
There are two solutions for that:
Use FormData. This will work in modern browswers;
Use a jQuery file upload plugin. This is only necessary if you need to support browsers that do not support FormData: Internet Explorer 9 and below.
You can find a nice explanation of the use of FormData here on SO: How to use FormData for ajax file upload
this is my php code:
if (($_SERVER["REQUEST_METHOD"] == "POST")&&(isset($_POST["btn_save"]))) {
$schoolsInput=$_POST['schoolsInput'];
echo $schoolsInput[0];
}
this is my jquery code:
<script type="text/javascript">
$(document).ready(function()
{
var counter=1;
var max_fields=5;
var add_button = $("#btn_addTxt");
var save_btn= $("#btn_save");
var wrapper= $("#prevSchoolTable");
$(add_button).click(function(e){
e.preventDefault();
if (counter == max_fields) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
$(wrapper).append('<tr><td><input type="text" name="schoolsInput' + counter + '" id="schoolsInput' + counter + '" class="textbox" style="width:400px;">'
+ '</td></tr>');
counter++;
}
});
var arrayFromPHP = <?php echo json_encode($schoolsInput); ?>;
$("#btn_save").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n " + $('#schoolsInput' + i).val();
}
alert(msg); \\array push must go here
});
});
</script>
I've search how can i access PHP variable and they say to use:
var obj = <?php echo json_encode($schoolsInput); ?>;
But everytime i put this on my jquery, the ADD function is not working.
any suggestion?
I have created several image buttons in php. I have assigned a common class to all of them. When I call a jquery function based on button class name click. This works fine but when I try calling an ajax function it doesn't work. There is no error seen.
PHP to create a button
function printpic($name, $picpath, $category, $pic)
{
$style = " margin=0px; background-color=transparent; border=none;";
//$functionname= "selectedpic(this.id)";
$functionname= "myCall(this.id);";
$styleimage = "HEIGHT= 120 WIDTH= 120 BORDER=0";
$eventimage1= "zoomin(this)";
$eventimage2= "zoomout(this)";
$btnclass="btnclass";
$j=0;
$spa=0;
$i=0;
for($k=0; $k<4; $k++)
{
echo "<tr>";
for($j=0; $j<4; $j++)
{
echo"<td>";
$btn= "btn".$category[$i];
echo "<span id='" . $spa. "'>";
echo "<button name='" . $btn. "'
margin ='".$style."'
class='".$btnclass."'
onClick='".$functionname."'
>";
echo "<img src='". $picpath[$i]."/".$name[$i]."'
id ='".$pic[$i]."'
alt ='".$name[$i]."'
.$styleimage.
onMouseMove='".$eventimage1."'
onMouseOut='".$eventimage2."'
>";
echo "</button >";
$spa++;
echo"</span>";
echo"</td>";
$i++;
} // wfor
echo "</tr>";
}// for
} // end function
?>
Jquery + Ajax
$(document).ready(function(e) {
$('.btnclass').click(function() {
event = event || window.event;
var target = event.target || event.srcElement;
var id = target.id;
var but = document.getElementById(id).parentNode.name;
var datastring = '&id='+ id;
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
success: function(responseText) { // get the response
if(responseText == 1) { alert ("hi");}
else { alert (datastring); }
} // end success
}); // ajax end
});
});
indexverification.php
<?php
session_start();
$picno=$_SESSION['picno']; // picno from db
$answer=$_SESSION['answer']; // answer from db
$id=$_POST['id']; // id of picture clicked
$ans=$_SESSION['ans']; // answer type
if (($id==$picno) && ($answer==$ans))
{
echo '1';
}
else
{
echo '2';
}
?>
I think you use the wrong syntax. Try this:
//AJAX request
$.ajax({
url: "indexverification.php",
type: "POST",
data: datastring,
})
//Success action
.success(function( html ) {
if(responseText == 1) { alert ("hi");}
else { alert (datastring); };
})
//Error action
.fail(function() {
alert("Request failed.");
});
I have a list on my site that has a favorites button associated with each item on the list. I am using an image as the button to click. The PHP for it is:
echo "<img src=\"./images/emptystar.png\" alt=\"favorite\" class=\"favoritebutton\" billid=\"" . $count['id'] ."\" userid=\"". $_SESSION['userid'] ."\" />\n";
I have javascript/jQuery to make an onclick of that image submit an AJAX request to a PHP file.
$(document).ready(function() {
$(".favoritebutton").click(function () {
var billid = $(this).attr("billid");
var userid = $(this).attr("userid");
var ajaxrequest;
var params = "billid=" + billid + "&userid=" + userid;
ajaxrequest.open("POST","./ajaxphp/favorites.php",true);
ajaxrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxrequest.setRequestHeader("Content-length", params.length);
ajaxrequest.setRequestHeader("Connection", "close");
ajaxrequest.send(params);
ajaxrequest.onreadystatechange=function()
{
if (ajaxrequest.readyState===4 && ajaxrequest.status===200)
{
if(ajaxrequest.responseText === "true")
{
if($(this).attr("src") === "./images/emptystar.png")
{
$(this).attr("src","./images/fullstar.png");
}
else
{
$(this).attr("src","./images/emptystar.png");
}
}
}
};
});
});
The php file at ./ajaxphp/favorites.php is the following:
<?php
include("./includes/dbcxnfunction.inc");
$billid = $_POST['billid'];
$userid = $_POST['userid'];
$query = "IF NOT EXISTS (SELECT * FROM favoritebills WHERE userid = '$userid' AND billid = '$billid' )
INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid)
ELSE
DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid' ";
$result = mysqli_query(dbcxn('bill'),$query)
or exit("Couldn't execute query for favorites");
if($result)
{
$request = "true";
}
else
{
$request = "false";
}
echo $request;
?>
In particular I am concerned with the SQL query and the javascript because I am not certain of their correctness, but I used a validator for the javascript with JQuery and everything is valid.
When I click the image on the page, nothing happens even though I have tested both conditions for the image change. Either the javascript is written incorrectly, or there is never a response sent back from the favorites.php file.
The network tab in console.
Use JQuery's .ajax and pass the clicked element by storing it in var before you make the ajax call
$(".favoritebutton").click(function () {
//Store $(this) in var so that it can be passed inside the success function
var this$ = $(this);
var billid = this$.attr("billid");
var userid = this$.attr("userid");
$.ajax( { url : "./ajaxphp/favorites.php", type: 'post', data : { billid : billid , userid : userid },
success : function( responseText ){
if( responseText == "true"){
if( this$.attr("src") == "./images/emptystar.png"){
this$.attr("src","./images/fullstar.png");
}else{
this$.attr("src","./images/emptystar.png");
}
}
},
error : function( e ){
alert( ' Error : ' + e );
}
});
});
I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);