I am having great difficulty passing a variable from a PHP file to .js files
The code in the PHP file I used is this:
<script>
jQuery(document).ready(function(){
var uid = <?php echo (intval($uid)); ?>;
//var uid = <?php echo(intval($_SESSION['uid'])); ?>.val();
});
</script>
The variable value should be passed into the .js file to refresh just a certain div on the page (not the whole page) after a form submission is performed.
This is the .js file and the corresponding code starts at "// refresh the monitor list div":
$(function() {
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var domain = $("input#domain").val();
if (domain == "") {
$("label#domain_error").show();
$("input#domain").focus();
return false;
}
var com_domain = $("input#com_domain").val();
if (com_domain == "") {
$("label#com_domain_error").show();
$("input#com_domain").focus();
return false;
}
var cemail = $("input#cemail").val();
var port = $("select#port").val();
var active = $("input#active").val();
var uid = $("input#uid").val();
var main = $("select#main").val();
var dataString = 'cemail='+ cemail + '&domain=' + domain + '&com_domain=' + com_domain + '&active=' + active + '&main=' + main + '&port=' + port;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "user_add.php",
data: dataString,
success: function() {
$('#monitor_form').append("<div id='message'></div>");
$('#monitor_form form')[0].reset();
$('#message').html("<img id='checkmark' src='images/tick.png' /><b> Monitor sucessfully added!</b>")
.hide()
.fadeIn(500, function() {
$('#message').append("");
});
setTimeout("$('#message').hide().remove();", 6000);
var dataString2 = 'ajax=1&uid=' + uid;
$.ajax({
type: "GET",
url: "monpanel.php",
data: dataString2,
success: function(html_data){
$('#list_monitors').html(html_data);
}
});
//document.onkeydown = showDown;
}
});
return false;
});
});
function showDown(evt) {
event = (evt)? evt : ((event)? event : null);
if (evt) {
if (event.keyCode == 8 && (event.srcElement.type!= "text" && event.srcElement.type!= "textarea" && event.srcElement.type!= "password")) {
// When backspace is pressed but not in form element
cancelKey(evt);
}
else if (event.keyCode == 116) {
// When F5 is pressed
cancelKey(evt);
}
else if (event.keyCode == 122) {
// When F11 is pressed
cancelKey(evt);
}
else if (event.ctrlKey && (event.keyCode == 78 || event.keyCode == 82)) {
// When ctrl is pressed with R or N
cancelKey(evt);
}
else if (event.altKey && event.keyCode==37 ) {
// stop Alt left cursor
return false;
}
}
}
function cancelKey(evt) {
if (evt.preventDefault) {
evt.preventDefault();
return false;
}
else {
evt.keyCode = 0;
evt.returnValue = false;
}
}
/*function mycallbackfunc(v,m,f) {
if (v == 'Cancel') {
$.prompt('The action was ' + v + 'ed');
}
else {
$.prompt('Monitor ' + v + 'd successfully');
}
}*/
// ask for validation on monitor delete, pause, resume request
$(document).ready(function(){
$(".error").hide();
alert("Stage 0! -> uid="+uid.toString());
$("#mondelpau").validate({
debug: false,
rules: {
act: "required",
uid: "required",
sid: "required"
},
/*messages: {
name: "Please let us know who you are.",
email: "A valid email will help us get in touch with you.",
},*/
submitHandler: function(form) {
// do other stuff for a valid form
//$.post('delpaures.php', $("#mondelpau").serialize(),
alert("Stage 1! -> uid="+uid.toString());
$.ajax({
async: false,
type: "POST",
url: "delpaures.php",
data: $("#mondelpau").serialize(),
success: function(data) {
$('#monadiv').html(data);
//$('#results').html(data);
//alert (data);return false;
// refresh the monitor list div
//$('#list_monitors').load(dataString8);
//var uid = $("input#uid").val();
//var dataString8 = 'ajax=1&uid=' + $("input#uid").val();
var dataString8 = 'ajax=1&uid=' + uid; // .val()
//var dataString8 = 'ajax=1&uid=19';
alert("Stage 2! -> uid="+uid.toString());
$.ajax({
async: false,
type: "GET",
dataType: "html",
url: "monpanel.php",
data: dataString8,
success: function(html_data){
alert("Stage 3!");
$("#list_monitors").css("background-color","#FF0000");
$("#list_monitors").html(html_data);
}
});
}
});
}
});
});
Needless to say I have tried everything, even renaming .js file to .php and redirecting to them with .htaccess, but that doesn't work either.
The reason you cannot access the variable in your js file is that the variable 'uid' is defined in a different scope than the js file. Its the same thing as:
if(true) {
var a = 1;
}
if(true) {
// b will be undefined since 'a' was defined in another scope
var b = a;
}
// so
jQuery(document).ready(function({
// this is one scope
var a = 1;
});
jQuery(document).ready(function({
// this is another scope and b will be undefined
var b = a;
});
You need to store the uid in a hidden field like:
<intput type="hidden" id="hidUid" value="<?php echo (intval($uid)); ?>"/>
And then inside the scope of your javascript ($(document).ready)
var uid = $("#hidUid").val();
Related
I want to handle two operations when I click the enter key after entering text in one textbox.
Two operations are
Move the cursor to the next textbox
Establish a serial communication using php code
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) { // Enter key is pressed
e.preventDefault(); // Prevent the default behaviour of enter key
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
// Ajax query to send request to php
var test = $("#command-text").val();
var inputtext = test;
var command = "1";
// var mode = $(".common-input mb-20").val();
$.ajax({
type: "POST",
url: "controller.php",
data: {
inputtext: inputtext,
command: command
},
cache: false,
success: function(html) {
var feedback = "#" + $("#command-text").val() + "#";
$("#feedback").val(feedback);
}
});
}
});
});
When I tried out with the following code,only one operation is executing,either cursor will move to the next textbox or establish communication.
Kindly help me to solve this issue
Code I tried is as below
You are using incorrect syntax your position of brackets is not correct try this:
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) { // Enter key is pressed
e.preventDefault(); // Prevent the default behaviour of enter key
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
// Ajax query to send request to php
var test = $("#command-text").val();
var inputtext = test;
var command = "1";
// var mode = $(".common-input mb-20").val();
$.ajax({
type: "POST",
url: "controller.php",
data: {
inputtext: inputtext,
command: command
},
cache: false,
success: function(html) {
var feedback = "#" + $("#command-text").val() + "#";
$("#feedback").val(feedback);
}
});
}
});
});
i am working on search form with autocomplete function. my autocomplete is working fine. i want to send the data to another php page after autocomplete value is set.
below is my jquery for autocompleate.
function autocomplet() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#searchitem').val();
var search_location = $('#search_location').val();
var datastring= 'keyword='+ keyword + '&search_location='+search_location;
if (keyword.length >= min_length) {
$.ajax({
url: 'global_search.php',
type: 'POST',
data: datastring,
success:function(data){
$('#search_list_id').show();
$('#search_list_id').html(data);
}
});
} else {
$('#search_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#searchitem').val(item);
window.location.href = 'searchtestr.php?key=' + data
// hide proposition list
$('#search_list_id').hide();
}
i tried window.location.href = 'searchtestr.php?key=' + data to redirect the page but its not working. the condition is the page should be redirect after some thing is selected from autocomplete.
You need to call your set_item method in your success handler:
success:function(data){
$('#search_list_id').show();
$('#search_list_id').html(data);
set_item(data.item); //data.something
}
Also, you are trying to pass a variable called data to the next page but the set_item method doesn't have access to that variable. You'd have to send item e.g. window.location.href = 'searchtestr.php?key=' + item;
Also, I'm not sure if you are doing something with a SPA (guessing not)... I don't think it makes sense to modify the DOM after you redirect the page - e.g. $('#search_list_id').hide(); and $('#searchitem').val(item);. You are aware thatwindow.location.href is not triggering an AJAX call and will redirect the entire page?
try this
function autocomplet() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#searchitem').val();
var search_location = $('#search_location').val();
var datastring= 'keyword='+ keyword + '&search_location='+search_location;
if (keyword.length >= min_length) {
$.ajax({
url: 'global_search.php',
type: 'POST',
data: datastring,
success:function(data){
$('#search_list_id').show();
$('#search_list_id').html(data);
},
change: function (event, ui) {
if (ui.item == null || ui.item == undefined) {
} else {
window.location.href = 'searchtestr.php?key=' + data;
}
});
} else {
$('#search_list_id').hide();
}
}
i tried like below and it worked. my concern is after value is set then redirect to php page.
function autocomplet() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#searchitem').val();
var search_location = $('#search_location').val();
var datastring= 'keyword='+ keyword + '&search_location='+search_location;
if (keyword.length >= min_length) {
$.ajax({
url: 'global_search.php',
type: 'POST',
data: datastring,
success:function(data){
$('#search_list_id').show();
$('#search_list_id').html(data);
}
});
} else {
$('#search_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#searchitem').val(item);
// hide proposition list
$('#search_list_id').hide();
var location = $('#search_location').val();
var search_term = $('#searchitem').val();
if(search_term != ''){
window.location.href = 'searchtestr.php?location=' + location + '&search_term='+ search_term;
}
}
Thank You all for helping me.
Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }
I have an Jquery submit textarea, now I want to set textarea submit without button submit. Just using enter key.
<textarea id="ctextarea"></textarea>
Here it's the JS :
$('.comment_button').live("click",function()
{
var ID = $(this).attr("id");
var uid = $("#uid").val();
var comment= $("#ctextarea"+ID).val();
var dataString = 'comment='+ comment + '&msg_id=' + ID + '&uid=' + uid;
if(comment=='')
{
$('#ctextarea').html("").fadeIn('slow');
$("#ctextarea"+ID).focus();
}
else if (!$.trim($("#ctextarea"+ID).val()))
{
$("#ctextarea"+ID).focus();
}
else
{
$.ajax({
type: "POST",
url: "comment_ajax.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append(html);
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});
I already search the tutorials and found, but I confused where can I put the code in My JS code.
Someone can give the idea ?
Thanks for helps.
$('#ctextarea').on('keyup', function(e){
if(e.which == 13 || e.keyCode == 13){
//enter key pressed..
}
});
You can subscribe to a keydown/keyup event and submit the form inside the event handler:
var KEY_ENTER = 13;
$('#ctextarea').keyup(function (event) {
if (event.keyCode === KEY_ENTER) {
$('form').submit();
// Or perform any necessary ajax calls here
}
});
I am developing a contact form that is submitted via the ajax command, the data is sent to a php file where it is processed and a json object is returned but i am having some trouble getting the json object back to into the ajax command as it keeps returning null, the code i am using is as follows...
$("#send").click(function () {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function () {
if ($(this).val()) {
$(this).css("background", "#ffffff").css("color", "#111111");
} else {
$(this).css("background", "#d02624").css("color", "#ffffff");
complete = false;
}
});
if (complete == true) {
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"' + name + '","sender":"' + email + '","subject":"' + subject + '","message":"' + message + '"}';
$.ajax({
type: "POST",
url: "contact.php",
data: "token=" + $.base64.encode(data),
dataType: "json",
success:function(response) {
if (response) {
var data = $.parseJSON(response);
alert(data.response);
if (data && data.status == "success") {
$.fancybox.close();
}
}}
});
}
});
You can also see the problem live at: http://idify.co.uk, thanks for the help, i am not too good with javascript, im still learning...
Change
if (response) {
var data = $.parseJSON(response);
alert(data.response);
if (data && data.status == "success") {
$.fancybox.close();
}
}}
to
if (response) {
var data = response;
alert(data.response);
if (data && data.status == "success") {
$.fancybox.close();
}
}}
or just use use response directly.