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