Reputation: 1
I have an HTML input with a function and parmeter set to it like so
<input onclick='myFunc($count)' type='button' value='ClickMe'>;
I also have script references to JQuery and my script file
<script src="jquery.js"></script>
<script src="myscript.js"></script>
Inside my myscript.js file I have the contents as such
function myFunc(x) {
alert(x);
$(document).ready(function() {
$.ajax({
url: "myphp.php",
method: "post",
data: { param1: "x" },
dataType: "text",
success: function(strMessage) {
}
})
})
}
Here is my myphp.php file
<?php
$param1 = $_GET['param1'];
echo $param1;
?>
As you can see in the javascript file, I have alert(x); to test that the function is grabbing the $count variable and so far that is working (the correct value appears in the alert box). However, I want to pass that x parameter to the PHP script but my PHP script won't echo anything, I assume the line where I have param1 is wrong. Any tips?
Upvotes: 0
Views: 95
Reputation: 2386
You are using post method in AJAX but trying to grab the value in $_GET
which is wrong.
In your PHP code, just replace $_GET['param1']
with $_POST['param1']
and it works.
or If you like to use $_GET
in your PHP code then change the method in AJAX or use $.get
. Examples can be found on W3School.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
Upvotes: 0
Reputation: 31
You're making the XHR with POST method
method: "post",
and youre looking for it in the GET array
$_GET['param1']
;
Change either to post or get (keeping in mind your scenario) and you should be good imo.
read more here to know about the different methods of sending http requests: https://www.guru99.com/php-forms-handling.html
Upvotes: 0
Reputation: 895
In your AJAX call you are using a POST method, so in order to catch the variable in PHP you need to access it from $_POST:
<?php
$param1 = $_POST['param1'];
echo $param1;
?>
Upvotes: 1