I have this function to execute Ajax POST request :
function ajaxPost(url, data, callback) {
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.addEventListener("load", function () {
if (req.status >= 200 && req.status < 400) {
callback(req.responseText);
} else {
console.error(req.status + " " + req.statusText + " " + url);
}
});
req.addEventListener("error", function () {
console.error("Erreur réseau avec l'URL " + url);
});
req.send(data);
}
But with this code, the captcah is never checked :
grecaptcha.ready(function() {
grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
var data = new FormData();
data.set('g-recaptcha-response',token);
ajaxPost("url", data, function(response){
return response;
});
});
});
The script execute ajaxPost() BEFORE grecaptcha.execute().
Thank you for your help !
I'm not sure what you need the callback for? You're already assigning a listener to "load". I think you can directly return req.responseText in that listener.
Just a guess..
Related
I tried to implement codeigniter with $config['csrf_regenerate'] = TRUE;
I create code with combining javascript XMLHttpRequest & Jquery $.ajaxPrefilter.
I make a function for getting new csrf_hash from Codeigniter and append to meta name on HTML head.
At first request everything seems working.
But next request a got message 403 Forbidden because ajax send an old csrf hash.
Please fix my code.
I want before sending a POST request, ajax get new csrf hash form meta name on HTML head.
Sorry for my bad English.
Best Regards,
This is my code
$.ajaxPrefilter(function( options, originalOptions, jqXHR )
{
get_csrf_hash(callback => document.querySelector('meta[name="csrf_hash"]').setAttribute("content", callback) ); // It Work!!.. Get new csrf_hash and update content meta name.
if (options.type.toLowerCase() === "post")
{
options.data = $.param($.extend(originalOptions.data, { csrf_simpeg_v2 : document.querySelector('meta[name="csrf_hash"]').getAttribute("content")})); // Not Work didn't send fresh csrf hash
}
var originalSuccess = options.success;
options.success = function(data)
{
if (originalSuccess != null)
{
originalSuccess(data);
}
}
var originalError = options.error;
options.error = function (jqXHR, textStatus, errorThrown)
{
console.log(jqXHR.status + ' ' + jqXHR.statusText);
if(jqXHR.status == 401 || jqXHR.status == 403)
{
alert(jqXHR.status + ' ' + jqXHR.statusText);
}
else
{
if(originalError != null)
{
originalError();
}
}
};
});
function get_csrf_hash(callback)
{
var url = baseURL + 'login/get_csrf_token';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == XMLHttpRequest.DONE)
{
console.log(xhr.responseText);
return callback(xhr.responseText);
}
}
xhr.open('GET', url, true);
xhr.send(null);
}
$(function () {
});
get_csrf_hash is an asynchronous function, meaning that the JavaScript runtime will not wait for it to finish its task before moving on to executing the next lines. You need to put all the code that depends on the first AJAX request inside the callback:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
get_csrf_hash(callback => {
document.querySelector('meta[name="csrf_hash"]').setAttribute('content', callback);
if (options.type.toLowerCase() === 'post') {
options.data = $.param(
$.extend(originalOptions.data, {
csrf_simpeg_v2: document.querySelector('meta[name="csrf_hash"]').getAttribute('content')
})
);
}
var originalSuccess = options.success;
options.success = function(data) {
if (originalSuccess != null) {
originalSuccess(data);
}
};
var originalError = options.error;
options.error = function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.status + ' ' + jqXHR.statusText);
if (jqXHR.status == 401 || jqXHR.status == 403) {
alert(jqXHR.status + ' ' + jqXHR.statusText);
} else {
if (originalError != null) {
originalError();
}
}
};
});
});
You should look into the Fetch API and Promises. They will greatly simplify writing code like this. Here is the get_csrf_hash re-written using those tools:
function get_csrf_hash(callback) {
fetch('login/get_csrf_token')
.then(res => res.text())
.then(text => callback(text));
}
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
Like the title says: "Uncaught ReferenceError: make_basic_auth is not defined"
I have a sensor that is connected to the app via bluethooth. The app sends the data to the cloud service. I got a link from the cloud service that contains the data in a json format and I have to GET the data from it.
make_basic_auth is a function to authentificate my GET request.
Im new and I dont have a clue what I did wrong.
<html>
<head>
<title>Test</title>
<script src="jquery-3.2.1.min.js"></script>
<script src="Base64Toolkit.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Post</button>
<div id="result" style="color:red"></div>
<script>
function make_base_auth(user, password) {
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
var auth = make_basic_auth('myUSERNAME','myPASSWORD');
var url = 'myURL';
// RAW
xml = new XMLHttpRequest();
xml.setRequestHeader('Authorization', auth);
xml.open('GET',url)
// ExtJS
Ext.Ajax.request({
url : url,
method : 'GET',
headers : { Authorization : auth }
});
// jQuery
$.ajax({
url : url,
method : 'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth);
}
});
function myFunctionPost() {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.withCredentials = true;
xhr.send();
});
};
getJSON('myURL').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
}
</script>
</body>
</html>
Typo:
make_base_auth <- defined
make_basic_auth <- used
I'm trying to call a view in Elgg via AJAX, but nothing works after >>HERE<<
$('.glyphicon-zoom-in').click(function(event) {
$( '.full-image-view' ).css( "color", "red" ).append('<div>Hope this works</div>');
// >>HERE<<
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.view('albums/inline_full_image_view', {
data: {
guid: 123 // querystring
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
$('.full-image-view').append(output);
});
});
Output : Hope this works
What could I be getting wrong?
Thank you all in advance.
UPDATE
inline_full_image_view.php
<?php
echo 'Hello World';
Elgg uses requirejs. Try this:
requirejs(["elgg/Ajax"], function(Ajax) {
var ajax = new Ajax();
//rest of your code!!
});
Otherwise, using native JS.
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('albums/inline_full_image_view'));
xhr.onload = function() {
if (xhr.status === 200) {
alert('User\'s name is ' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
I have this code-behind:
[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public string GetMessage() {
XmlTextReader reader = new XmlTextReader (Global.sAppPath + "/alt/importantMsg.xml");
string message = null;
while (reader.Read()) {
if (reader.IsStartElement ()) {
switch (reader.Name.ToString ()) {
case "Message":
message = reader.ReadString();
break;
}
}
}
return message;
}
And I want to retrieve the message (the string that the code-behind returns) using jQuery. So I have this code:
$(document).ready(function () {
$.get("isoServe.asmx/GetMessage", function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
But this is not working for me. It's like I can't get a hole through. What am I doing wrong?
I also tried this:
$(document).ready(function () {
$.ajax({
url: "isoServe.asmx/GetMessage",
data: "message",
dataType: "json",
success: function (data) {
alert(data);
}
});
});
But this last piece of code, I am very unsure about. How should the "data" be given in this one.
The example below, does work (using xmlhttp). But I want to use jQuery
function getMsg() {
var msg = "";
xmlhttp = gus.tie = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
msg = xmlhttp.responseXML.documentElement.textContent;
alert("Msg: " + msg + ": fra getMsg()");
}
};
xmlhttp.open("GET", "isoServe.asmx/GetMessage", false);
xmlhttp.send();
return msg;
}
Sorry folks, for some reason the referenced file from the url had been deleted. That's why it wouldn't find it. I have a lot of debugging to do it seems, omg. Wish me luck.
Thanks for your time