Dynamic loading JavaScript from AJAX - fails? - php

I have a problem with dynamic loading of javascript function from Ajax.
I want to update some part of HTML with Ajax. Let's say I want to place a button and to attach a javascript function to that button dynamically.
For example:
...
<head>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function f_OnLoadMain()
{
fParseBrowserInfo();
getJSFromServer();
getHTMLFromServer();
}
</script>
</head>
<body onload="f_OnLoadMain()">
<div id="AjaxArea" width="100%" height="100%" align="left" valign="top" >
<!-- Updated with ajax -->
</div>
</body>
</html>
----- getJSFromServer() - calls to php code:
<?php
$somesource = '
function Clicked(){
alert("Clicked");
}
';
class TestObject{
public $source = "";
function TestObject()
{
$this->source = "";
}
function setSource($source){
$this->source = $source;
}
}
$ti = new TestObject();
$ti->setSource($somesource);
echo(json_encode($ti));
?>
the script is inserted with:
var oHead = document.getElementsByTagName('HEAD').item(0);
if (oScript){
oHead.removeChild(oScript);
}
oScript = document.createElement("SCRIPT");
oScript.type = 'text/javascript';
oScript.text = oScript.source;
oHead.appendChild( oScript);
And getHTMLFromServer() - call php :
<?php
$error = 0;
$someText = '
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
';
class TestObject{
public $src = "";
public $error = 0;
function TestObject()
{
$this->error = 0;
$this->src = "";
}
function setSrcString($sample){
$this->src = $sample;
}
}
$ti = new TestObject();
$ti->error = $error;
$ti->setSrcString($someText);
echo(json_encode($ti));
?>
Then the content is updated with:
var dynamicArea = document.getElementById("AjaxArea");
if(dynamicArea != null)
{
dynamicArea.innerHTML = obj.src;
}
And that works fine!
So, when the page loads the button is displayed ok, BUT pressing button doesn't call function Clicked().
Someone knows how to fix it?
Regards!

i guess you have to escape your apostrophe:
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
you see: onclick="Clicked()"
Together with: function Clicked(){ alert("Clicked"); }
It renders to: onclick="alert("clicked")"
Try to escape your apostrophe :)
Regards

Related

How can I download file in codeigniter?

I am trying to download file in my codeigniter web application using javascript and codeigniter controller, it shows the file contents in ASCII format but not download the file directly
view.php
Download
<img src="<?php echo site_url()."/../images/uploads/".$jobno."/thumb_".$prd_row->filename; ?>" alt="Loading Image..." >
<input type="checkbox" name="img_check" id="img_check" class="img_check" image="<?php echo $prd_row->filename ?>">
<script type="text/javascript">
function prd_download(ele)
{
var selected_images = $(".img_check:checked");
var job_no = $("#product_table").attr("jobno");
var image_name = new Array();
for(i = 0; i < selected_images.length; i++)
{
image_name[i] = $(selected_images[i]).attr('image');
}
$.get('<?php echo site_url('project_controller/file_download') ?>', {file_name : image_name, jobno : job_no});
}
</script>
controller.php
function file_download()
{
$url_para = $_GET['file_name'];
$job_no = $_GET['jobno'];
$this->load->helper('download');
$data = file_get_contents(site_url().'/../images/uploads/'.$job_no."/".$url_para[0]);
$name = 'myphoto.jpg';
force_download($name, $data);
}
I had tried by changing path also, but its not working...
I made changes in my javascript
<script type="text/javascript">
function prd_download(ele)
{
var selected_images = $(".img_check:checked");
var job_no = $("#product_table").attr("jobno");
var image_name = new Array();
for(i = 0; i < selected_images.length; i++)
{
image_name[i] = $(selected_images[i]).attr('image');
}
window.location.href = "<?php echo site_url('project_controller/file_download') ?>?file_name="+ image_name +"&jobno="+ job_no;
}
</script>
In javascript I called controller directly, cause $.get function treat like call back...
Now its working fine...! :) :D

How do I call a javascript function in a PHP generated script?

I have one problem. I have a popup and after a user creates a room in the popup, I want to close that popup and then redirect the opener window to a new url. I have the function and everything, except for I do not know how to call the function. (Below I have written where I want the function to load).
Thanks
<?php session_start(); ?>
<script type="text/javascript">
function CloseAndRefresh()
{
opener.location.href = "<?php echo $website_url; ?>/livechat.php?idim=<?php echo $perdorusi2; ?>&room=<?php echo $emri; ?>";
opener.focus();
self.close();
}
</script>
<?php
include_once('db.php');
$perdoruesi = $_GET['perdoruesi'];
if( strlen($_SESSION['id']) > '0' ) { $perdorusi2 = $_SESSION['id']; } else { $perdorusi2 = $perdoruesi; }
function makeRandomString($max=8) {
$i = 0;
$possible_keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$keys_length = strlen($possible_keys);
$str = "";
while($i<$max) {
$rand = mt_rand(1,$keys_length-1);
$str.= $possible_keys[$rand];
$i++;
}
return $str;
}
$emri = makeRandomString();
$hidhnedb = mysql_query("INSERT INTO dbname(`row1`, `row2`) VALUES(NULL, '$emri')");
if($hidhnedb) {
$max=count($_SESSION['mysession']);
$i = $max + 1;
$_SESSION['mysession'][$i][$emri] = $emri;
?>
***Here is the the place where I want to call the javascript function but I do not know how to do that.***
<?php
} else { echo "Error!"; }
?>
What you named "popup" is not really clear: is it another browser window ? An window.confirm or window.alert dialog ? a popup like in jQueryUI or Twitter Bootstrap ?
Let's assume it's a browser window.
You have two possibilities:
1 - Make a single button to close your popup:
<button onClick="CloseAndRefresh()">Close</button>
2 - Trigger it automatically after N seconds:
<script type="application/javascript">
var n = 5;
setTimeout(CloseAndRefresh, 1000*n);
</script>
Try
<script type="text/javascript">
CloseAndRefresh();
</script>
Although a PHP redirect would probably fit your purpose better.
Here is an article on PHP redirects:
http://php.about.com/od/learnphp/ht/phpredirection.htm
You can't invoke Javascript functions from PHP as PHP is running on the server, whereas Javascript is downloaded and run on the client, long after the PHP code has executed. You can however print a <script> tag where you, in this case, invoke the Javascript function you want:
<?php
echo '<script>(function () { CloseAndRefresh(); } ());</script>';

how to disable one hyperlink by clicking on second hyperlink

I have 2 hyperlinks.
when i click on one hyperlink the another hyperlink should be disabled means it should be seen but not clicked by any user
Please help me
hiii
<a id="check" href="google.com">bye</a>
in JavaScript
$('#check').attr('disabled', true);
but it is not working
Using java script you can disable the hyper link by adding a .disabled class as seen below:
.inactive //add this class to the link if you want to disable it
{
pointer-events: none;// this will disable the link
cursor:default;
}
then use .inactive class in appropriate line...
Try below
$('.my-link').click(function () {return false;});
To re-enable it again, unbind the handler:
$('.my-link').unbind('click');
or
$('.my-link').attr('disabled', 'disabled');
Use this to re-enable it:
$('.my-link').attr('disabled', '');
Thanks,
Siva
Below is the code you need.
<a id="gLink" href="http://google.com">click me</a><br />
<a onclick="disableLink()" href="#">Disable link</a><br />
<a onclick="enableLink()" href="#">Enable link</a>
javsacript functions:
function disableLink() {
var a = document.getElementById('gLink');
a.href = "#";
}
function enableLink() {
var a = document.getElementById('gLink');
a.href = "http://google.com";
}
for e.g if you have
<a id="link1" href="page1.php">One</a> <a id="link2" href="page2.php">Two</a>
document.getElementById('link1').onclick = function()
{
document.getElementById('link1').disabled = true;
document.getElementById('link2').disabled = false;
};
document.getElementById('link2').onclick = function()
{
document.getElementById('link1').disabled = false;
document.getElementById('link2').disabled = true;
};
That's all I know
<html>
<head>
<script language="javascript" type="text/javascript">
window.onload = firstLoad;
function firstLoad() {
document.getElementById("lesson").href = "";
document.getElementById("posttest").href = "";
}
function clickHome() {
document.getElementById("pretest").href = "";
document.getElementById("lesson").href = "lesson.html";
}
function lessonRead() {
document.getElementById("posttest").href = "posttest.html";
document.getElementById("lesson").href = "";
}
</script>
</head>
<body>
Home |
Pre-test |
Lesson |
Post-test |
About |
</body>
</html>
You can use jQuery onClick event (or .on("click") / .live("onClick") or whatever you prefer) to change to attribute of the link like this:
$('.my-link').attr('disabled', true);
Short example:
<a href='#' id='link1'>First</a>
<a href='#' id='link2'>Second</a>
<script>
$("#link2").onClick(function(){
$('#link1').attr('disabled', true);
};
}
</script>

codeigniter : passing data from view to controller not working

I have this code in my view file (searchV.php):
<html>
<head>
<title>Search Domains</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function noTextVal(){
$("#domaintxt").val("");
}
function searchDom(){
var searchTxt = $("#searchTxt").val();
var sUrl = $("#url").val();
$.ajax({
url : sUrl + "/searchC",
type : "POST",
dataType : "json",
data : { action : "searchDomain", searchTxt : searchTxt },
success : function(dataresponse){
if(dataresponse == "found"){
alert("found");
}
else{
alert("none");
}
}
});
}
</script>
</head>
<body>
<form id="searchForm">
<input type="text" id="searchTxt" name="searchTxt" onclick="noTextVal()" >
<input type="submit" id="searchBtn" name="searchBtn" value="Search" onclick="searchDom()" />
<input type="hidden" id="url" name="url" value="<?php echo site_url(); ?>" />
</form>
<?php
var_dump($domains);
if($domains!= NULL){
foreach ($domains->result_array() as $row){
echo $row['domain'] . " " . $row['phrase1'];
echo "<br/>";
}
}
?>
</body>
</html>
and below is my controller (searchC.php):
<?php
class SearchC extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('searchM');
}
public function index()
{
$data['domains'] = $this->searchM->getDomains();
$this->load->view('pages/searchV', $data);
switch(#$_POST['action']){
case "searchDomain":
echo "test";
$this->searchDomains($_POST['searchTxt']);
break;
default:
echo "test2";
echo "<br/>action:" . ($_POST['action']);
echo "<br/>text:" . $_POST['searchTxt'];
}
}
public function searchDomains($searchInput)
{
$data['domains'] = $this->searchM->getDomains($searchInput);
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo json_encode($res);
}
} //end of class SearchC
?>
Now I've done a test on the controller using switch to check if the json data passed was successful but it's always showing undefined.. What's wrong here? Can someone explain why the data is not recognized in the controller??
You aren't passing the data in via the url, so you need to use $this->input->post() to retrieve the data.
For example,
public function searchDomains()
{
$data['domains'] = $this->searchM->getDomains($this->input->post('searchTxt'));
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo $res;
}
I believe that the data is being correctly returned, but the problem is with your code check. The $.ajax function parses the JSON and transforms it into a JavaScript object. Therefore you would need to modify your code as follows:
if(dataresponse.res == "found"){ // Changed from dataresponse to dataresponse.res
alert("found");
}
else{
alert("none");
}
This should work for you.

How to run PHP script with post form tag in terminal?

I am trying to create my own method of receiving texts which are alerts from a website. In this script I am using php, I get the html of a site on another domain, then paste its html into the current page, then use jquery to extract information from it, then use its click() button to submit a form with the data in a textarea tag, which then gets passed to a php code. There I send a text with the info to me. This works so far. But now I am trying to automate this in putty terminal using cron. But using the command nohup php myscript.php, it seems to run the php file, but I am not recieving any texts. I think it has something to do with the submit button.
Does anyone know a technique that I can use to solve this problem so that the putty code above will work?
Thanks.
<html>
<head>
<title>
Test
</title>
<script type="text/javascript" src="Includes/jquery-1.8.1.min.js">
</script>
</head>
<body>
<?php
$Fname = $_POST["new_movies"];
if (isset($Fname)) {
$formatted_number = "4163958750#msg.telus.com";
$pieces = explode("\n", $Fname);
$count = 0;
$build = "";
foreach ($pieces as &$value) {
$build = $build.$value."\n";
$count = $count + 1;
if ($count==2) {
$count = 0;
mail("$formatted_number", "", "$build");
$build = "";
}
}
}
else {
$contents = file_get_contents( "http://extratorrent.com/" );
echo "$contents";
}
?>
<form method="post" action="<?php echo $PHP_SELF;?>" style="display:none">
<textarea rows="5" cols="20" id="my_text_field" name="new_movies" wrap="physical"></textarea>
<br />
<input id="my_submit_button" type="submit" value="submit" name="submit"></input>
</form>
<script type="text/javascript">
var build = "";
var g = $('.tl').eq(0);
g = $('.tlr, .tlz', $(g));
for (var i=0; i<g.length; i+=1) {
val = $ ( 'a', $ ('td', g[i]) ).attr('title');
val = val.substr(9);
val = val.substring(0, val.length-8);
build += val;
if (i < g.length-1) {
build += '\n';
}
}
$('#my_text_field').val(build);
if ($('#my_text_field').val().trim() != "") {
$('#my_submit_button').click();
}
</script>
</body>
</html>

Categories