Data not getting passed via Ajax to PHP script - javascript

I'm trying to send the value of a variable number via ajax to a PHP script. But the PHP script is not printing the desired output on opening on a browser. Tried but couldn't find whats wrong here.
Any pointers ?
index.html
<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.open("POST", "index.php", true);
xhr.send(data);
}
</script>
index.php
<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>

Editing my long winded lame answer since you fixed the close curly bracket... but bloodyKnuckles is right you also need something in your 'process' function to take the response from your PHP page and output it... or whatever you want to do. You can basically use the method 'onreadystatechange' in the XMLHttpRequest object and then look for a 'readyState' property value of 4 which means everything is done. Here is a simple example of that just outputting the results to the console (which you can view using developer tools in your browser of choice).
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
}
else if (xhr.readyState == 1 ){
xhr.send(data)
}
};
xhr.open("POST", "ajax-test.php", true);
}
</script>
As you go further you may want to update your PHP page to only update the session when the POST value is there.
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
session_start();
$_SESSION['numb'] = $_POST['num'];
echo $_SESSION['numb'];
}
?>
You can uncomment those ini_set and error_reporting lines to try to figure out what is going on with your PHP script.

This is because you are not sending header information with request...
Append this code
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
after
xhr.open("POST", "index.php", true);

Related

Posting js variables to PHP not running in any method

In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn't echo the variables, but it doesn't.
Full code: https://codeshare.io/ayvK9e
Exact PHP elements (just trying to send normal variables right now as it still won't work"
PHP:
foreach($_POST as $post_var){
echo($post_var);
}
JS:
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText
};
xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");
If $post not work try using input php
$data = json_decode(file_get_contents('php://input'), true);
When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function('text or variable'); IDK how I missed that.
Try using the FormData()
let form = new FormData();
form.append('name', 'dominic');
form.append('message', 'bumbaclaat');
const xhr = new XMLHttpRequest();
xhr.open("POST", "eDBase.php");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
else console.log('error')
};
xhr.send(form);
Comment out the setRequestHeader to test it.
And at PHP
if(isset($_POST['name'])){
echo $_POST['name'];
echo $_POST['message'];
}
else{
echo 'There was a problem';
}

JavaScript Not Returning Data But No Error Either

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>

Ajax call with ONLY javascript (no jquery)

I'm trying to do an ajax call with POST method, but the PHP only return an empty array. What am i doing wrong?
JAVASCRIPT
// ajax call
function makeRequest(){
var http_request = false;
// example data
var fileObjectInfo = 'bla';
var url = 'archivo.php';
if (window.XMLHttpRequest){
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
}else if(window.ActiveXObject){
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if (!http_request) {
console.log('Falla :( No es posible crear una instancia XMLHTTP');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.send(fileObjectInfo);
function alertContents(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
console.log(http_request.responseText);
} else {
console.log('Hubo problemas con la peticiĆ³n.');
}
}
}
}
My php only do: <?php print_r($_POST); ?> (i tried with request too), but always return an emty array. (so the call works but javascrip doesn't send the information, no?)
I get examples code from internet but never works the ajax call with POST method and i don't know why.
thank you in advance for all the help they can lend.
If You request post method you must be pass header data with request like
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", fileObjectInfo.length);
http_request.setRequestHeader("Connection", "close");
put this data before http_request.send(fileObjectInfo);
I hope this will help you
To send a POST request you need a form data object containing key value pairs for PHP to interpret post values
var fileObjectInfo = new FormData();
fileObjectInfo.append("key", "value");
fileObjectInfo.append("name", "prince");
// ajax code
http_request.send(fileObjectInfo);
In PHP then do this
echo $_POST["key"];
echo $_POST["name"];
Be sure to check if the post params exist using isset()

PHP not receiving JSON send by Ajax

I am trying to send some JSON data to a PHP file using Ajax. Here is my JavaScript code:
function updateJSON(){
var xmlhttpa;
if (window.XMLHttpRequest){
xmlhttpa = new XMLHttpRequest();
} else {
xmlhttpa = new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttpa.onreadystatechange = function(){
if (xmlhttpa.readyState==4 && xmlhttpa.status==200){
console.log("Sent")
}
};
xmlhttpa.open("POST", "update.php", true);
xmlhttpa.send("json=" + JSON.stringify(json));
};
And here is the PHP file that processes the request:
<?php
$json = $_POST["json"];
file_put_contents('data.json', $json);
Unfortunately this isn't working. How can I repair my code?
Please, no jQuery.
Thanks!
Also, if you vote down, please tell me why so I can improve this question.
You should add line with setting Content-type when you POST your data.Try this:
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Also :
xmlhttp.send("json=" + encodeURIComponent(JSON.stringify(json)));

AJAX not linking to PHP file

I need to change a session value inside a JavaScript function so I decided to use AJAX. However, the call does not seem to be working. What is wrong?
Index page setting default session value:
session_start();
if( is_null($_SESSION['lang']) ){
$_SESSION['lang'] = 'english';
}
AJAX call on index page:
var request = new XMLHttpRequest();
request.open('GET', 'setlang.php?entry=0', false);
request.send();
The setlang.php file:
$entry = $_GET['entry'];
if($entry == 0){
$_SESSION['lang'] = 'english';
Print_r ($_SESSION);
}else if($entry == 1){
$_SESSION['lang'] = 'japanese';
Print_r ($_SESSION);
}
Nothing is being printed. Does anyone know what is wrong?
You didn't actually have anyway to check the response (unless you omitted some part of your javascript).
Check MDN's XMLHttpRequest's documentation.
var request = new XMLHttpRequest();
request.onload = function() {
alert(this.responseText);
}
request.onerror = function(e) {
alert('Error : ' + e.target.status);
}
request.open('GET', 'setlang.php?entry=0', false);
request.send();
Also make sure you call session_start(); in your php file.
Add this on the top of setlang.php:
session_start();

Categories

Resources