How to store Javascript value in php variable shown in alert - javascript

How to pass javascript variable to php variable my code is- I want to store alert value in php variable.
<script type="text/javascript" >
$(document).ready( function() {
$( '#container' ).html( '<ul class="filetree start"><li class="wait">' + 'Generating Tree...' + '<li></ul>' );
getfilelist( $('#container') , 'Sample' );
function getfilelist( cont, root ) {
$( cont ).addClass( 'wait' );
$.post( 'Foldertree.php', { dir: root }, function( data ) {
$( cont ).find( '.start' ).html( '' );
$( cont ).removeClass( 'wait' ).append( data );
if( 'Sample' == root )
$( cont ).find('UL:hidden').show();
else
$( cont ).find('UL:hidden').slideDown({ duration: 500, easing: null });
});
}
$( '#container' ).on('click', 'LI A', function() {
var entry = $(this).parent();
if( entry.hasClass('folder') ) {
if( entry.hasClass('collapsed') ) {
entry.find('UL').remove();
getfilelist( entry, escape( $(this).attr('rel') ));
entry.removeClass('collapsed').addClass('expanded');
window.alert($(this).attr('rel'))
$( '#selected_file1' ).text( "Folder: " + $(this).attr( 'rel' ));
<?php
?>
}
else {
entry.find('UL').slideUp({ duration: 500, easing: null });
entry.removeClass('expanded').addClass('collapsed');
}
} else {
$( '#selected_file' ).text( "File: " + $(this).attr( 'rel' ));
}
return false;
});
});
</script>

There is difference between Javascript and PHP, PHP is a server-side script language while Javascript is a client-side script language. See https://www.sqa.org.uk/e-learning/ClientSide01CD/page_18.htm
Use the advantage of AJAX instead for your problem

Related

How do I add a second variable value to the jQuery widget 'Autocomplete'?

I have been using the jQuery ‘Autocomplete Widget’ for a number of years now. This has always been done but passing a value with ‘term’ to the PHP SQL code like this;
$( "#cs1" ).autocomplete({
autoFocus: true,
minLength: 3,
source: "gethint.php",
select: function( event, ui ) {
// This if undes the readonly on the Fname input field below
if ( ui.item.label == 'NONHAM' ) {$('#Fname').prop('readonly', false);}
$( "#cs1" ).val( ui.item.label );
$( "#hints" ).val( ui.item.value );
$( "#Fname" ).val( ui.item.desc );
var nc = $( "#thenetcallsign" ).html();
//return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + " ---> " + item.desc + "</a>" )
.appendTo( ul );
};
});
But now I have to add another condition to the SQL code to return a more detailed value. The value for this additional condition is;
var nc = $( "#thenetcallsign" ).html();
The problem is I don’t know how to add this to ‘term’ or a separate variable and pass it to gethint.php using the ‘Autocomplete’ widget.
Once I get the extra value to the PHP program I know what to do.
Would somebody please explain or show me how to do this?
You might have to stringify it but pass the extraParams
extraParams: { type: "CoolCode" },
var nc = $("#thenetcallsign").html();
$("#cs1").autocomplete({
autoFocus: true,
minLength: 3,
source: "gethint.php",
extraParams: {
nc: nc
},
select: function(event, ui) {
// This if undes the readonly on the Fname input field below
if (ui.item.label == 'NONHAM') {
$('#Fname').prop('readonly', false);
}
$("#cs1").val(ui.item.label);
$("#hints").val(ui.item.value);
$("#Fname").val(ui.item.desc);
var nc = $("#thenetcallsign").html();
//return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + " ---> " + item.desc + "</a>")
.appendTo(ul);
};
});
source could be a function in order to get more flexibility
$( "#cs1" ).autocomplete({
/* ... */
source: function(request, response) {
$.getJSON( "gethint.php", {
term: request.term ,
nc: $( "#thenetcallsign" ).html()
}, response );
},
/* ... */
});

Send JSON Array to MySql database

I need to send array to my mysql database.
I've created a JSON array and dont know how to post it to php to transfer to db.
$( function () {
$( '#orderForm' ).on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
} );
} );
I need to post it item->item, qty->qty, price->price to the db.
I've tried :
$.ajax( {
url: 'tc_menu',
type: 'POST',
data: JSON.stringify( myData ),
success: function ( data ) {
console.log( "success:", data );
},
failure: function ( errMsg ) {
console.error( "error:", errMsg );
}
} );
Data stores whole page, but not (stringified myData). And I still cant get it at php code by $_POST and json_decode
Data stores whole page, but not stringified myData and I can't get it at php code by $_POST and json_decode
php code
`if(isset($_POST['submitted_m'])){
$myData = serialize($_POST['data']);
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
if (mysqli_query($db, $sqli)) {
$msg = "New Order added!";
echo "<script>
alert(\"$msg\");
window.location.replace('tc_menu.php');
</script>";}
else {echo "Error:".$sql."<br>".mysqli_error($db);}}`
Try this one for js
$(function () {
$('#orderForm').on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
data_to_server = JSON.stringify(myData);
});
$.post("*your_php_file*", {
data: data_to_server;
}).done(function (data_returned) {
// any your code
});
});
And seems you have mismatch in PHP code - trying to serialize() instead of json_decode()
Remove nested click event and closure.
e.g.
$( '#orderForm' ).on( 'submit', function ( event ) {
$( '#orderForm' ).on( 'submit', function ( event ) {
} );
} );
Than try again.
And your MySQL insert statement in php
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
is not ok.
Learn more about MySQL insert statement here https://www.w3schools.com/php/php_mysql_insert.asp

Accessing multiple css property

Is this method appropriate for accessing multiple css method?
<script>
$("div").click(function () {
var html = ["The clicked div has the following styles:"];
var styleProps = $(this).css( ["width", "height", "color", "background-color"] );
This is what jquery API is doing.Is above method for accessing multiple property appropriate?Or is that the way?
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
$( "#result" ).html( html.join( "<br>" ) );
});
You copied the code from the docs, mentioning it could help, anyway they show you they pulled all the data with:
var styleProps = $(this).css( ["width", "height", "color", "background-color"] );
Now they manipulate the data with:
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
Finally they output the result with a <br> between each name-value pair:
$( "#result" ).html( html.join( "<br>" ) );

how to remove selected item from the list after performing autocomplete?

I have implemented an auto complete event using Jquery, and it works fine, now I need to implement a remove or delete functionality in the list I selected.
pls see the code below.
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#poolName" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/DataWeb/getPoolName",
type : 'post',
dataType: 'json',
data: { name_startsWith: request.term },
success: function( data ) {
console.log(data);
response( $.map( data, function( item ) {
return {
label: item.poolName,
value: item.poolName
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
Ex : in the textBox if i type 'a' I get list of names starting with 'a', and I select 5 names starting with 'a'. It will be stored in "log" id.
Pool Name:
<div style="margin-top: 2em; font-family: serif; font-size: medium;"> Result:
<div> <fieldset id="log" style="height: 200px; width: 300px; overflow: auto;"> </fieldset> </div>
</div>
</div>
</form>
Now if i want to remove one of the name selected, how do i need to implement??
can anyone help??
Thanks in advance
Change your log function to:
Note: This adds a "Remove" button in front of each message, which will delete the message when clicked.
function log( message ) {
var _m = '<div style="float:left;">' + message + '</div>';
_m += '<div style="float:right;"><input type="submit" value="Remove"></div>';
_m += '<div style="clear:both;"></div>';
$( "<div>" ).html( _m ).prependTo( "#log" ).click(function(o){
$(this).remove();
});
$( "#log" ).scrollTop( 0 );
}
Hope this helps.

jquery autocomplete combobox error: Uncaught TypeError: Object [object Object] has no method 'button'

i am trying to implement an autocomplete combobox using jquery ui plugin.
with the below mentioned code i am able to achieve the autocomplete part but not the dropdown part (due to the uncaught typeerror the dropdown arrow is not visible)
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default ui-combobox-input" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
},
destroy: function() {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call( this );
}
});
$( "#combobox" ).combobox();
The above code is under document.ready.
The error is thrown due to '.button' method.
The html:
<tr>
<td><label>Country:</label></td>
<td>
<div class="ui-widget">
<select id="combobox">
<option value="">Select one...</option>
<option value="ActionScript">ActionScript</option>
<option value="AppleScript">AppleScript</option>
<option value="Asp">Asp</option>
<option value="BASIC">BASIC</option>
<option value="C">C</option>
</select>
</div>
</td>
</tr>
combobox css,
.ui-combobox {
position: relative;
display: inline-block;
}
.ui-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
/* adjust styles for IE 6/7 */
*height: 1.7em;
*top: 0.1em;
}
.ui-combobox-input {
margin: 0;
padding: 0.3em;
}
The script sequence is,
<script type="text/javascript" src="<?php echo base_url('/assets/js/jquery.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('/assets/js/validation.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('/assets/autocomplete/js/jquery-ui-1.8.21.custom.min.js'); ?>"></script>
<?= $_scripts ?>
jquery version 1.7.2, jquery ui version 1.8.21
i have tried rearranging the sequence of the scripts
there are no multiple instances of different jquery versions.
Any help would be appreciated. Thanks!
Your code looks fine so the problem is almost certainly that you didn't include ui.button in your custom jQuery UI build.
You can verify this by running typeof $.ui.button. If you have it included it will be function, if you do not it will be undefined.
Re-build jQuery UI and make sure to select the Button checkbox.

Categories

Resources