Values from vanilla JavaScript to PHP using AJAX - javascript

I want to know how to send something to php using ajax and vanilla javascript.
I ask you because I just found jQuery solution.
I know that if I want to recieve something it should looks like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
this.responseText; // This is my response
}
};
xhttp.open("GET", "phpfile.php", true);
xhttp.send();
Someone can explain or send me to solution because I couldn't find anything.

First method
To send data from JavaScript to PHP (or any other script) should be just as you found out:
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(params));
where params is some JavaScript variable. application/json is the datatype for JSON data.
On the PHP side, you were also correct: use JSON_decode() to get a PHP-equivalent to the JavaScript data you sent.
Second method (only for GET requests)
GET data is encoded in the URL, so an alternative way is to encode the data directly into the URL of the PHP script. (Don't do this for sensitive data.)
Javascript:
xhttp.open("GET", "phpfile.php?x=2&y=3&z=4");
PHP:
$x = $_GET["x"];
$y = $_GET["y"];
$z = $_GET["z"];
Because you seemed unclear on how to send multiple variables using the first method:
If you want to send multiple variables, put it into an object or array (because JSON.stringify() only takes one (data) argument, not a comma-separated list of arguments).
// for example, to send the variables x, y, z
var xValue = 2;
var yValue = 3;
var zValue = 4;
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify({ x: xValue, y: yValue, z: zValue }));
PHP:
$data = json_decode($_GET);
echo $data->x; // 2
echo $data->y; // 3
echo $data->z; // 4;
(disclaimer: code is untested; I'm not sure if data is received into the $_GET variable. Use json_decode() on the variable that PHP receives JSON data from.)

Related

Output PHP already encode to json, and send to javascript to be json, not working

I'm do output with json_encode to sending to javascript, with this code.
<?php
include "Connection.php";
$syntax_query = "select * from product";
$thisExecuter = mysqli_query($conn, $syntax_query);
$result = array();
while($row = mysqli_fetch_assoc($thisExecuter)){
array_push(
$result,
array(
"id" => $row["product_id"],
"name" => $row["product_name"]
)
);
}
echo json_encode($result);
?>
so output show like this,
[{"id":"121353568","name":"Baju Casual - Black"},{"id":"556903232","name":"Tas LV - Red"},{"id":"795953280","name":"Sword - Wood"},{"id":"834032960","name":"Scooter - Iron Plate"}]
and code javascript like this
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var obj = this.responseText;
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
so obj.id its not working, output show undifined.
I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.
If Jquery is imported then ignore the steps
Here are steps,
Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
Import the js file in the HTML file in script tag as shown '
Now, this is the ajax example to call the PHP file and to get a response
function showHint() {
//since you have used GET method I have used here GET but You can use POST also here
$.ajax({
url: 'Download.php',
type: 'get',
//if any value you want to pass then uncomment below line
// data: {'name_to_pass':'value'},
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
success: function(res)
{
// open DevTool console to see results
console.log(JSON.parse(res));
}
});
}
Hope this will help you out, thank you
Maybe you need a JSON.parse in the response, something like JSON.parse(this.responseText).
And also I can see the result is an Array so you will need to iterate obj
obj.forEach(item => {
document.getElement("txtHint").innerHTML = item.id;
});
you should define the response type as json
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
**var obj = this.responseText;**
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
When you get the responseText it's text, not an object.
var obj = this.responseText; should be let obj = JSON.parse(this.responseText);
Then you can access obj.id as a property.

XMLHttpRequest - Which format does request.send(data) expect for data?

I have to use a XMLHttpRequest, but I don't know which data format is expected by the function request.send(). I searched for too long now.
I tried to pass a JSON object but it does not work:
var request = new XMLHttpRequest();
request.open("GET","fileApi");
var data = {
action: "read",
targetFile: "testFile"
};
request.addEventListener('load', function() {
if (request.status >= 200 && request.status < 300) {
$("#messageOutput").html(request.responseText);
} else {
console.warn(request.statusText, request.responseText);
}
});
request.send(data);
I get updateFile:155 XHR finished loading: GET "http://localhost/cut/public/fileApi".
But no data is received on the server. I made this simple check to approve this:
PHP (server side):
$action = filter_input(INPUT_GET, "action");
$targetFile = filter_input(INPUT_GET, "targetFile");
echo ("action = '$action' | targetFile = '$targetFile'");
exit();
Returns: action = '' | targetFile = ''
Unfortunatelly I can't use jQuery in my application, since the target is a C# Webbrowser (Internet Explorer) and it detects errors in the jQuery file and stops my scripts from working...
I don't know which data format is expected by the function request.send()
It can take a variety of formats. A string or a FormData object is most common. It will, in part, depend on what the server is expecting.
I tried to pass a JSON object
That's a JavaScript object, not a JSON object.
request.open("GET","fileApi");
You are making a GET request. GET requests should not have a request body, so you shouldn't pass any data to send() at all.
GET requests expect data to be encoded in the query string of the URL.
var data = {
action: "read",
targetFile: "testFile"
};
var searchParams = new URLSearchParams();
Object.keys(data).forEach((key) => searchParams.set(key, data[key]));
var url = "fileApi?" + searchParams;
console.log(url);
// and then…
// request.open("GET", url);
// request.send();
Warning: URLSearchParams is new and has limited browser support. Finding a library to generate a query string is left as a (simple) exercise to any reader who wants compatibility with older browsers.

send url with parameters using ajax

I want to send a url with parameters using ajax following is the data I want to sent http://sample-domain.com/send-email.php?pid=3224&act=report but it sends only http://sample-domain.com/send-email.php
Following is my ajax code
<script>
window.addEventListener("load", function(){
var x=document.getElementsByTagName("a");
for(var i=0; i<x.length; i++){
x[i].addEventListener("click", nextlocation);
};
});
function nextlocation(evt){
var y = String(this.getAttribute("href"));
alert(y);
httpRequest = new XMLHttpRequest();
httpRequest.open('POST', 'setnext.php');
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('next='+y);
};
</script>
and in setnext.php
<?php
session_start();
$_SESSION['next']=$_POST['next'];
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
You've said that you are encoding the data using the application/x-www-form-urlencoded format.
But here:
httpRequest.send('next='+y);
You are just putting an = between the key and the value without taking into consideration any of the other rules for application/x-www-form-urlencoded data.
One of those rules is that & separates key=value pairs … and you have a & in your data.
You have to encode your data properly.
httpRequest.send('next=' + encodeURIComponent(y));

xmlHttpRequest AJAX POST Reading the Posted value in MVC Controller

Been struggling to find a solution to this one, despite the mass of useful information out there.
I have the following Javascript Function that is sending an AJAX call to my controller.
var ajax = new XMLHttpRequest();
var posts = document.getElementsByClassName('postLink');
var sendstr = "";
for (var i = 0; i < posts.length; i++) {
sendstr += ',';
sendstr += posts[i].attributes.getNamedItem('onmouseup').value.substr(9, 1);
}
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
var posts = JSON.parse(ajax.responseText);
addPostToList(posts.Title, posts.Description, posts.postID);
}
}
ajax.open('POST', '#Url.Action("SAR", "posts")', true);
ajax.setRequestHeader('Content-type', 'text/plain');
ajax.setRequestHeader('Content-length', sendstr.length);
ajax.setRequestHeader('Connection', 'close');
ajax.send(encodeURIComponent(sendstr));
The controller is as follows...
[HttpPost]
public ActionResult SAR(string r)
{
var s = Request.QueryString[0];
return Content(Post.JSONSerialize());
}
I have tried a number of different Data types as the Parameter and have still not received anything of use... I have also tried Request.Param, request.queryString, request.Form and a number of other 'solutions' that i have found on the web, it is passing only a comma seperated list of integers to the controller, stored as a string. How do i read this value when it has been sent off to the controller?
~I do not want a JQuery or JS Framework solution, i would like a native Javascript solution.
1.- Use JSON as your content-type.
2.- The string you are sending back has to match the parameter name you are expecting on your controller.
change your sendstr to the following format:
//Where r is the name of your parameter on the controller.
var sendstr = '{"r":"STRING YOU WANT TO RETURN"}';
then change your ajax configuration to be
ajax.open('POST', '#Url.Action("SAR","Controller")', true);
ajax.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
ajax.setRequestHeader('Content-Length', sendstr.length);
ajax.send(sendstr);
I hope this works for you :)

Send an array with ajax request to php

I have a js function GetTableData() that gets an array like this. [rowindex,[value1,value2,value3...]]. I want to send over these array using Ajax POST to a php script or url. This time, its not variables that are being sent over but its a function GetTableData() that holds the array of values. How do I go about this as no data is being sent.
<script language="JavaScript" type="text/javascript">
function ajax_post() {
var hr = new XMLHttpRequest();
vars = function GetTableData;// This is my problem
hr.open("POST", "destination.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.table_attendance == 200) {
}
}
hr.send(vars); // Actually execute the request
document.getElementById("resultsdiv").innerHTML = "processing...";
}
</script>
HTML code here
<input type="button" value="Post using Ajax" onClick="javascript:ajax_post() );" />
As Marc B also points out:
var vars = GetTableData();
This will only work if GetTableData is defined in a higher scope than the current function and is accessible to that function.
Also make sure GetTableData "returns" the data; so your function:
function GetTableData()
{
return [rowindex,[value1,value2,value3..]];
}
Besides you have to call your GetTableData as vars = GetTableData();, you have to encode your request data:
hr.send("tableData=" + encodeURIComponent(JSON.stringify(vars)));
We do 2 encodings
encodeURIComponent Mandatory, required to be sent by POST with application/x-www-form-urlencoded
JSON.stringify Optional (can be another encoding method). Has to be an encoding method that your backend cand decode. JSON is a great one and almost a standard
Then, parse it (decode) in the backend. For example in PHP
$tableData = json_decode($_POST['tableData'])
Hope this helps. Cheers

Categories