Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the href?

I have a button, when pressed has to call a function from an external php file and load it in a new page.

When I click the "SHOW" button on my index.php page, it shows me the message hold in "mesaj", but displays it in index.php page (that I don`t want!).

What I want to accomplish is when I click on the "SHOW" button on my index.php it shows me the content of the message into another php page, named - for eg - content.php. I want to set the href.

index.php

<input type = "button" class="btn btn-primary" id = "show" onClick = "show()" value = "SHOW"/>

functions.php

function show()
{

    database();

    $sql = "SELECT title FROM `Articles`";

    $titleSql = mysql_query( $sql ) or die("Could not select articles:");

    $html = '<html><body><div class="container"><h2>Basic List Group</h2><ul class="list-group">';

    while ($title = mysql_fetch_array($titleSql)) {
        $html .= '<li class="list-group-item">'.$title["title"].'</li>';
    }

    $html .= '</ul></div></body></html>';

    echo $html;
    //die(json_encode(array("mesaj" => "Entered data successfully ")));

}

function.js

function show(){
        var n = $('#show').val()
        $.post("functions.php", {show:n}).done(function(mesaj){
            //$(document).html(mesaj);
            document.write(mesaj);
        });
}
like image 548
Lulu Avatar asked Nov 10 '22 13:11

Lulu


1 Answers

There is no reason (apparently) to go from PHP to JS in your case. You'd use JS $.post if you need a change of the DOM after it loaded. You can just do this:

<a href="function.php" class="btn btn-primary" id="show"/>SHOW</a>

This works without going thru JS.

If you want to use BUTTON and go via JS then do this:

<input type="button" class="btn btn-primary" id="show" value="SHOW"/>

jQuery:

$('#show').click(function(e){
    e.preventDefault();
    window.location.href = 'function.php';
});

Plain JS:

document.getElementById("show").onclick = function(){
    window.location.href = 'function.php';
}

As a note, be careful because <button> if used inside a form when clicked submits the form. That's why the e.preventDefault();

Let's say you have multiple functions in your function.php and you need to call one a specific one, I would do this:

function.php

if(isset($_GET['fn1'])){
    function functionOne(){
      //do something
     }
}

if(isset($_GET['fn2'])){
    function functionTwo(){
       //do something else
    }
}

And call it this way:

<a href="function.php?fn1" class="btn btn-primary" id="show"/>SHOW</a>

or

$('#show').click(function(e){
    e.preventDefault();
    window.location.href = 'function.php?fn1';
    //window.location.href = 'function.php?fn2';
});
like image 111
Mr.Web Avatar answered Nov 14 '22 21:11

Mr.Web