Call a php from another php using ajax - javascript

I'm trying to call a php from ajax, so I wrote this on my first page (index.php):
<script type="text/javascript">
function valid(id) {
var element = document.getElementById(id);
$.ajax({
url: 'valid.php',
type:'POST',
data:
{
url: element.children[0].childNodes[0].nodeValue
},
success: function(msg)
{
console.log('done 1');
}
});
}
</script>
and here is my second one (valid.php):
<script type="text/javascript">
console.log('done 2');
</script>
<?php
if (isset($_GET['url']))
{
try
{
$bdd = new PDO('mysql:host=host;dbname=dbname;charset=utf8', 'id', 'password');
$bdd->exec("INSERT INTO sometable (url)
VALUES (".$_GET['url'].");");
}
catch (Exception $e)
{
die();
}
}
?>
But when I call my function, it doesn't seem to call valid.php even if the console show "done 1", "done 2" doesn't appear anywhere by the way and the database stay unchanged, like valid.php just doesn't run.
How may I fix that? Thank you!

Since you are using POST, you need to retrieve your data using $_POST rather than $_GET.

In valid.php if you are expecting isset($_GET['url']) which is a GET parameter but your AJAX request is sent via POST. You should change that to isset($_POST['url']).
Regarding the console.log('done 2'); on valid.php it won't get executed unless you append that to the body of index.php and evaluate that specific script but it is redundant because console.log('done 1'); refers to the completion of valid.php request.
Edit: On your insertion query you have $_GET['url'] and it should be $_POST['url'].

Related

Ajax function returning echo instead of value

I need to update a span element with a value from an update PHP function (that performs mySQL queries), triggered after a button click. I used jQuery/Ajax to achieve this, via a function in another file.
Apparently PHP logs in this case require the following form:
echo '<script> console.log("My message"); </script>';
So I put these in my PHP function file, which looks like the following:
if(isset($_POST['myAction'])) {
if ($_POST['myAction'] == "right_action") {
echo '<script> console.log("ENTERED"); </script>';
update(...)
...
}
}
function init()
{
...
echo '<script> console.log("Successfully connected to database"); </script>';
return ...;
}
function fetch(...) {
init();
...
echo '<script> console.log("Database fetch successful"); </script>';
echo '<script> console.log(' . result . '); </script>'; // equals 49
return ...;
}
function update(...) {
init();
...
echo '<script> console.log("Database update successful"); </script>';
return fetch(...);
}
On the one hand, the logs appear properly while the PHP is executing.
However it seems that the return value of the update PHP function, from the perspective of the Ajax function, contains all the logs. Here is the Ajax function:
$.ajax({
method: "POST",
url: "my_php_file.php",
data: { myAction: 'myAction',
(params) },
success: function(result) {
console.log("Success at Ajax transfer-to-PHP");
console.log("RESULT: " + result);
spanElement.load(result);
},
error: function(error) {
console.log("Error at Ajax transfer-to-PHP: " + error);
}
});
And the Ajax log:
RESULT
<script> console.log("ENTERED"); </script><script> console.log("Successfully connected to database"); </script><script> console.log("Database update successful"); </script><script> console.log("Successfully connected to database"); </script><script> console.log("Database fetch successful"); </script><script> console.log(49); </script>
The same behavior happens when I print in Ajax the content of the span element, initially filled with the result from the fetch PHP function. It prints all the logs; but then it does print the value (while the update mechanic above doesn't even).
I think you are approaching this very unusually, and making things quite hard for yourself. I've never seen PHP returning Javascript to do console.log() before. I'm sure it works, and maybe it really suits what you need, but it seems very Rube Goldberg-ish to me.
If you want to generate logs of what your PHP is doing, just do it in PHP on the server. You can then monitor your application log on the server.
If you want a response from your PHP that your browser can handle and use to update your page, just return the response as text, or better yet as JSON, so you can include eg a status as well as a message. If you really want to pass log messages back to the browser, you could structure the response to include a log element which will be logged to the console, along with a message element to display to the user. You might want to include a status or success element, which is true or false.
There are thousands of examples here on SO, here's a highly ranked one, here's a simpler one, but searching for anything like "php ajax example" will turn up plenty more for inspiration.
As to why your result includes multiple msgs, just trace through what your PHP is doing - each step echoes a message, one after the other. They're all part of the content returned to your Javascript.
I see one bug in your Javascript - .load() loads content from the specified URL. You've already loaded content with your .ajax(), and result is not a URL, so that isn't doing what you expect and won't work.
Here's some clunky pseudo-code which skips over some specifics but gives you a general idea. If you want to keep a running log of each step as you are currently, you'll have to pass your $response array around to/from your functions, or if this is a PHP class make it a class property to avoid that. If you just log to the server you can avoid that, since you only need the final result of your update().
$response = [];
if(isset($_POST['myAction'])) {
if ($_POST['myAction'] == "right_action") {
// If you really want to return log msgs to the browser
$response['log'][] = 'ENTERED';
// More appropriate might be to just log them in PHP. How you do that is
// up to you, eg if you are using a library or just your own simple fopen(),
// fwrite() etc. Though you might not want this level of detail after initial
// development.
// myLogger('Entered');
// In this pseudo-code you'll have to include $response as parameter passed
// to your functions so they can update it, and they'll have to return it
update(...)
...
}
}
// Return your response as JSON which is easy for JS to work with
header('Content-Type: application/json');
echo json_encode($response);
function init()
{
...
$response['log'][] = 'Successfully connected to database';
// myLogger('Successfully connected to database')
return ...;
}
function fetch(...) {
init();
...
$response['log'][] = 'Database fetch successful';
$response['message'] = $result;
// myLogger('Database fetch successful')
return ...;
}
function update(...) {
init();
...
$response['log'][] = 'Database update successful';
// myLogger('Database update successful')
return fetch(...);
}
Then your Javascrtipt can do something like:
$.ajax({
method: "POST",
url: "my_php_file.php",
data: {
myAction: 'myAction',
(params)
},
success: function(result) {
console.log("Success at Ajax transfer-to-PHP");
// Log your log msgs
console.log("RESULT:");
console.dir(result.log);
// .load() will load the specified remote content, similar to .ajax()
// spanElement.load(result);
// You can use .html() or .text() to update your span
// https://api.jquery.com/html/
spanElement.html(result.message);
},
error: function(error) {
console.log("Error at Ajax transfer-to-PHP: " + error);
}
});

How can we apply both JavaScript and PHP to a button?

When I click a button:
I need the JavaScript to perform some function.
Also run PHP code as well.
How can we achieve this?
PHP is only run by the server and responds to requests like clicking on a link/button (GET) or submitting a form (POST).
HTML & JavaScript is only run in someone's browser.
<html>
<?php
function PhpFunction() {
echo 'A php function';
}
if (isset($_GET['JsFunction'])) {
PhpFunction();
}
?>
Hello there!
<a href='index.php?JsFunction=true'>Run PHP Function On Click Of This Link</a>
</html>
Alternatively ,
You can create a ajax request to run a php code in your server..
Ajax can help you to send an asynchronous request to the server that php (or other) can catch, in this way you can implement and play with some callback functions
$.ajax({
url : "yourScript.php", // the resource where youre request will go throw
type : "POST", // HTTP verb
data : { action: 'myActionToGetHits', param2 : myVar2 },
dataType: "json",
success : function (response) {
//in your case, you should return from the php method some fomated data that you //need throw the data var object in param
data = toJson(response) // optional
//heres your code
},
error : //some code,
complete : //...
});
in your php script, you'll receive the request posted throw the superglobal vars like POST (for this example)
<?php
$action = (string)$_POST['action']; //this is unsecure, its just for the example
if("myActionToGetHits" == $action) {
//here you have to call your php function and so on..
$data = hitsMonth();
echo $data;
exit;
}
here is html
<a href="#" onclick="javascript:functionName(arg1, arg2);">
This is a basic example to do it, there are lots of ways to do.
Have javascript do the submit:
function button1() {
// js code here
var formelt = document.getElementById("form1");
formelt.submit(); // this will submit the form to server
}
Example =>
<button class="btn-test">Btn Test</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
jQuery('.btn-test').click(function() {
js_do_something();
php_do_something();
});
function js_do_something() {
console.log('something done from js');
}
function php_do_something() {
console.log('something done from php');
jQuery.ajax({
type: "POST",
url: 'you_php_file.php',
data: {param: 'btn-test-click'},
success: function () {
console.log('success');
}
});
}
</script>
There you have how to execute a php function with on Onclick.
Execute PHP function with onClick
You can execute a Javascript function assuming you´re using jQuery like this:
jQuery('#id-button').on('click', function(){
// your function body
});

Ajax call to insert to database not working

I'm trying to do an Ajax call on button click to insert to a database through a PHP file. I want to use AJAX to achieve this, but it does not show the alert dialog on success nor does it insert the data to the database. Here is the code I have:
AjaxTest.html:
<button type="button" onclick="create()">Click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function create () {
$.ajax({
url: "AjaxTestRegistration.php",
type: "POST",
data: {
'bid': 10,
'kid': 20
},
success: function (msg) {
alert("!");
}
});
}
</script>
AjaxTestRegistration.php:
<?php
include "connection.php";
include "Coupon.php";
$bid = $_GET['bid'];
$kid = $_GET['kid'];
Coupon::insertCoupon($bid, $kid);
?>
If I try to enter AjaxTestRegistration.php manually in the browser like this: ajaxtestregistration.php?kid=10&bid=5, the row gets inserted into the database.
wWhat could be the problem with this code? How to rectify that?
Your PHP handles GET requests.
$bid = $_GET['bid'];
But your ajax function tries to POST
type: "POST",
The easiest here is to get your data by $_POST in php.
I think you should try $__REQUEST method of php and also use $_POST method if you use post from ajax
$bid = $__REQUEST['bid'];
$kid = $__REQUEST['kid'];

ajax request is successful, but php is not running

I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:
function getObdDescription(){
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if($length == 5){
window.confirm($length);
$.ajax({ url: '/new.php',
data: {action: 'test'},
type: 'post',
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});
}
return false;
}
Here is new.php
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
?>
I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?
This isnt the way it works if you need to alert the text, you should do it at the front-end in your ajax success function, follow KISS (Keep It Simple Stupid) and in the php just echo the text . that is the right way to do it.
You should do this:
function getObdDescription() {
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if ($length == 5) {
window.confirm($length);
$.ajax({
url: '/new.php',
data: {
action: 'test'
},
type: 'post',
success: function (result) //we got the response
{
alert(result);
},
error: function (exception) {
alert('Exception:' + exception);
}
});
}
return false;
}
In your php
<?php
echo 'message successfully sent';
?>
You are exactly right Muhammad. It was not going to work the way I was expecting it. I wasn't really trying to do an Ajax call, but just to get an alert box to pop up; I just wanted confirmation that the call was working, and the PHP was running. Changing the alert('Successfully called'); to alert(result); and reading the text from the php definitely confirmed that the php was running all along.
I want to stay on topic, so will post another topic if that's what's needed, but have a follow-up question. To elaborate a bit more on what I'm trying to do, I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
Now, I know that this function works. I can then access this function in my Javascript with:
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
This is a block loop, and will loop through the block variable set in the php function. This work upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the php runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the html. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
I'm using this conditional and switch to call the function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. It appears that the block variable is not being set.

Calling a php function from Javascript and using a javascript var in the php code

JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !

Categories

Resources