0

Hello I have already search but they often use jquery ajax to pass data from js to PHP(server-side). but for my project it has a bunch of pure js code so I should use raw AJAX to pass data.

For example, if I want to send a variable "Imgname" that value = 13 and want to echo in php page.

this is my try

<script>
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                alert('send to server successfully');
            }
        };
        xmlhttp.open("POST", "test2.php", true);
        xmlhttp.send("Imgname=13");
    }
</script>

in test2.php

<?php
$temp = $_POST['Imgname'];
echo $temp;   /////output should be 13
?>

but error Undefined index: Imgname in C:\xampp\htdocs\test2.php on line 2

Supanat T. Boss
  • 305
  • 4
  • 13
  • 1
    Try `xmlhttp.send({Imgname: 13});` – Blue Nov 03 '16 at 02:34
  • @FrankerZ That won't work. The argument to `send()` has to be a string or FormData. You're thinking of `$.ajax()`, which will convert an object to an encoded string. – Barmar Nov 03 '16 at 02:35
  • @Barmar I pulled it from [here](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send) – Blue Nov 03 '16 at 02:36
  • 1
    Something's wrong there. The **Syntax** section doesn't show a syntax like `send(Object data)`. – Barmar Nov 03 '16 at 02:39

2 Answers2

2

You need to make sure that you're sending the correct content-type:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Blue
  • 22,608
  • 7
  • 62
  • 92
2

Try sending the header:

var http = new XMLHttpRequest();
var url = "test2.php";
var params = "Imgname=13";
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}
http.send(params);
WEBjuju
  • 5,797
  • 4
  • 27
  • 36
  • are you getting any errors in the console in your browser? – WEBjuju Nov 03 '16 at 02:41
  • Yes that alert. but in test2.php page (other page) it cannot echo $_POST['Imgname']; – Supanat T. Boss Nov 03 '16 at 03:13
  • Where is it that you are asking if you need a submit button? If you are loading my x.html, it submits automatically and just displays the **die('
    '.print_r($_POST, 1));** to prove that **Imgname** is truly being sent by the snippet above.
    – WEBjuju Nov 03 '16 at 03:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127237/discussion-between-webjuju-and-tuchawat). – WEBjuju Nov 03 '16 at 03:16