JavaScript Function Post and Call PHP Script

Javascript function post and call php script

EDIT 2018

Yeah, I am still alive. You can use the fetch API instead of jQuery. It is widely supported except (guess who?...) IE 11 and below but there is a polyfill for that. Enjoy modern coding.

Support for fetch API

OLD ANSWER

You will have to use AJAX.

Javascript alone cannot reach a php script. You will have to make a request, pass the variable to PHP, evaluate it and return a result. If you'are using jQuery sending an ajax request is fairly simple:

$.ajax({
data: 'orderid=' + your_order_id,
url: 'url_where_php_is_located.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
}
});

and your php script should get the order id like:

echo $_POST['orderid'];

The output will return as a string to the success function.

EDIT

You can also use the shorthand functions:

$.get('target_url', { key: 'value1', key2: 'value2' }).done(function(data) {
alert(data);
});

// or eventually $.post instead of $.get

Call any PHP function using a Javascript AJAX post request

The PHP Manual states that the $_POST super global variable only contains the post arguments for post data of type application/x-www-form-urlencoded or multipart/form-data.

An associative array of variables passed to the current script via the
HTTP POST method when using application/x-www-form-urlencoded or
multipart/form-data as the HTTP Content-Type in the request.

However, you are trying to send a post request with the body of type application/json.

To read a raw body in PHP you can do this:

$postdata = file_get_contents("php://input");

This will give you a string of the entire request body. You can then json_decode this string to get the desired JSON object.

As for the part of calling a function supplied in the request, the call_user_func_array will do the job fine. Whether or not that is something you should do is an entirely separate issue. From what I understand, you are edging on on the concept of a router and a controller.

I have writen a simple snippet of what I think you want to do:

<?php

switch ($_SERVER['REQUEST_METHOD']) {
case 'POST':
post_handler();
return;
case 'GET':
get_handler();
return;
default:
echo 'Not implemented';
return;
}

function post_handler() {
$raw_data = file_get_contents("php://input");
$req_body = json_decode($raw_data, TRUE);
call_user_func_array($req_body['function'], $req_body['args']);
}

function get_handler() {
echo 'This page left intentionally blank.';
}

function some_function($arg1, $arg2) {
echo $arg1.' '.$arg2;
}

?>

Ajax Post request to call javascript function

Instead of

echo '<script>prepareforconvert("'.$target_file.'")</script>';

and then a separate AJAX request, it would make a lot more sense to just write

require "prepare.php";

in that location instead.

The AJAX request seems to be redundant - you don't need an extra round-trip to the server, because all the information that prepare.php needs is already present within upload.php...nothing new is being added by the client-side code which then runs your AJAX request.

Also just modify prepare.php slightly so it doesn't expect a POST variable:

<script src='scripts\prepare.js'></script>
<?php
if (empty($target_file)){
echo '<script>readFile("'.$target_file.'")</script>';
}
?>

In javascript how to send data to php file using post method

Do something like this and pass your values like this and you can check in your profile.php page....Here you cannot check if(isset($_POST['submit'])), but you you can check if(isset($_POST['name']))

    <form method="post" name="form" enctype="multipart/form-data">
<input type="text" name="name" id="name" placeholder="Name" required/>
<input type="email" name="email" id="email" placeholder="Email" required/>
<input type="password" name="pass" id="pass" placeholder="Password" required/>
<input type="submit" name="submit" value="Send" onclick="myFunction()"/>
</form>

<script>
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
$.ajax({
type : "POST", //type of method
url : "profile.php", //your page
data : { name : name, email : email, password : password },// passing the values
success: function(res){
//do what you want here...
}
});
}
</script>

How can I call PHP functions by JavaScript?

Yes, you can do ajax request to server with your data in request parameters, like this (very simple):

Note that the following code uses jQuery

jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},

success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});

and your_functions_address.php like this:

    <?php
header('Content-Type: application/json');

$aResult = array();

if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }

if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }

if( !isset($aResult['error']) ) {

switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;

default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}

}

echo json_encode($aResult);

?>

Calling JavaScript function after PHP Submit

try this it will work.

here your php code must be last in your file then it will work. otherwise not.

     <form name="form1" id="form1" method="post" action="#" onsubmit="return  checkForm()">

// Some HTML code
<input type="hidden" name="next" value="sd">
<input type="submit">

</form>

<script>
var isDateTimeValid = true;

function checkDates() {
alert("Hello");
isDateTimeValid = false;
}

console.log(isDateTimeValid);
function checkForm () {

if (isDateTimeValid == true) {
return true;
}
else {
return false;
}
}

</script>
<?php

if(isset($_POST['next'])){
echo "<script> checkDates(); </script>";
}
?>

Call Javascript function and execute PHP at the same time?

You can just load the new page with PHP after you check the login. Unless you have some other reason you need to do it with JavaScript, I think it makes more sense to do it in PHP anyway, because you'll want to do different things depending on whether or not the login was successful.

if ($result->num_rows > 0) {
$_SESSION["email"] = $_POST['email'];
header('Location: new url');
exit;
}
else {
echo "Incorrect username or password. Please try again!";
}

When I send a POST request from a JavaScript file to a PHP file in the same application, the PHP script always reads it as a GET request. Why?

OK, I can't tell you why my form data wasn't being posted and I have confirmed that it was being sent as a GET request. But this is how I solved this problem.

I added a hidden field in the form and changed the button of type "submit" to type "button". I then grabbed that button via JS and set a click listener on it. When the user presses the button I first assign my JSON serialized survey object to the hidden field. Then I manually submitted the form and it was sent via POST to the PHP script. The form's method was always "post" but that didn't seem to matter initially. I don't know why but here is my input in the form:

<input name="survey" id="survey" type="hidden" value="">

then I grab the button which looks like this:

<button type="button" class="btn btn-success" id="saveSurvey">Save Survey</button>

notice it's no longer of type "submit".
I then add a click event listener to it and call this function when clicked:

function saveSurvey(e) {
document.getElementById('survey').value = JSON.stringify(survey)
surveyForm.submit()
}

This worked. I don't know if I fully answered my own question so if someone else comes along with a better answer I will adjust this post. Thank you everyone for your help.



Related Topics



Leave a reply



Submit