3

Good day.

I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).

I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:

var read = function(id) {
  xmlhttp = new XMLHttpRequest();

  xmlhttp.open("POST", "view.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("id=" + id);
}

In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.

What's the correct way to send the data? Thank you.

Justin Burgard
  • 360
  • 4
  • 16
Ash
  • 498
  • 6
  • 19
  • https://api.jquery.com/jquery.post/ –  Mar 29 '17 at 16:08
  • use for example only jquery and dont mix Xhhtp and ajax for wat you want make life difficult. –  Mar 29 '17 at 16:16
  • @Breakermind jQuery is a lot of overhead if all you need to do is make an AJAX request. – doublesharp Mar 29 '17 at 16:17
  • i dont like ajax :) but i know it can upload images –  Mar 29 '17 at 16:18
  • and I send with ajax only when need upload files –  Mar 29 '17 at 16:20
  • You do realize that jQuery uses `XMLHttpRequest` to make AJAX requests, which is what you are suggesting? – doublesharp Mar 29 '17 at 16:21
  • I only prefers jquery syntax. –  Mar 29 '17 at 16:23
  • @StrayPointer - The JavaScript in your example is correct, it will submit `id` via POST. Can you include the code where you call `read()`? Are you passing in an ID? Can you include your PHP and the exact error message? – doublesharp Mar 29 '17 at 16:23
  • @doublesharp Well a simple test call to read will result in the same error. (For example this: Test). The exact PHP erros is (Notice: Undefined index: id in C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www\view.php on line 13). Line 13 is where I use $_POST['id']. – Ash Mar 29 '17 at 17:03
  • Do you see it in the output of `print_r($_POST)` or `print_r($_REQUEST)`? – doublesharp Mar 29 '17 at 17:25
  • @doublesharp a statement like echo $_POST('id') would cause that error message. But I think I figured my mistake. In the JS function I eventually open (view.php) using a window.open() statement. I figured that the transition to view.php that way was ineffective when I switched the passing method to GET but the URL didn't contain "?id=55". – Ash Mar 29 '17 at 17:40
  • I think I'll settle for window.open("view.php?id=55") and get over with it. – Ash Mar 29 '17 at 17:45
  • That's why I was asking for the output of `print_r($_REQUEST)`, it will echo the full contents of both `$_POST` and `$_GET` in case it is not using the proper method. Again, the code in your example is valid for a `POST`. – doublesharp Mar 29 '17 at 17:47
  • I'll try to find the cause of the issue and post it for anyone facing a similar one in the future. For now I'll just use GET without XMLHTTPRequest. – Ash Mar 29 '17 at 17:56
  • Possible duplicate of [Send POST data using XMLHttpRequest](https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest) – Vaishal Patel Apr 02 '18 at 10:49

2 Answers2

8

Your input is not complete. So I did the full example below that you can follow. I made a function, named readid(id), doing the same thing as you want. Then I call that function from html, when needed.

<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";   
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 || this.status === 200){ 
        console.log(this.responseText); // echo from php
    }       
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>

view.php

<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>
MGZ
  • 121
  • 8
  • it worked var ajax = new XMLHttpRequest(); ajax.onload= success; ajax.onerror = failure; ajax.open("POST", "handle.php", true); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); let data = 'name='+'zeeshan'; ajax.send(data); function success() { if(this.status===200) document.getElementById('demo').innerText = this.responseText; } function failure(exception) { document.getElementById('demo').innerText = exception; } – Zeeshan Mehdi Aug 22 '19 at 16:39
-1
        <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form id="formoid" title="" method="post">
            <div>
                <label class="title">First Name</label>
                <input type="text" id="name" name="name" >
            </div>
            <div>
                <label class="title">Name</label>
                <input type="text" id="name2" name="name2" >
            </div>
            <div>
                <input type="submit" id="submitButton"  name="submitButton" value="Submit">
            </div>
     </form>
    <script type='text/javascript'>
        /* attach a submit handler to the form */
        $("#formoid").submit(function(event) {

          /* stop form from submitting normally */
          event.preventDefault();

          $.ajax({
    type: 'POST',
    data: id,
    url: 'PATH_TO_VIEW.PHP',                        
    success: function(data) {
        //do something 
    },
    error: function(data){
        console.log('Something went wrong.');
    }
});
        });
    </script>

    </body>
    </html> 

Now the data in ajax can be collected numerous e.g. serialized and new FormData(form) to quickly name two.

Vaishal Patel
  • 361
  • 2
  • 24