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);
Related
I'm working on some codes. Here's my code
jQuery
duration = 30;
var countdown = setInterval(timer,1000);
var url = window.location.origin + '/pro/index.php/Test';
function timer(){
duration = duration - 1;
if(duration<=0){
clearInterval(countdown);
window.location(url+'/next');
}
}
I want to redirect and run function in Test/next. In next() method, it will rule where the link should go. url helper also has been added automatically in Loader
Controller
public $num;
public $val;
public function index(){
// get the value from GET method
$this->num = $this->input->get('num');
$this->val = $this->input->get('val');
}
public function next(){
$x = $this->num;
$x = $x + 1;
if($x < 4){
redirect(site_url('index.php/Test?x='.$x/.'&num='.$this->num));
}
else{
// it will redirect to another page
// redirect(site_url('index.php/Home'));
echo 'x = '.$x.', num = '.$this->num;
}
(The codes above have been simplified).
The method has been run, but the url was localhost/pro/index.php/Test/next and echo-ing :
x = , num =
It seems like the global property doesn't work for the function called from JS/jQuery. Any explanation or solution for this?
You need ajax calling.
In your View file
<button class="call_ajax" name="submit">Call Ajax</button>
<script type="text/javascript">
$('.call_ajax').click(function(){
var value1 = 'some data';
var value2 = 'some data';
$.ajax({
url: '<?php echo site_url('your_controller/your_function'); ?>',
type: 'POST',
data: {
key1: value1,
key2: value2
},
dataType: 'json',
success: function(url) {
window.location.href = url;
}
});
});</script>
in your Controller
your_function(){
$data1 = $this->input->post('key1');
$data2 = $this->input->post('key2');
// do Data Processing
// For return some data ;
echo "https://some-webiste-url/";
// FOR Array
echo json_encode($any_data_array);
}
NOTE : controller Function called from ajax will not do redirection . If you want to direct to some other url , you have to do that in the Javascript Section Using
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.
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 :)
In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1.
VIEW:
<h4 class="qr-title" id="status"></h4>
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
console.log(data);
}
});
document.getElementById("status").innerHTML = isAuth;
}
</script>
here's the listen_auth() function in my CONTROLLER:
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
return 1;
} else{
return 0;
}
}
The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? Or is there any better way to do this?
The function from server 'listen_auth()' should print text not return.
public function listen_auth(){
$username = $this->input->post('username');
$isApproved = $this->adminmodel->get_auth($username);
if($isApproved == 1){
echo 1;
} else{
echo 0;
}
}
And then get the answer from server in AJAX request:
<script>
var username = <?php echo(json_encode($username)); ?>;
function checkAuthStatus() {
setInterval(getStatus, 1000);
}
function getStatus() {
var isAuth = <?php echo(json_encode($isAuth)); ?>;
$.ajax({
url: '<?php echo base_url('auth/listen_auth'); ?>',
type: 'post',
data: {username:username},
success: function(data){
document.getElementById("status").innerHTML = data;
}
});
}
</script>
You need to declare $isAuth and assign its value in ajax request, because php variable will not change its value without server request.
I'm trying to create a small chat application but for the sake of minifying the bytes being transferred is there any other way on writing this javascript that is less heavy than this code?
Here is my javascript:
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = AjaxRetrieve();
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
Can this also be done on a JSON format too? because I think some says that json is lighter.. not sure though
here is my php code
$con = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt=$con->prepare($sql);
$stmt->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt->execute();
foreach($stmt->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$text=$_POST['message'];
$sql4 = "INSERT INTO $tblname2(msgid,username,message_content,message_time,recipient)VALUES(:aid,:a,:b,NOW(),:c) ";
$stmt5 = $con2->prepare($sql4);
$stmt5->bindParam(':aid',$tblpre,PDO::PARAM_STR);
$stmt5->bindParam(':a',$_POST['name'],PDO::PARAM_STR);
$stmt5->bindParam(':b',$text,PDO::PARAM_STR);
$stmt5->bindParam(':c',$usern,PDO::PARAM_STR);
$stmt5->execute();
As user2401175 saies. Why not use a framework, thats what they are here for.
jQuery is really simple and easy to understand.
You could try adding this, just before your "" tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Under this include of jQuery, you may now use the jQuery Post method to do your ajax request.
In html Use
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
then Create javascript object like this
var changePacket = {
date1:value1,
data2:value2
}
And send Ajax request
$.ajax({
url: "phpFile.php",
dataType: 'json',
type: 'POST',
data: {json:JSON.stringify(changePacket)},
success: function(response) {
alert('hip hip hurray');
},
error: function(response) {
alert('some thing wrong happend');
}
});
In php
$json = $_POST['json'];
$data = json_decode($json);
now user your variable like this $date->data1 and $date->data2