Read XML from PHP - JQUERY AJAX POST - Not using XMLHTTP - javascript

I got some code off a tutorial a couple of months ago that I am now changing and using in my site. I have already coded alot so do not want to go another route.
Basically I need to retrieve all posts from a database and display on screen dynamically without refreshing the page. now I have the XML that is generated from the PHP file - all is good. Where I am stuck is reading that XML o the ajax side. here is what I have so far:
function getAllPosts() {
alert('hi');
var count = 0;
var tlu = getUrlVars()["user"]; // tlu stands for time line user
var data = 'user='+tlu;
$.ajax({
url: 'getAllPosts.php',
type: 'POST',
data: data,
success: function(response){
var xml = response.responseXML;
var posts = xml.documentElement.getElementsByTagName("post_item");
for (var i = 0; i < posts.length; i++) {
var id = posts[i].getAttribute("id");
var account_name = posts[i].getAttribute("account_name");
var author = posts[i].getAttribute("author");
var type = posts[i].getAttribute("type");
var data = posts[i].getAttribute("data");
var postdate = posts[i].getAttribute("post_date");
categoryPost(id, account_name, author, type, data, postdate);
}
}
});
}
function categoryPost(id, account_name, author, type, data, pastdate){
if(type === 'write'){
alert("hello");
}
}
It is running the alert("hi"); test but not the rest of the code.
My console gives me this: Uncaught TypeError: Cannot read property 'documentElement' of undefined
How can I read the elements from the xml? Everywhere I look has that XMLHTTP stuff and I don't, so I am pretty confused...
Thanks in Advance

If you are expecting an XML response, try setting data type: 'xml'. In your $.ajax parameters. If you're still having issues. Log the response object by using console.log(response) to examine what is actually being returned or you can use Chrome's postman extension. Comes in handy ;-).

Related

How to do a JSON api call with error response?

I use Javascript to retrieve through a JSON api call the amount of active products pasted in a certain filter.
My typicall response would be
{"total":34,"product_ids":["PRODUCT1","PRODUCT2",....."]}
My script is working fine when products are present but when none of the products are active the response will be:
{"error":"No products found, please check request settings"}
In this case the script will crash.
What I tried to do is to set the var NumEdPicks to 0 when I get an error but I don't really know how as the script is crashing when it doesn't find "total".
This is what the retrieve part of the script looks like
// Retrieve
var url = 'http://api.jetlore.com/products/products_by_filter.json?jl_cid=' + clientID + '&filter=' + filterName + '&per_page=' + maxCount + '&page=1';
var response = HTTP.Get(url);
var responseObj = Platform.Function.ParseJSON(response["Content"]);
var NumEditorsPick = responseObj.total;
if(NumEditorsPick>maxCount){ var NumEditorsPick = maxCount;}
I would like to set NumEditorsPick to 0 when I get the error response.
Some things I was thinking about but which isn't working:
var NumEditorsPick = responseObj.total || 0
or
var NumEditorsPick = ‘total’ in responseObj ? responseObj.total : 0
How to define NumEditorsPick when there is no total?
I've tried so far:
if (responseObj.hasOwnProperty('total')){
var NumEditorsPick = responseObj.total;
}else{
var NumEditorsPick = 0;
}
And
if (responseObj.has("total")){var NumEditorsPick = responseObj.total;
}
if (responseObj.has("error")){var NumEditorsPick = 0;
}
Both are crashing the execution of my script, so I'm starting to think that when there is an error response it just stops the script and ignores the rest, would that be possible? In that case, how to ignore this error response?
EDIT:
After using the try/catch method as suggested in the comments, I managed to finally make it work:
var NumEditorsPick;
try {
var response = HTTP.Get(url);
var responseObj = Platform.Function.ParseJSON(response["Content"]);
NumEditorsPick = responseObj.total;
} catch (error) {
NumEditorsPick = 0;
}
You can use Javascript's hasOwnProperty() to check if the parse JSON has the key you're looking for.
In this case, I'd be something like:
var responseObj = Platform.Function.ParseJSON(response["Content"]);
if (responseObj.hasOwnProperty('error')){
// handle error msg
}else{
// do something else
}
Here's a simple example using the JSON input you've provided.
Update
Ok, so my initial answer was based on what you said here:
My script is working fine when products are present but when none of
the products are active the response will be:
{"error":"No products found, please check request settings"}
But the service you're calling does not return a JSON string containing the error. Instead it returns a 404 and therefore, any attempt to parse or use the response content is not valid.
So, to start, you could try wrapping your HTTP.Get(url)in a try/catch method and on the catch clause set the NumEdPicks to zero.
Another option would be to check HTTP.Get() method documentation to see if the response object has a status (e.g: response.Status) or if you can pass a callback function for response and error, like this example in AJAX:
$.ajax({
url: 'yourUrl',
type: 'GET',
success: function(data){
// Set NumEdPicks to total and do other stuff
},
error: function(data) {
// Set NumEdPicks to zero
}
});

Ajax url is undefined

I'm making a function to get a xml file and edit it. I've never done that before so I searched a good way to get an xml file. I decided to use ajax, but the file is never returned because the url is undefined.
EDIT :
I edited the code and made the treatment in the success function. Now there is no problem with this file.
Here is the update of the ajax part :
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
//file = $.parseXML(xml);
// Editing the file to have the good dates
$(xml).find('StartDateTime').text(start);
$(xml).find('EndDateTime').text(end);
var strFile;
if (window.ActiveXObject) {
strFile = xml.xml;
} else {
strFile = (new XMLSerializer()).serializeToString(xml);
}
var encoded64 = Base64.encode(strFile); // Encoded in base64
var encodeURL = encodeURIComponent(encoded64); // Encoded URL
var AR = urlAR + encodeURL; // The URL to open
window.open(AR, '_blank');
}
})
Now all is working well about the xml file, I have a little problem with the window.open, which open my url but with %31 at the beggining, but it's another problem.
Thank you for your help !
file is undefined because you are declaring it inside a ajax success function
function openRecords(start, end) {
// Extraction of the xml file
var file;
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
file = $.parseXML(xml);
},
error: function(ex) {
console.log(ex);
}
})
// Test
var start = '2016-02-15T12:57:00+01:00';
var end = '2019-02-16T13:57:00+01:00';
setTimeout(function(){
// Editing the file to have the good dates
file.find('StartDateTime').text(start);
file.find('EndDateTime').text(end);},1500);
}
Add an error callback:
error: function (ex) {}
Many things can be happening, you will get more info with the error callback. Probably you are querying an incorrect url. Do not trust that undefined upon url, see what returns your jquery ajax function. Maybe you should be querying something like '\files\xxx.xml'.
can you give me a picture of Network in your broswer? I want to know the URL is send or not:
1. F12 open your console
2. select the Network tab
3. refresh the broswer
4. check the request is send or not

How to receive array using AJAX which calls PHP script?

So basically what I'm doing is auto filling a textbox using AJAX to grab information from a PHP script that calls a C function.
This is what I've found in theory: (Assuming receiving only one value)
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response) {
$('#v1').val(response);
});
}, 5000);
});
Now, if this works, which I believe it will. If I receive an array of values, then the input inside of function cannot be response, correct? So what would I have to change it to make it an array?
Just to be clear, my PHP script is using echo to output its information. I'd rather output in such a more "standard" manner as in V1 = 120, V2 = 120, etc. but PHP is new to me and that I am currently researching. Thank you.
EDIT:
Just to make it clearer
Would something like this work?
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
$('#v1').val(response[0]);
$('#v2').val(response[1]);
$('#v3').val(response[2]);
});
}, 5000);
});
Since you echo on PHP side, the response just can be a string.
But if that string if formed as a valid JSON, you will be able to use it like you wish.
So on PHP side, make sure the json format is valid:
$array = [120,340,800];
echo json_encode($array);
Then in JS... You received a string... You have to parse it to make it an array.
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
var responseArray = JSON.parse(response);
$('#v1').val(responseArray[0]);
$('#v2').val(responseArray[1]);
$('#v3').val(responseArray[2]);
});
}, 5000);
});
Per the OP update, you could try something like this to map each item of the array up to its corresponding text box you could do.
$.post(ajaxurl, NULL, function (response) {
for (var i = 0; i < response.length; i++) {
$("#v" + (i + 1)).val(response[i]);
}
});
This would map each index of the array returned from the JSON endpoint, to a corresponding text box.
If the JSON being returned from your endpoint is a valid JSON array, your response variable should already be an array!
Send your array as json:
echo json_encode(array($value1, $value2, $value3));
JS
$.post(ajaxurl, NULL, function (response) {
// selectors in same index order as response array
$('#v1, #v2, #v3').val(function(i){
return response[i];
});
},'json');
The easiest way (for me) to communicate between javascript and PHP is JSON.
So your PHP script have to generate an answer in this format.
PHP code
// At the top of your PHP script add this
// that will tell to your browser to read the response as JSON
header('Content-Type : application/json', true);
// Do your logic to generate a PHP array
echo json_encode($yourArray);
HTML code
<div class="someClass"></div>
Javascript code
var container = $('.someClass');
$.post(ajaxurl, NULL, function (response) {
console.log(response); // for debuging
for (let i = 0; i <= response.length; i++) {
let myItem = response[i];
container.append('<p>' + item + '</p>');
}
});
It's cleanest to generate dynamically the p elements because you don't know how many results your PHP file will return you.
I'm not sure of the javascript code, you maybe will received a json string that you have to transform to a Javascript Array
Before link you javascript to php script, try some call with postman (or others http client) to ensure that your 'webservice' is working as excepted

Better way to pass data to server?

So I am using query strings to pass data from a form to my server. The query strings look like this:
this.$http.post('http://localhost:3000/operation?Stime='+this.Stime+'&Etime='+this.Etime+'&eAMPM='+this.eAMPM+'&sAMPM='+this.sAMPM+'&id='+this.id+'&activity='+this.activity+'&auto_insert='+this.auto_insert+'&yearmonthday='+this.yearmonthday+'&color1='+this.c)
and In my server I have all these variables to store the query's variables:
var color = req.query.color1;
var Stime = req.query.Stime;
var Etime = req.query.Etime;
var sAMPM = req.query.sAMPM;
var eAMPM = req.query.eAMPM;
var id = req.query.id;
var activity = req.query.activity;
var requestAccepted = req.query.requestAccepted;
var yearmonthday = req.query.yearmonthday;
var auto_insert = req.query.auto_insert;
It just seems like a lot of code to just post my variables to the server (It works just fine) but I was wondering if there were some ways I could refactor it/ make it cleaner
Of course there is!
Consider doing some research into the HTTP message body:
A message body is the one which carries the actual HTTP request data (including form data and uploaded, etc.) and HTTP response data from the server ( including files, images, etc.).
In your case, you can change your Angular $http POST request to as follows -
var data = {
Stime: '+this.Stime+',
Etime: '+this.Etime+',
eAMPM: '+this.eAMPM+',
sAMPM: '+this.sAMPM+',
id: '+this.id+',
activity: '+this.activity+',
auto_insert: '+this.auto_insert+',
yearmonthday: '+this.yearmonthday+',
color1: '+this.c+'
}
$http({
method: 'POST',
url: 'http://localhost:3000/operation',
data: JSON.stringify(data)
})

MediaWiki api JSON parsing error in javascript

I am accessing the media wiki api using javascript and returning a JSON, but when parsing/accessing the returned data and inserting the datastr variable into an existing div, I receive undefined. Here is my script code:
$.getJSON("http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images", function(data) {
var datax = $.parseJSON(data);
var datastr = datax.images[2];
console.log(datastr); //prints nothing to the web console
});
The link itself is working appropriately I believe, returning a JSON:
http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images
This may be a problem with either the way I am accessing the API, or just receiving/parsing the JSON.Ultimately, I need the image "001Bulbasaur.png". Thanks!
**Changing datax.images[2] to datax.parse.images[2] returns the same undefined.
Change
var datastr = datax.images[2];
To:
var datastr = datax.parse.images[2];
Update: Seems you are having cross-origin problems, its not making the request. This should work:
$.ajax({
dataType: "jsonp",
url: "http://bulbapedia.bulbagarden.net/w/api.php?action=parse&format=json&page=Bulbasaur_%28Pok%C3%A9mon%29&prop=images",
success: success
});
function success(datax){
var datastr = datax.parse.images[2];
console.log(datastr); //prints 001Bulbasaur.png
}
Fiddle: http://jsfiddle.net/mRU3M/

Categories