php variable to javascript (via json) - javascript

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.

Related

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 :)

use javascript variable in php in jquery function

I want to use javascript variable in php function.. my code is as below
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
alert('<?php echo getYoutubeDurationV3("<script>document.write(video_val);</script>"); ?>');
});
});
I want to use video_val variable in php function.. how can i do that ?
You can use Ajax for this solution. When you place your PHP getYoutubeDurationV3 function in a .php file.
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
$.ajax({
url: 'yourphpscript.php',
data: {duration: video_val},
type: 'POST',
success: function(data) {
alert(data);
}
});
});
});
And in your PHP file you can get the value like this:
<?php
$duration = $_POST['video_val'];
//rest of your logic, in your case your function
//return your response back to your webpage.
return $response;
?>
yes, u can do that by ajax post method..
$(document).ready(function() {
$("#btn_url").on('click', function() {
var video_val = $("#video_url").val(); alert(video_val);
$.ajax({
url: 'ajax_file.php',
data: {duration: video_val},
type: 'POST',
success: function(data) {
alert(data);
}
});
});
});
And in ajax_file.php write below code..
<?php
$duration = $_POST['video_val'];
return $duration ;
?>

How do you input javascript variable into php script?

I'm trying to get a function called that calls a php function with an input.
javascript function (picNum is an integer):
function hello(picNum) {
var pictureNumber = picNum;
var phpFunc = "<?php
include 'otherfile.php';
otherFileFunc(" + pictureNumber + ") //This is where the problem is, the input(pictureNumber) wont go through
?>";
echo phpFunc;
}
otherfile.php
<?php
function otherFileFunc($i) {
$final = $i + 1;
echo $final;
}
?>
this code pretty much says if you do onclick="hello(1)" then the output or phpFunc should be 2 because you add one in the otherfile.php, but no matter the input the output is always 1 so I'm guessing the input at where I marked just isn't going through.
DONT TELL ME IT DOESNT WORK BECAUSE IT DOES.
if i put an integer instead of " + pictureNumber + " it works perfectly!
any help is appreciated :)
Unfortunately you won't be able to call php from javascript.
Php is run from the server and javascript is run on a client (usually, the exception being node.js. However even in the instance of node.js, php is not used as javascript has replaced its functionality)
If you need to have javascript "call" a server function you will need to look into ajax requests so that the server can then run a function and return it to the client.
You have to use Ajax bro:
Javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
PictureNumber = output_string['picturenumber'];
alert(PictureNumber);
}
});
}
PHP otherfile.php:
$picNum = $_POST['picNum'];
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);
Note: Untested
EDIT, tested:
javascript:
function hello(picNum) {
var pictureNumber = picNum;
$.ajax({
url: "otherfile.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
pictureNumber = output_string['picturenumber'];
alert(pictureNumber);
}
});
}
hello(1); //sample
PHP otherfile.php:
$picNum = $_POST['picNum'];
$picNum = 1;
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = otherFileFunc($picNum);
$array = array('picturenumber' => $outputnumber);
echo json_encode($array);

Pass Array FROM Jquery with JSON to PHP

hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});

assign php variable to javascript variable

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;?>";
});
}
});
});

Categories

Resources