I need to get some JSON data from and AJAX function in PHP
This is what i've written so far but not sure exactly what to do on the PHP side.
JS:
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(json);
}
PHP:
<?php
if(isset($_POST['json']) ){
$json = $_POST ['json'];
$json_d = json_decode($json);
echo $json . 'hello';
} else {
echo 'error';
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src='ajax.js'></script>
<body>
HELLO THERE THIS IS AN HTML PAGEEEEE
</body>
</html>
Stringify your JSON on the client side.
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(JSON.stringify(json));
}
Decode the JSON from the raw request body.
$json = json_decode(file_get_contents("php://input"));
If you want to use raw post data, to get JSON try:
$json = json_decode(file_get_contents("php://input"));
JS example:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({key:"value", key:"value"}));
Related
I would like to send an array with elements to my laravel controller with vanilla JS, (I don't want to use Jquery). But I can't get it work... I found several solutions on web with trying to make a json object and so on but nothing wanted to work...
This is my code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('sent');
}
};
xhttp.open("GET", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.send(categories);
and my laravel controller:
public function toggleCategory(Request $request, User $user)
{
dd($categories = $request->categories);
$user->categories()->sync(collect($categories));
}
I changed a few things and now it is working!
The working code:
web.php:
Route::post('{user}/togglecategory', 'Site\ProfileController#toggleCategory')->name('toggleCategory');
Javascript code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('send');
}
};
xhttp.open("POST", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
xhttp.send("categories="+categories);
});
Laravel Controller:
public function toggleCategory(Request $request, User $user)
{
$categories = explode(',', $request->categories);
$user->categories()->sync($categories);
}
I am sending two parameters inside the send method to index.php. But the PHP returns an error "Undefined index". echo $_POST['fname'];
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
In order to send form data through Ajax, you have to specify the content type of the request. In you case it will be 'application/x-www-form-urlencoded:
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
So your code will be:
submit.addEventListener("click", function(e){
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result);
}
}
xhr.send("fname=Henry&lname=Ford");
});
I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>
I'm new to Ajax. I'm writing two function in one file called home.php and make an Ajax call to members.php.
My problem is when I send an data with ajax call I fail to get response.
home.php
<script language="javascript" type="text/javascript">
var httpObject=false;
var httpObject1=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
httpObject1 = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
httpObject1 = new ActiveXObject("Microsoft.XMLHttp");
}
function logout(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var response = httpObject.responseText;
if(response == "logout"){
window.location.href="index.php";
}
else{
error.innerHTML = "Sorry, Invalid Login.";
}
}
}
function get_Request_Member_List(type){
var member_Type = type;
var queryString = "?data1=" + member_Type ;
if(httpObject1.readyState == 4 && httpObject1.status == 200){
var response = httpObject1.responseText;
document.getElementById(type).innerHTML = response;
}
}
httpObject.open("GET", "logout.php" ,true);
httpObject.send(null);
httpObject1.open("GET", "members.php"+queryString ,true);
httpObject1.send(null);
</script>
members.php
<?php
echo "hello";
?>
Don't forget to add an onreadystatechange event handler to your XMLHTTPRequest, e.g.:
httpObject.onreadystatechange = logout;
I need to use the xhr.send(VALUE) to send the data in AJAX. How do I get this data in a PHP file?
JS:
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(value);
}
You are just sending a string to the PHP file. You are not sending it as a query string or with a content type, so PHP doesn't populate the $POST array.
You can try to read the raw post data:
$post = file_get_contents('php://input');
echo $post; // hello
Or, if you want PHP to populate $_POST, you need to do some extra steps in your JavaScript.
window.onload = function() {
var value = 'hello';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
// Tell the server you are sending form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Send it as a query string
xhr.send('value='+value);
}
Then in your PHP, you can access $_POST['value'].
echo $_POST['value']; // hello
If you want to see the $_POST variables on the PHP page you can use this code to display them all so you can visually see their keys and values
echo "<pre>";
print_r($_POST);
echo "</pre>";
From there you will know how to use the data in any file. You can do the same thing with $_GET
Try this, replace your xhr.send with
JS
xhr.send('value='+value);
PHP
echo($_POST['value']);