0

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?

2
  • remove the quotes from data: { param1: "x" }, in your javascript and add alert(strMessage); inside of the success: function( strMessage ) { } curly braces. Commented Mar 28, 2019 at 7:03
  • I followed your instructions and removed the alert(x); function underr myFunc() and when I click the button I get an alert but nothing inside the alert. This would mean that either the parameter is not being passed in AJAX and/or PHP? It is kind of hard to test if AJAX is calling the PHP file from within the web browser. Commented Mar 28, 2019 at 7:08

3 Answers 3

1

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;
?>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.