assign php variable to javascript variable - javascript

How can i assign value of a javascript variable using php variable
$(function(){
$("select[name=myselectlist]").change(function(){
var id = $(this).val();
if(id != 0) {
$.post("ajax.php", {"id":id}, function(){
var data = "somedatahere";
document.getElementById("namesurname").value = data;
});
}
});
});
the code above works perfectly without php.Yet, i need to assign "var data" from mysql everytime.

If your php var is in the scope of the file where you have this function, you can do it like this:
var data = "<php echo $myvar; ?>";

1) You can do as Shadowfax wrote but more simple:
var data = '<?=$dbResult?>';
2) More correct. Pass your result to AJAX response with json_encode function in PHP so you can rewrite your JavaScript code block as follows:
...
$.post("ajax.php", {"id":id}, function(response){
$("#namesurname").val(response.data);
});
For example your PHP code block in backend may look like this:
....
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')) {
echo json_encode(array('data' => $dbResult));
}

If this javascript code is in the php file, then you can simply use php variables as updated in the code:-
<?php
// assign a value
$data = 'your data here';
?>
$(function(){
$("select[name=myselectlist]").change(function(){
var id = $(this).val();
if(id != 0) {
$.post("ajax.php", {"id":id}, function(){
var data = "somedatahere";
document.getElementById("namesurname").value = "<?php echo $data;?>";
});
}
});
});

Related

php variable to javascript (via json)

I know this has been discussed before but I can't seem to make anything work. I'm trying to pass the variable $thedate from PHP file mainclass.php to the variable datestr in a JS function from the file footer_script.php
JS:
function getsched(str)
{
//some code
$.ajax({
type: 'POST',
url: 'mainclass.php',
data: 'date=' + str + '&form=getsched',
success: function(data) {
var datestr = <?php echo json_encode($thedate); ?>;
$("#" + str).html(data);
}
}).error(function() {
alert(data);
});
}
PHP:
case "getsched":
//some code
//some query
while($row = mysql_fetch_array($result))
{
//more code
$thedate = $_POST['date'];
}
//other code here
break;
When I alert datestr, I get undefined. How to fix this?
You can't use PHP like this. You should obtain the response from PHP and use it. In your PHP, you should output a response similar to this (just an example of JSON response):
echo json_encode(array('thedate', '2018-4-3'));
and you can obtain the value of 2018-4-3 in your JS with:
function getsched(str)
{
//some code
$.ajax({
type: 'POST',
url: 'mainclass.php',
data: 'date=' + str + '&form=getsched',
success: function(data) {
var datestr = data.thedate;
$("#" + str).html(datastr);
}
}).error(function() {
alert(data);
});
}
You need to replace the line:
var datestr = <?php echo json_encode($thedate); ?>;
with
var datestr = JSON.stringify(date);
alert(datestr);
It will convert the server response to a JSON encoded string. The encoded string is then displayed in the alert. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Assign a global variable in HTML/PHP file before includeing JS file.
var datestr = <?php echo $thedate; ?>;
Then you can access the datestr variable from your JS file.

Ajax not getting only json output data (it print whole loaded view code.).? codeigntier

Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)

Sending a JavaScript array to PHP via POST

I am trying to send a JavaScript array to a PHP file via POST.
JS:
var songlist = ['song1', 'song2', 'song3'];
var sendData = function(){
var data = songList.join(',')
$.post('test.php', {data: data}).always(function() {
window.location = 'test.php';
});
}
sendData();
test.php:
<?php
$songData = $_POST['data'];
$songData = explode(',', $songData);
print_r(array_values($songData));
?>
when sendData(); directs me to test.php I get:
Notice: Undefined index: data
Why doesn't the data variable have any value when I try to print or use it?
That's not how POST request works. Read more about Ajax, but for now, that's how you should do it.
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
$songData = $_POST['data'];
print_r($songData);
?>
1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid.
2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. Thats why its showing "Notice: Undefined index: data"
3) Try to understand how ajax works. Follow it -
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
if(isset($_POST)){
if(isset($_POST['data'])){
$songData = $_POST['data'];
print_r($songData);
}}
?>

How can I use a GET from my php file, to get a variable that I declared in my .js file?

I made some variables that contain the answers that are selected in my dropdown menu's. Now I want to use those variables in my .php file so i can make a query of them. But I can't figure out what I'm doing wrong, so here is my code.
This my main.js file:
$("#slctTable").change(function(){
var table = document.getElementById("slctTable");
var tableSelected = table.value;
console.log(tableSelected);
});
$("#slctField").change(function(){
var field = document.getElementById("slctField");
var fieldSelected = field.value;
console.log(fieldSelected);
});
$("#slctAttribute").change(function(){
var attribute = document.getElementById("slctAttribute");
var attributeSelected = attribute.value;
console.log(attributeSelected);
});
And this my getData.php file:
<?php
include "connect.php";
$test1 = $_GET['tableSelected'];
$test2 = $_GET['fieldSelected'];
$test3 = $_GET['attributeSelected'];
echo ($test1);
echo ($test2);
echo ($test3);
?>
You will have to redirect the user to a page with the variables in the URL. PHP runs a script on the server then sends the output of that script to the client. JavaScript only runs on the client. You can do this:
$('#slctTable').change(function(){
var table = document.getElementById("slctTable");
var tableSelected = table.value;
console.log(tableSelected);
window.location.href = "?tableSelected=" + tableSelected
});
Alternatively you can make an Ajax request to make a call to the server without refreshing the page. You can use this:
$('#slctTable, #slctField, #slctAttribute').change(function ()
{
var tableSelected = document.getElementById("slctTable").value;
var fieldSelected = document.getElementById("slctField").value;
var attributeSelected = document.getElementById("slctAttribute").value;
$.ajax({
"url": "getData.php",
"type": "GET",
"data": {
tableSelected: tableSelected,
fieldSelected: fieldSelected,
attributeSelected: attributeSelected
}
})
.done(function (response)
{
console.log(response);
});
});
Using Jquery, you could use Ajax to accomplish that:
$("#slctTable").change(function(){
var table = document.getElementById("slctTable");
var tableSelected = table.value;
console.log(tableSelected);
});
$("#slctField").change(function(){
var field = document.getElementById("slctField");
var fieldSelected = field.value;
console.log(fieldSelected);
});
$("#slctAttribute").change(function(){
var tableSelected = slctTable.val();
var fieldSelected= slctField.val();
var attributeSelected = $(this).val();
$.get( "getData.php?tableSelected="+tableSelected+"&fieldSelected="+fieldSelected+"&attributeSelected="+attributeSelected )
.fail(function(data){
alert('Ajax Call Error');
})
.done(function(){
alert('Success');
});
});
});

Javascript alert when new row is added to database

I need to give a javascript alert to users browser when a new record is added to database. So far i have done this:
PHP chatalert.php
require("../system/config.php");
$result = mysql_query("SELECT * FROM chat");
$rows = mysql_num_rows($result);
echo $rows;
Javascript: test.php
<?php
define('BASEPATH', true);
require("../system/config.php");
?>
<script>
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "chatalert.php",
success : function(data){
if (data > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);
</script>
But I always recive an error: "Uncaught ReferenceError: $ is not defined". So I will need some advice on this.
Mairo
Have you included jquery? if not try adding this in your head tags
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
also make sure to parse the string to integer/Float for accurate result. The data returned by php can also be in string format:
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "chatalert.php",
success : function(data){
if (parseFloat(data) > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);

Categories

Resources