简体   繁体   中英

Trying to use AJAX to grab parameter of function and pass to PHP code

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?

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;
?>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM