im still a beginner in this field i wanted to send the information from the value that I created from javascript to the other file external php or i mean from client-side to server-side as an example i have loop and value stored in 'i' and i wanna send it to php how? i googled and see some ppl say's use ajax method i still don't know it anyway i tried as an experiment like this it actually worked it only prints a value for me in console but idk how to send it to php
var myrequest = new XMLHttpRequest();
myrequest.open('POST','upload.php',true);
xhr.setRequestHeader('Content-Type',"application/x-www-form-urlencoded");
myrequest.onreadystatechange = function() {
myrequest.onload = function() {
console.log(this.responseText);
}
let data = JSON.stringify({'test': 'test'});
myrequest.send(data);
}
in php file i tried as an example to call variable from js $_post['test']
i dunno how but it didn't work
CodePudding user response:
First you need to convert variable "data" to text like this
let data = JSON.stringify({test: 'test'});
In PHP you can use PHP input stream. PHP input stream is basically way to receive raw data. You can access it this way
$data = file_get_contents("php://input");
Now we have stringified JSON in $data variable. To access data that is in $data variable you need to use PHP's json_decode function.
$final_data = json_decode($data);
echo $final_data->test;
This might seem complicated thing to understand. You should read more about data types. In that way you can understand this example so much better. I will link you few things that might help you out in learning.
CodePudding user response:
String(0) means that your PHP has not received your data from Javascript. Reason for that might be that your URL is not written in right way. I recommend using full URL. For example if you have web server set at localhost your URL should be "http://localhost/upload.php".
I made you example code that you can take look at. It has comments that explain you every step that is happening. It might be hard for you to read it and understand it completely but that is okey. I actually did this example for me aswell as I do need to remind myself how to do things. I post you two links to Pastebin that you can try to use together. I post it in comments as I did not find out how to post content from Pastebin to answer.