Send the POST variable in ajax request - javascript

I have the following ajax ,on which im trying to post the dataString as a parameter to the php file.
I have tried putting dataString inside xhr.send(dataString);.But it didnt work out.Is there any way around?
dataString = txCryptData;
var xhr = new XMLHttpRequest();
var params="data="+dataString;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
}
xhr.open('POST', 'tokenize.php', true);
xhr.send();
In the php I tried $_POST['params']; to fetch the value posted by the ajax req

In PHP use this to get the string sent with ajax :
$data = file_get_contents("php://input");
And in JS :
dataString = txCryptData;
var xhr = new XMLHttpRequest();
var params="data="+dataString;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
alert(xhr.responseText);
}
}
xhr.open('POST', 'tokenize.php', true);
xhr.send(params);

$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'youUrl',
data: {
'Joo': 'bar',
'ca$libri': 'no$libri' // $ sign in the parameter name seems unusual, I would avoid it
},
success: function(msg){
alert('Value' + msg);
}
});

xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(params);
You may have to add these lines to your js snippet

Related

Send PHP Variable with Ajax Call

I wrote a PHP application that makes an AJAX call (XMLHttpRequest) and is called every 5 seconds. The page called makes a database query. However, I need a variable from the main page and am unable to find a solution to attach it to the Ajax call.
Using $_GET seems a bit too insecure to me. Is there another way here?
This is my first expierence with ajax so please dont be to hard with me :)
Here is my Ajax Call
const interval = setInterval(function() {
loadText() }, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.'&name='.$_SESSION['name'].'&org='.$_SESSION['org'];?>', true);
xhr.onload = function() {
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText; }
})
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
// console.log(xhr);
}
Ill hope i provided enough Information
WIsh u all a great weekend
You do not need sending session variables at all: those are already known to the called page, because it can share the session information of the calling page.
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?= $role ?>'
is enough, provided that "table_view.php" issues a session_start() command.
I have fixed your code; It's here:
(Note: \' means that the character ' doesn't closing the string.)
const myInterval = setInterval(function(){loadText();}, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.\'&name=\'.$_SESSION[\'name\'].\'&org=\'.$_SESSION[\'org\']; ?>', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText;
}
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
}

my ajax send post is not working in JS

I have a wordrpess site and I am trying to do an ajax call to send a variable but I cant make it work when I try to retrieve the variable I dont get anything back this is my code:
<script type="text/javascript">
window.onload = function(){
var boton = document.getElementsByClassName("teatro-buy");
const xhr = new XMLHttpRequest();
xhr.onload = function ()
{
console.log(this.responseText);
}
for (let qq = 0; qq < boton.length; qq++)
{
boton[qq].onclick = function()
{
botonid = this.id ;
xhr.open("POST", "ajaxcallnew.php")
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("lol=" + botonid);
console.log(botonid);
}
}
};
</script>
and this is my php
<?php
if(isset($_POST['lol'])){ //check if $_POST['examplePHP'] exists
echo $_POST['lol']; // echo the data
die(); // stop execution of the script.
}
?>
you can var_dump($_POST) or var_dump($_SERVER) or echo 1 ... if it's empty, your request is not arrive php
you can read the server log (such as nginx log, apache log ... almost they exist in runtime folder)
check your format:
examples:
(1) get:
var ajax = new XMLHttpRequest();
ajax.open('get','getStar.php?starName='+name);
ajax.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
(2) post:
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.open('post', '02.post.php' );
xhr.send('name=fox&age=18');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
you must add to your request action property.
For example:
jQuery.ajax({
url: ajaxurl, // ('admin-ajax.php')
method: 'POST',
dataType: 'json',
data: {action: 'yourvalue', fields: info},
success: function (json) {
console.log(json)
});
and on functions.php add the following:
add_action('wp_ajax_nopriv_actionValue', 'FunkName');
add_action("wp_ajax_actionValue", 'FunkName');
function FunkName()
{
//buisness logic
}
Why not use jQuery for this. It would become very simple.
$.ajax({
url:'path_to_php_file.php',
type:'post',
data:{'lol':'value_for_lol'},
onsuccess:function(response){
alert(response);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
https://www.w3schools.com/jquery/default.asp

Chrome extension send selected text to an external API via POST

Here is my popup.js file
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.getElementById("output").innerHTML = selection[0];
});
How do I send selected text along with the url to an external API via POST request?
Following code was able to send POST requests to an external API
popup.js:
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
//document.getElementById("output").innerHTML = selection[0];
var data = "quote=This%20is%20%dope%20feature%20with%20embed%20option";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://localhost:8000/api/excerpt/");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("authorization", "Token 42f2909aeacc293ac3a33a76485821e6399d5e1472");
xhr.send(data);
});

How can i get the ContentType of a ajax request in plain javascript?

I have a script that sends an AJAX request to a server and if the answer is just text it is gonna put it in a div but if its json it should handle it different.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open(method, "/controller.php?url=" + location, true);
xhttp.send(data);
now how can i check if xhttp.responeText is json?
In Javascript you can can use getResponseHeader('content-type') method to check the content type of returned JSON response
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(this.getResponseHeader('content-type') == 'application/json'){
//do something with the json
}
else{
document.body.innerHTML = xhttp.responseText;
}
}
};
xhttp.open(method, "/controller.php?url=" + location, true);
xhttp.send(data);
In Jquery you can try something like this
$.ajax({
type: "POST",
url: "www.yourURL.com",
data: "data which you want to sent to server",
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('text') > -1) {
//do something
}
if (ct.indexOf('json') > -1) {
// handle json here
}
}
});
Basically it will check the string 'html' or 'json' exist in the response header

my php can't receive the 'post' variabe I am sending via ajax

Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax

Categories