How do I call HTML via AJAX - Elgg? - javascript

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();

Related

document.querySelector().getAttribute() didn't get fresh content meta name

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));
}

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

How to Verify Google Recaptcha V3 Response with AJAX

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..

Ajax script only working in Firefox (not working in Chrome, Safari, Edge,...)

this code is working fine in Firefox, but in all other browsers I have tested I get the error "SyntaxError: JSON Parse error: Unexpected EOF" in line if (this.readyState == 4 && this.status == 200). The json-string looks like this:
[{"ID":"1","token":"1234","name":"Test Satio","matno":"11111","reg_date":"2017-10-24 00:00:00","last_active":"2017-10-24 00:00:00","user_id":"25"},{"ID":"3","token":"2232434","name":"Test Satio 2","matno":"44444","reg_date":"2017-10-23 00:00:00","last_active":"0000-00-00 00:00:00","user_id":"25"},{"ID":"5","token":"32233","name":"Test Satio 3","matno":"12","reg_date":"0000-00-00 00:00:00","last_active":"0000-00-00 00:00:00","user_id":"25"}]
JS-Code:
$(document).ready(function postData() {
var id = localStorage.getItem('user-id');
var token = localStorage.getItem('user-token');
var vars = "id=" + id + "&token=" + token;
var hr = new XMLHttpRequest();
var url = "../php/getUsers.php";
hr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { //in this line I get the error
var data = JSON.parse(hr.responseText);
for(var i=0;i<data.length;i++){
var templateData = {
name: data[i].name,
id: data[i].id
};
var id=templateData['id'];
$.get('templates/user.htm', (function (templateData) {
return function(templates) {
var template = $(templates).filter('#user-template').html();
$('#user-container').append(Mustache.render(template, templateData));
}
})(templateData));
}
}
}
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(vars);
});
What do I need to change to get this code working in all browsers?
Thanks, Lukas
I don't think you need to fire off a request for the user template for each user, I think you can do it once and save it.
I've simplified your code a bit and changed your outer ajax to use jquery.
$(document).ready(function postData() {
$.post({
url: "../php/getUsers.php",
data: {
id: localStorage.getItem('user-id'),
token: localStorage.getItem('user-token')
},
dataType: 'JSON',
success: function (data) {
// now get the template
$.get('templates/user.htm', function (templates) {
var template = $(templates).filter('#user-template').html();
// we have the template and userdata array
data.map(function (el) {
return {id: el.id, name: el.name};
}).forEach(function (templateData) {
$('#user-container').append(Mustache.render(template, templateData));
});
});
}
});
});

jQuery/AJAX, retrieving a string that my method returns

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

Categories