Ajax query not working - javascript

I have spent some time looking at examples of Ajax, sending a variable to PHP and getting back a different variable. This is from another page (how to get variables from php using AJAX) but it seems something is not working for me. I do not get an error, just no actions appear to happen. My goal is to simply post some data to the php page and get variables back and put them in different DIVs.
htmlpage.html
<html>
<head>
<script>
$(document).ready(function() {
$("#ajaxButton").click(function() {
$.ajax({
url:'phppage.php',
data:{username: $('#username').val()},
type:'POST',
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
</head>
<body>
<input type="text" name="username" id="username"/>
<input type="button" value="Find" id="ajaxButton"/>
<div id="result">This should change on click</div>
</body>
</html>
phppage.php
<?php
$_POST['username'];
$username = $_POST['username'];
$result = '<div class="result">' .$username. "</div>";
echo $result;
?>

It is the whole scripts of yours? If it is, I think that you don't import the jquery in your frontend scripts
Please add the jquery in your code, for example :
<script src="http://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>

Related

Parse HTML input value to php over javascript file

I have the following scenario running:
graph.html --> uses ChartJS to display a line graph and imports graph.js
<html>
<head>
<title>ChartJS - LineGraph</title>
</head>
<body>
<div class="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<form name="form" action="" method="get">
<input type="text" name="input" id="subject" value="">
</form>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/graph.js"></script>
</body>
graph.js --> makes a AJAX call on the graph.php file to get the data and format it.
$(document).ready(function(){
$.ajax({
url : "/graph.php",
type : "GET",
success : function(data){
console.log(data);
...
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
graph.php --> Calls mysql database to get data
$var = $_GET['input'];
$query = sprintf("SELECT $var FROM wetter");
//execute query
$result = $mysqli->query($query);
I like to change the SELECT statement in the php-file by entering a new SELECT-statement in a input field of the .html file. If I put the normal $_GET[] method into the .php it will not find the input value from the .html file.
How can I parse the input value from the .html to the .php when there is a Javascript file in between?
Do I need to change something in my scenario?
From the code you've shown, it doesn't look like you're passing the input value along with your ajax request, you should add something like
$.ajax({
url : "/graph.php",
type : "GET",
data : {input : $('#subject').val()}, <-- added this
success : function(data){
In order to be able to see the value in $_GET['input'] on the php side.
But there is another issue I believe, your ajax request is sent as soon as your document is ready ($(document).ready(function(){), but at that time your input is most likely going to be empty. You probably want to change it to $('form[name="form"]').on('submit',function(event){event.preventDefault(); ...}), assuming your form only does that one thing (display a graph according to the input)

Turn PHP variable into Javascript variable and use that Javascript variable as an argument in a Javascript function

An input from a form in my index.php page is sent to my search.php page. This input is turned into the PHP variable $q with $_GET. How do I turn this PHP variable into a Javascript variable that is a string? Then how do I pass this string as an argument in a Javascript function in the body tag when the page loads? The onload function only works if the first parameter is a string. Here is my simplified code:
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(*PHP variable turned into Javascript string*, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Javascript within your script tag 'should' be ignored if there's a src for it. However you can't have precompiled php in a js file. One option is to set the javascript variables within your php files, then separately include your js files. If your js files make use of those variables, make sure to set the variables first:
<script type="text/javascript">
var q = "<?php echo $q;?>";
</script>
<script src="assets/js/script.js"></script>
The script doesn't work because you're trying to include an external JavaScript file, while also using the same tag for inline script.
This part
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
Should look something like this
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
Fully fixed code
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(q, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Edit: Footnote
As #dossy points out, you should avoid directly passing user input into the HTML code. Use json_encode() to avoid any malicious code or invalid input.
<script>
var q = <?php echo json_encode($q); ?>;
</script>
This is what json_encode() is for. Other answers that use the naive approach of var x = "<?php echo $var; ?>"; will break if $var contains a double quote, for example.
This is the safest way of doing this:
<script type="text/javascript">
var q = <?php echo json_encode($q); ?>;
</script>

How to convert JavaScript variable into PHP through ajax

its the code for posting a javascript variable into php...
but its not working..sugesstion...
i want to take value of id from javascript and post into a php.
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("form").submit(function() {
var id = $("input[type=submit]").attr('id');
alert(id);
$.ajax({
type: 'post',
url:('abcde.php')
data: {id1: id},success: function(response){}
alert(id1);
});
});
});
</script>
</head>
<form action="abcde.php" method="POST">
<!-- other form fields -->
<input type="submit" id="a" name="idVal" value="a">
</form>
</body>
</html>
<?php
if(isset($_POST['id']) ){
$id=$_POST['id'];
echo $id;
}
?>
ohh boy, 1st: it's
data: {'id': id}
secondly, your code is really wrong on this part, you are not doing anything in success, and you just randomly put an alert() in, with a variable that doesn't even exist.
So instead of success: function(response){}, it should be success: function(response){alert(response);} and forget about the alert(id1);
Other errors I saw from looking at it quickly: you are submitting your form from AJAX and HTML as well. You should block the default behavior with a function at the beginning of .submit(funcition() {...}. There already is a function for that, but I can't remember.
Lastly, you are sending the form data to the same page you are submitting from. You will get an answer from AJAX with the same page you are looking at. You should extract the php code to a different file and make abcde.php a simple abcde.html file.
One last thing: instead of alerts, you should use Console.log and watch the browser's console for debugging. You will see a bunch of errors, which makes debugging a lot easier.
You should, instead of blindly coding, be more mindful about what is responsible for what. You should be thinking more about the side-effects of you are introducing to your code. This will come with experience, we've all been there. Make sure one 'thing' is only responsible for ONE task.

jQuery AJAX function returning strange output

I'm playing around with AJAX requests to a php file via jQuery, and I'm getting some strange output.
main.php:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<?php
include('main.html');
?>
<script type='text/javascript'>
$('#startButton').click(function() {
$.ajax({
method: "POST",
url: "test.php",
}).done(function(data) {
alert(data);
});
});
</script>
</body>
test.php:
<?php
echo 'Hello';
?>
Instead of alerting 'Hello' on button click, my program alerts the html of main.php. Any idea what's going on?
Figured it out - I'm using GoogleAppEngine and my app.yami file was not configured to direct requests to test.php, as it defaults all requests to main.php, hence the returned html.
Apologies for not stating that I was using GAE - I didn't think it was relevant.
Credit to #Dagon for suggesting that it was a redirecting error which led me to the correct answer.

Call php function on click of a button

I am trying to call a php function on click on a button using Javascript. It does not seem to be working fine.
Is there a better way to call php function on click of a button
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function executeShellScript(clicked)
{
var x="<?php ex(); ?>";
alert(x);
return false;
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
function ex(){
echo "Trying to run shell script from the web browser";
echo "<br>";
$contents = file_get_contents('/var/www/shellscriptphp/helloworld.sh');
echo shell_exec($contents);
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
echo $result;
}
?>
</body>
</html>
You cannot invoke a php function just like the way you have explained above. Because php script executions happen before the source of the webpage is sent to the client browser from the server.
However you can do it via an ajax call in which you invoke a client side side js function onclick of the button and and that function inturn makes an ajax call to a server side page and returns the result back.
example:
Here is a sample code which you may refer. This page makes a POST ajax request to itself and gets the response back. Let me know incase of errors as i havent run it here.
<?php
/** this code handles the post ajax request**/
if(isset($_POST['getAjax'])) {
/* you can do this below settings via your php ini also. no relation with our stuff */
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
/* setting content type as json */
header('Content-Type: application/json');
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
/* making json string with the result from shell script */
echo json_encode(array("result"=>$result));
/* and we are done and exit */
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
function executeShellScript(clicked)
{
//$_SERVER["REQUEST_URI"] is used to refer to the current page as we have the ajax target as this same page
$.post('<?PHP echo $_SERVER["REQUEST_URI"]; ?>',{"getAjax":true}, function(data) {
alert(data['result']);
return false;
});
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
</body>
</html>

Categories