How would I go about doing this? - ajax

First I have my data encoded in the json_encode function.
Looks like this for example:
{"test":"test value"}
What I want to do is make test into a javascript variable where it can hold the data of "test value".

index.php (use json_encode here):
<?php
$foo = array('test' => 'test value');
echo json_encode($foo);
?>
example.html
<script type="text/javascript">
$.get('index.php', function(response) {
alert(response['test']);
// this will alert "test value"
}, 'json');
</script>
EDIT1: example.html (without-jQuery solution):
<script type="text/javascript">
window.onload = function() {
var request;
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "index.php", true);
request.send(null);
}
function sendData() {
if(request.readyState == 4){
var JSONtext = request.responseText;
var JSONobject = JSON.parse(JSONtext);
// notice how variables are used
var output = JSONobject.test;
alert(output); // displays "test value"
}
function getHTTPObject(){
var xmlhttp = false;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
</script>

$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
straight from the jquery docs...

Objects are associative arrays. They store key/values pairs. So All you have to do is:
var test = function(){}
test["hello"] = "world";
This will set hello as a variable and world as its value.
you can test this by doing
alert(test.hello);
Replace hello and world with the json key and value
Hope this help more with this example:
I am using Jquery AJAX to go to index.php resource and return a json object.
index.php
<?php
$variables = array('hello' => 'world');
echo json_encode($variables);
?>
example.html
var test = function(){}
$.ajax({
url: index.php,
success: function(json) {
for(var key in json ){
var testVarName = key;
var testVarValue = json[key];
test[testVarName ] = testVarValue;
}
}
});
So now test object has variable hello and it value is world

Related

esp32 - Ajax get multiple values

I am trying to get multiple values from my ESP32 and display them on a webpage without refresh usign ajax. So far I have found only examples online that update only one vairable (see example below), but how can I update more than one variable?
code from my index.h file:
<script>
setInterval(function() {
// Call a function repetatively with regular interval
getData();
}, 500); //500mSeconds update rate
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ADCValue").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readADC", true);
xhttp.send();
}
</script>
in this sample ADCValue is written with the responsetext, but what if I have multiple values coming in?
In esp32 server you need to response JSON message. Something like this
{"var1": "value1", "var1": "value2"}
Example code in ESP32
// Send headers
client.println("HTTP/1.1 200 OK");
client.println("Content-type: application/json");
client.println();
// Send http body
String var1 = "value1";
String var2 = "value2";
String jresp = "{\"var1\":\""+var1+"\",\"var1\":\""+var2+"\"}";
client.println(jresp);
client.println();
Finally, in your JS code, you can do something like this
xhttp.onreadystatechange = function() {
if (http.readyState == 4) {
try {
var msg = JSON.parse(http.responseText);
var var1 = msg.var1;
var var2 = msg.var2;
// You got 2 values above
} catch (e) {}
}
}

Worpress bad request 400 pure Javascript

I get this following error when I use ajax in pure javascript:
"POST http://localhost:8888/website/wp-admin/admin-ajax.php" 400 (Bad Request) line in code: this.xhr.send(JSON.stringify(data));
my Contact.js file:
var Contact = function(data){
//setups and others methods
this.onFormSent = function(data){
data = {
action: 'my_action',
data: data
};
if(this.ajaxSendURL !== null){
this.xhr.open("post", this.ajaxSendURL);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.onload = function() {
if(self.xhr.status === 200){
console.log(self.xhr.responseText);
var response = JSON.parse(self.xhr.responseText);
self.onSuccessForm(data);
}
};
this.xhr.send(JSON.stringify(data));
}
};
};
I use a form tag in html after filled my "form" and pressed the submit button it should call 'my_action' in php.
this my function.php:
function add_theme_scripts() {
wp_enqueue_script('Contact', get_template_directory_uri() . '/js/Contact.js', array(), 1.0, true);
wp_localize_script('Contact', 'ajaxurl', admin_url('admin-ajax.php'));
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');
/* AJAX */
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action(){
echo 'msg from server:' + $_POST['data']['name'];
die();
}
What am I doing wrong?
Updated: replaced by the following code and it works
this.onFormSent = function(data){
data = "action=my_function&name=" + dada.name;
this.xhr.setRequestHeader("Content-Type", "application/json");
...
}
Change this lines in ajax request;
data = {
action: 'my_action',
data: youdatadata
};
var data = $.param(data);
http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http.send(data);

How to add live data to stacked bar chart

I have a stacked bar chart, which gains data from an api.
It works fine when loaded, and the data is displayed as it should be.
Now I wish to add new data to the chart every ten minutes, calling the same API as when loaded, the chart should refresh asynchronously and he new data and axis label need to be updated as new data is gained.
What I have done so far..
https://plnkr.co/edit/s2Os8UlpSbCWlkNP6wuA?p=preview
var ma = d3.line()
.x(function(d) { return x(parseDate(d.date)); })
.y(function(d) { return y(d.ma); });
If you use jquery, then you can send an AJAX request using the $.ajax function. Make sure you handle the response in the result's done() function, as success is deprecated.
Plain AJAX request example:
HTML:
<!DOCTYPE html>
<html>
<body>
<div id="demo"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadDoc()">Change Content</button>
</body>
</html>
JS:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
Taken from here. If you mastered AJAX requests, then the next step is to write a poller, using setInterval. The first parameter should be a function which sends a request and the second should be the time between two execution in milliseconds (10000 in this case). Or you can use an existing poller. This is one I have implemented:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function Poller(params) {
Initializable.call(this, params);
var that = this;
this.initialize("url", window.location.href);
this.initialize("interval", 5000);
this.initialize("type", "POST");
this.initialize("method", "POST");
this.initialize("data", {});
this.initialize("strict", true);
var defaultFunction = function() {};
this.initialize("done", defaultFunction);
this.initialize("fail", defaultFunction);
this.initialize("always", defaultFunction);
this.isRunning = function() {
return !!params.intervalID;
};
this.run = function() {
if (this.strict && (this.green === false)) {
return;
}
this.green = false;
$.ajax({
url: this.url,
method: this.method,
data: this.data
}).done(function(data, textStatus, jqXHR) {
that.green = true;
that.done(data, textStatus, jqXHR);
}).fail(function(jqXHR, textStatus, errorThrown) {
that.green = true;
that.fail(jqXHR, textStatus, errorThrown);
}).always(function(param1, param2, param3) {
that.green = true;
that.always(param1, param2, param3);
});
};
this.start = function() {
if (!params.intervalID) {
this.run();
params.intervalID = setInterval(this.run.bind(this), this.interval);
}
};
this.stop = function() {
if (!!params.intervalID) {
clearInterval(params.intervalID);
params.intervalID = undefined;
}
};
}

File upload using AnguarJS

I wanted to upload image in an AJAX manner and did so with reference to this Article
What I have done:
Controller:
$scope.uploadImage = function () {
var result;
var formdata = new FormData();
var fileInput = document.getElementById('fileInput');
for (var i = 0; i < fileInput.files.length; i++) {
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Common/Image_upload?imageType=' + $scope.imageType);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
};
View:
<form id="uploader" ng-submit="uploadImage()">
<input id="fileInput" type="file">
<input type="submit" value="Upload file" />
</form>
MVC Controller:
[HttpPost]
public JsonResult Image_upload(string imageType)
{
....
success = ProductImage_insert(Image);
message = success ? "Image uploaded successfully!" : "Image was not uploaded!";
return Json(message, JsonRequestBehavior.AllowGet);
}
Requirement:
I need to catch this JSON response in the controller, how can I do it?
Thanks in advance.
You can do it in a angular way:
$scope.uploadImage = function () {
var fileInput = document.getElementById('fileInput');
var messageHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' };
messageHeaders['X-File-Name'] = encodeURI(fileInput.files[0].name);
messageHeaders['X-File-Type'] = encodeURI(fileInput.files[0].type);
var fileData = fileInput.files[0];
$http({
url: '/Common/Image_upload',
method: "POST",
data: fileData,
headers: messageHeaders
}).success(function (data, status, headers, config) {
// do what you want with the response
});
}
on the server read Request.InputStream for a file content
[HttpPost]
public virtual ActionResult Image_upload(productType)
{
var xfileName = HttpUtility.UrlDecode(Request.Headers["X-File-Name"]);
var xfileType = HttpUtility.UrlDecode(Request.Headers["X-File-Type"]);
var inputStream = Request.InputStream;
var fileLenght = (int)inputStream.Length;
var bytes = new byte[fileLenght];
Request.InputStream.Read(bytes, 0, fileLenght);
System.IO.File.WriteAllBytes(Server.MapPath("/MyFiles/" + xfileName), bytes);
// return status code 200 or any other data
return new HttpStatusCodeResult(200);
}

Change content of div onclick with Ajax

I want to change the content the div named john to the output from the php file when an image is clicked. I'm sure it's simple but I can't find an example that fits. Here's my code:
function ajaxFunction(){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send(null);
}
html
<img class='cross' src='images/cross.png' onclick="ajaxFunction();">
<div id='john'>john</div>
test.php
<?php echo "hello"; ?>
Looks to me like you've got a syntax error with your javascript. Your trying to get the responseText from xmlhttp but your XMLHttpRequest is stored in ajaxRequest
Try this
function ajaxFunction(){
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
document.getElementById("john").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send();
}
may I suggest for cross browser/version, use:
var ajaxRequest = getXMLHttpRequest();
and then,
function getXMLHttpRequest() {
var re = "nothing";
try {re = new window.XMLHttpRequest();} catch(e1) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.4.0");} catch(e) {};
try {re = new ActiveXObject("Msxml2.XMLHTTP");} catch(e2) {};
try {re = new ActiveXObject("Microsoft.XMLHTTP");} catch(e3) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.3.0");} catch(ex) {};
if (re != "nothing") {return re;}
else {return null;};
};
as well as changing it to
ajaxRequest.responseText();
I've managed to solve it with the code below. This code also returns the ID of the element after getting "hello" from the php file.
<script language="javascript">
function calldislike(str){
if (str==""){
document.getElementById("john").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true);
xmlhttp.send();
}
</script>
<img src='images/cross.png' onclick="calldislike(this.id);" id='3'>
<div id='john'>john</div>
test.php
<?php echo "hello".$_GET["q"]; ?>

Resources