How to send variable value from php to js [duplicate] - php

This question already has answers here:
Inserting php into js file
(5 answers)
Closed 9 years ago.
I want to send variable from php to js . I want to work this file like that js sends value php file then php works on this code and return again variable like true or false after that js controls and shows something users.I am Sorry for my poor English :D
<?php
if(!empty($_POST['a']))
{
$value=1;
echo '{"a":"'.$value.'"}';
}
else
{
?>
<script src="assets/plugins/jquery-1.10.1.min.js" type="text/javascript"></script>
<script src="assets/plugins/jquery-migrate-1.2.1.min.js" type="text/javascript></script>
<script>
function sendValue($page,$value)
{
$.post($page, $value , function(data)
{
if(data.a==1)
{
alert("its work");
}
else
{
alert("oh no Houston we have a problem !!");
}
}
)};
</script>
<a href="#" onclick='sendValue("a.php",{a:"1"});' >blabla</a>
<?php
}
?>

str=$("input.classname").val();
or
str=$("input#idname").val();
it is inside js
and the easy way to send information by hidden input like this
<input type="hidden" class="classname" value="<?php echo "here the value you want to send"; ?>" />

If I understand correctly, you want to send data to PHP, then have PHP return data accordingly. Here is what I use to make an ajax call:
var sendData = "action=do_action";
sendData += "&value=" + $("input.value").val();
$.ajax({
url: "post.php",//Page to send our data to
global: false,
type: "POST",
data: sendData,
dataType: "html",
async:false,
success: function(data){
//We could return JSON and then just parse that, but I usually just return values like this
//create jquery object from the response html
var $response=$(data);
var results = $response.filter('div.results').text();//Or .html() if we want to return HTML to show
if (results == "true") {
alert("it works");
}else{
var reason= $response.filter('div.reason').text();
alert(reason);
}
}
});
And the PHP would look like:
<?php
$action = $_POST['action'];
if ($action == "do_action") {
if (true) {
echo "<div class='result'>true</div>";
}else{
echo "<div class='result'>false</div>";
echo "<div class='reason'>Houston, we have a problem!</div>";
}
}
?>

Which is the active directory in this case? Is it the one which contains a.php?
Also, you are sending back a string. You must convert that using JSON.parse().
Your response is a string, so it does not have an 'a'.

Related

PHP file not picking up $POST parameter from JQuery

Thank you very much for your help. I have the following file. The two alerts in the jquery event listener both work, but not the one inside the if (isset) block, as it is posting to itself. Thank you very much! I have abbreviated the code, everything is inside its proper tag.
<?php session_start();
include("config.php");
$myID = $_POST['chatid'];
$_SESSION['chateeID'] = $myID;
if(isset($_POST['inputmessage'])) {
echo '<script type="text/javascript">alert("got in here");</script>';
$sMessage = mysqli_real_escape_string($_POST['inputmessage']);
if ($sMessage != '') {
$sql = "INSERT INTO chatmessages (user_one_id, user_two_id, mymessage, action_user_id)
VALUES ('$user1', '$user2', '$sMessage', '$action_user_id')";
// Perform a query, check for error
if (!mysqli_query($con,$sql)){
echo '<script type="text/javascript">alert("'.mysqli_error($con).'");</script>';
}
}
}
<script>
$('#ChatInputBox').keydown(function (e) {
var keyCode = e.keyCode || e.which;
var txt = $("#ChatInputBox").val();
if (keyCode == 13 && txt!="") {
alert("txt is: "+txt);
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
});
}
});
</script>
I did this exactly the same way on another page but cannot find the discrepancy here.
After setting up your code on my development system I discovered that the short piece of script your PHP code is sending is being sent correctly, and being received correctly but not being executed by the jQuery AJAX code.
If you want that alert to show up in your page you need to place it in an HTML element
<div id="response"></div>
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("got to callback!");
$("response").html(result);
});
A better way to do this is to echo some sort of status as a JSON object, then unpack that into an alert in Javascript.
echo json_encode((object)['status'=>'ok', 'msg'=>'All good']);
then
$.post("inserttochat.php", { inputmessage: txt }, function(result){
alert("Response: "+result.status+', '+result.msg);
},'json');
Note the json datatype added to the POST request*.
A better approach here is to standardise all your responses as JSON, and then add header("Content-type: application/json"); at the top of your PHP files. This will tell jQuery what the data is, rather than you having to force the issue in the browser.

Echo JS variable in Joomla JText

Ajax.php, Script tag in php file
<script>
success: function(data) {
var message = data.message; //Json data
if ( data.status == 1 ) {
jQuery("#msgError").html(<?php echo JText::_(' + message + ');?>);
}
}
Is it possible to Echo JS variable in php like above?
Here is a best example,
<?php
// In php write following code
JText::script('COM_HELLOWORLD_MESSAGE');
<script>
// Using in Javascript like this
Joomla.JText._('COM_HELLOWORLD_MESSAGE')
// For your example look like
success: function(data) {
if ( data.status == 1 ) {
jQuery("#msgError").html(Joomla.JText._('COM_HELLOWORLD_MESSAGE'));
}
}
;
</script>
I already sent code to merge in joomla to make it more advanced. Please check it here https://github.com/joomla/joomla-cms/pull/6006
Also there are many ways to do it which you will find in above link.

PHP: Unable to get the json output into my javascript page as a variable value [duplicate]

This question already has answers here:
php : how to pass database value into a javascript/jquery function
(3 answers)
Closed 9 years ago.
i have to get output in this format
var sampleTags = ['c++', 'scala'];
My javascript function is:
<script>
$(document).ready(function(){
$(function(){
var sampleTags;
$.ajax({
url:"<?php echo base_url('ajax_get_tags/gettags'); ?>"
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
......................
.......................
$(function(){
var sampleTags = <?php echo json_encode($query) ?>;
My php controller is
function gettags(){
$json_array=$this->tagsmodel->get_all_tags();
echo json_encode($json_array);
}
My model is
//-------------------------------Function get all tags--------------------------------
function get_all_tags() {
$this->load->database();
$this->db->limit('10');
$this->db->select('tags_name');
$res = $this->db->get('tags');
$ret = array();
foreach ($res->result_array() as $row) {
$ret[] = $row['tags_name'];
}
return $ret;
}
How can get the json output from ajax request to be display its value for a javascript variable?
Please help me to solve this issue..
You're using an older version of jQuery, so .done won't work. It looks like you want to add a key to your request object called complete, with the anonymous function as its value:
$.ajax({
url: "<?php echo base_url('ajax_get_tags/gettags'); ?>",
complete: function(data) {
if (data) {
sampleTags = data;
}
}
});
I found this out by googling your error message. One of the results was this question: Object #<XMLHttpRequest> has no method 'done'. You could have just googled the error message and figured this out yourself.
I would like to give a few suggestions
Check for the return value form the server side by printing it with die or exit.
check the http response in firebug net tab.
3.

IF HTML element display is none, then do something, ELSE do something else - PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get CSS style from PHP
I want to make an if that will do things, only if div's display is not none. Here is an example:
<div id="div_1" style="display:none;">blah blah blah</div>
<?php if (div_1 display is none){...} else {echo $variable;} ?>
Any idea how will I syntax this part (div_1 display is none)??? If it can be of-course! Thank you in advance!
You cant do that server-side. Maybe you can use JavaScript and Jquery is a good tool:
if($('#div_1').css('display') == 'none')
{
...
}
else {
$('#Some_Div').html('...');
}
for non-jquery plain 'ol javascript
if (element.style.display == 'none'){
//your element is not visible
} else {
//your element is visible
}
You can use Ajax and JavaScript
<script>
$(document).ready(function() {
if($('#div').is(':hidden')) {
$.ajax({
url: "file.php",
type: "POST",
data: {somedata: "data"},
success: function(msg) {
$("#div").html(msg);
}
});
}
else {
//...
}
});
</script>

Stuck with Codeigniter and jQuery.ajax

So... thanks to one of stackoverflow users I tried to implement this fancy feature into my existing Codeigniter application...
In my View I have this:
<script type="text/javascript">
$(function() {
$(".submit_op").click(function() {
var dataString = $("#op_form").serialize();
var url = "<?php echo site_url('submit/insert_data'); ?>";
$.ajax({
type: "POST",
url: url+"/"+dataString,
data: dataString,
cache: false,
success: function(html){
//$("div#op").prepend(html); //PROBLEM HERE???
$("div#op").prepend("<div>TEST</div>");
$("div#op div:first").fadeIn("slow");
//$("#debug").append("<font color=green><b>OK!</b></font> : " + dataString + "<br/>");
},
error: function(html){
//$("#debug").append("<font color=red><b>ER!</b></font> : " + dataString + "<br/>");
}
});
return false;
});
});
</script>
<div id="debug"></div>
<?php
//here goes some data from db... newly added div should go in top of other divs
foreach ($some_data_sent_from_controller as $var) {
echo "<div id=\"op\">";
echo "<table width=\"100%\" border=\"0\">";
//showing data
echo "</table>";
echo "</div>";
}
echo "<form action=\"#\" id=\"op_form\">";
//some clickable stuff...
echo br().form_submit('submit', 'OK', 'class="submit_op"');
echo "</form>";
In my Controller I have a function which handles data sent from View:
function insert_data($input) {
$this->load->model('blah_model');
//processing serialized data and sending it to corresponding tables via Model
$this->blah_model->add_to_table($some_data);
$this->blah_model->add_to_another_table($some_other_data);
}
And the Model is not a biggy :)
function add_to_table($data){
//processing data...
$insert = $this->db->insert('my_table', array('array_which_contains_actual_data'));
if ($insert == TRUE) {
return TRUE;
} else {
return FALSE;
}
}
//etc.
As far as I can tell, my problem is not in my M-V-C pattern, since every time I submit a form the data is correctly inserted in all possible tables in my relational db... But the newly added row just won't show up unless I refresh a page.
I think that I'm doing something wrong inside of my jQuery.ajax lines... If I run my script with this line $("div#op").prepend("<div>TEST</div>"); and when I submit a form, I get desired result - text TEST shows up on top of my page every time I submit... But if I change that line to $("div#op").prepend(html); nothing show up until refreshing...
What am I doing wrong here??
Thanks a lot for any help!
wow, this was probably pretty lame from me... But in the end I figured out that I have to echo out my result in controller, not return it... So when I change the function in my controller into
function insert_data($input) {
$str = "<div>KILLROY WAS HERE!</div>";
echo $str; // <----- !!!!!!
}
I can see a message on my page...
Now to other things... Thanks for self-brainstorming :)

Categories