How to use a PHP Function inside a JS Function

Asked

Viewed 120 times

-1

I have a PHP function (I read that it was recommended to make modifications to the PHP database and not JS)

function insertTable()
    {

        $name = 'nome';
        $categoria = 'categoria';
        $download = 1000;
        $upload = 1000;
        $magnet = 'magnet';

        mysqli_query($connect, "INSERT INTO torrents(`Nome`, `Categoria`, `DownloadQuantity`, `UploadQuantity`, `Magnet`) VALUES ('".$name."', '".$categoria."', ".$download.", ".$upload.", '".$magnet."')");
    }

And in my role in JS(she’s at action one button) I want to call the function insertTable().

I read that PHP runs on the server and JS and runs on the browser, the only way I found it was when the PHP function is in a separate file, so using AJAX, but I want to do this with both functions in the same file.

  • @Sorry Miguel, I think Stack cut her off, I got :D

  • No problem, it was more for the joke.. I already deleted the comment

  • In the same file, only if you make the AJAX request to the file itself and treat it with PHP. However, as the file would receive both 'normal' requests and via AJAX, with PHP you will have to worry about not returning the HTML to when it is AJAX. Honestly, I see no reason to do this, not to mention that it leaves the organization of the project confused.

  • I’m on my cell phone, so I can’t put the code in now. I use ajax to put a div on the page when pressing a button, and when that button is pressed I have to enter data into the database.

1 answer

1


Javascript has no way to access your database, so the command can only be done by a script that runs on the server, in case PHP, the solution is to make an ajax request, or even a POST/GET form, as you want to be on the same page, I think AJAX is more practical, but in both cases the operation is the same:

  • Your page requires a link
  • This link executes the command in the bank

You want everything to be in the same "file"? Make an "if" in the file validating some parameter passed by your AJAX or POST/GET ($_FORM[your parameter) that tells your file what to do.

It’s not pretty, but it works, but unless you have some sort of access control, it would be at least a security breach in your application

  • Before answering search if there is no answer in another question that solves the problem, example of research that returns several results http://answall.com/search?q=php+server-side+javascript+client-side

  • Who would have to do that is not the question?

  • Yes, also, it is everyone’s duty to keep the community organized, both me and you and the author. Except the author didn’t know the answer, and you did, so you can find out what the proper answer is, it’s easier than it is for him who doesn’t have the slightest notion, you know? See you around ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.