Javascript web service request not working - javascript

I have a working PHP web service that returns data (if I input the url into the browser I get the results). I need to use Javascript to retrieve this data from my web service, but I'm not too great with Javascript. Based on all the tutorials, examples, and StackOverflow questions and answers I've read this should work, but it doesn't. Please Help!
<script type="text/javascript">
var url = '*working url*';
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
else { document.write('Perhaps your browser does not support xmlhttprequests?'); }
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myObj = eval ( xmlhttp.responseText );
} else {
// wait for the call to complete
}
};
</script>
Also, I need help making sure that I'm calling this correctly. Currently I do it like this, which may be the problem:
<script type="text/javascript">
document.write(myObj);
</script>

I'm aware this doesn't directly answer your question but if you are "not too great" with javascript I would recommend just going straight to jQuery instead of messing with the lower level objects.
It will also help you with cross browser compatibility.
http://jquery.com/
http://api.jquery.com/category/ajax/
However if you have a particularly boring day some time in the future, going back and learning what's going on behind the scenes is always beneficial.
This would be a simple ajax post using jQuery (with a text response):
$.post(
"test.php",
{ postValue1: "hello",
postValue2: "world!" },
function(data){
alert("Success: " + data);
},
"text");
To answer your second question (in comments), the code looks correct but perhaps you're getting a bad response. You can attach additions events onto the ajax call to get additional information.
This code is borrowed and modified from jQuery's site:
http://api.jquery.com/jQuery.post/
I got the function parameter info from:
http://api.jquery.com/jQuery.ajax/
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("example.php", function() {
alert("success");
})
.success(function(data, textStatus, jqXHR) { alert("second success"); })
.error(function(jqXHR, textStatus, errorThrown) { alert("error"); })
.complete(function(jqXHR, textStatus) { alert("complete"); });

Related

ajaxStart() and ajaxStop() functions not getting fired

I am building a Q/A website. When the user clicks on a particular question, he is redirected to the question page where the user can post answers.
Now, the issue is while the user clicks on "Answer" link, few things are processing in the background like updating db, sending mail, etc. I am trying to display a load indicator in the UI but the AJAX function is not getting triggered.
Here is my code:
HTML:
<span id="msg"><img src="ajax-loader.gif"/></span>
<a id="sub-link" href="javascript:void(0)" onclick="loadAnswerList(document.getElementById('user-ans').value,<?php echo $qid; ?>,'<?php echo $posted_by; ?>')">Answer</a>
JS:
$(document).ajaxStart(function () {
$('#msg').show();
}).ajaxStop(function () {
$('#msg').hide();
});
AJAX request
function loadAnswerList(ans,qid,postedBy,page) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ans_container").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page,true);
xmlhttp.send();
}
I also tried adding $(document).ready(function() { .... }); above the ajax but still it is not working. Am I missing anything?
Am using jQuery version 3.2.1
jQuery does not work with the native XMLHttpRequest object. The ajaxStart and ajaxEnd lines you are using deals with their api. So in order to use it, you need to use jQuery's .ajax() or .get() methods.
Thanks for the details.
This is the modified function:
function loadAnswerList(ans,qid,postedBy,page) {
var answer=ans;
var qstnid=qid;
var postby=postedBy;
var pg=page;
var request = $.ajax({
type: "GET",
url: "load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page",
data: {ans: answer, qid: qstn_id, postedBy: postby, page: pg},
dataType: "html"
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Please correct me if am wrong. One more thing - I want to display the response from the php page to a particular div as I have done in my previous ajax request.
document.getElementById("ans_container").innerHTML = this.responseText;
How do I do it here?

Calling JavaScript function after updating table with PHP

I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.
Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.
This is what AJAX request looks like:
function ajax_post(){
if (typeof featureId !== 'undefined') {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "parse_file.php";
var fn = featureId;
var vars = "featureId="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
hilites.destroyFeatures();
featureId = undefined;
}
else {
window.alert("Select polygon first");
}
}
What is the best way to do this? Some examples would really help.
Looking at your code, you simply need to call the function around this part:
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
// CALL YOUR FUNCTION HERE
}
}
The best solution is to use a Promise. However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.
Here is an example using jQuery.
// This is the function you want to call after the script succeeds
function callbackSuccess() {
console.log('Done!');
}
// This is the data you want to submit to the PHP script
var myData = {
hello: "world"
};
// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
callbackSuccess();
});
Add this to the end of your php save-function:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));
Making the call:
$.getJSON('url_to_your_php_file.php', function(data) {
if (data.status == 'SUCCESS') {
console.log('Save complete');
}
else {
console.log('oops, something went wrong!!');
}
});
It's possible to return something like ERROR, this will return:
console.log('oops, something went wrong!!');
You may try the following:
In php you can use return code from sql statement
echo $sqlResult = $conn->query($sqlStatement);
On Javascript, you can try the following
$.ajax({
url: 'file.php',
type: 'POST',
data: {
data1 : data1,
data2: data2
},
success: function(data){
if(data == success_code){
alert("Success")
}
}
Hope this helps!
Completing ajax request without errors does not mean that the data is saved to DB without errors.
Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.
If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.
If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).
Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).
Maby you have to try this:
setTimeout(function(){
//your function here...
}, 500);

xhr does not get invoked from js

i am using phonegap and trying to invoke a xhr POST on click of a button.
my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:
function fetchTags(){
console.log("Fetched url is:" + IMAGE_URL);
//var url = "http://localhost:8080/echo";
var url ="http://localhost:8080/echo";
console.log("#1");
var xhr = new XMLHttpRequest();
console.log("#2");
xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
console.log("#3");
xhr.setRequestHeader("Content-type", "application/json");
console.log("#4");
xhr.open('POST', url, true);
console.log("#5");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response);
}else{
window.alert(xhr.status);
}
};
console.log("#5");
//var msg = "{'message' : '" + IMAGE_URL + "'}";
console.log("sending request");
xhr.send(JSON.stringify({"message" : "my msg"}));
}
Button code:
<button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
The console prints:
Fetched url is:undefined
#1
#2
#3
To clarify i can see first console.log getting printed. but that's it. nothing happens after that.
just for everyone's benefit the issue was not the javascript but invoking from the phonegap using the localhost.
I was unders the assumption that phonegap will be able to access my api at localhost (not sure why had this stupid idea) but yes using the actual ip of the host machine made it work right away.

Execute SOAP xml request

So in my company we use SOAP API to get connect to our system, and I'm pretty well rehearsed in it and can use all the calls.
I just want to know where should I start if I want to build a test landing page that can execute the API queries.
I would prefer to do it with JavaScript if that is possible as we don't have PHP installed on our servers.
Looking for some direction of where to start - I'm simply going to take a value from a text box and place within the XML request and execute it :)
Any pointers appreciated!
<script>
function fireRequest(){
..
//parse your SOAP Request and set the request with 'dataContent'
...
var url = //your target gateway here Java/PHP or your web service recpetor
var postStr =//xml SOAP resquest ;
makeRequest(url, postStr);
}
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest(); //Mozilla, Safari ...
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP"); //IE
} else {
alert("Your Browser does not support XMLHTTP");
}
}
function makeRequest(url, param) {
//If our readystate is either not started or finished, initiate a new request
//clearing all divs
receiveReq = getXmlHttpRequestObject();
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
//Set up the connection to captcha_test.html. True sets the request to asyncronous(default)
receiveReq.open("POST", url, true);
//Set the function that will be called when the XmlHttpRequest objects state changes
receiveReq.onreadystatechange = responseHandler;
//Add HTTP headers to the request
receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
receiveReq.setRequestHeader("Content-length", param.length);
receiveReq.setRequestHeader("Connection", "close");
//Make the request
receiveReq.send(param);
}
}
function responseHandler(){
if (receiveReq.readyState == 4) {
var response = receiveReq.responseText;
if(response){
//do what ever you want with the response XML
}
}
}
</script>
This would be enough for your case. use the methods at your page.

How to refresh a part of a web page using Javascript or using jQuery?

How can I refresh a particular part of a web page with a time interval (not entire page)?
You can use Ajax for your purpose.
suppose you want to check username availability before registering a user to your site.
create a request object asynchronously
function createRequest()
{
try{
request=new XMLHttpRequest();
} catch(tryMS){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
} catch(otherMS){
try{
request=new ActiveXObject("Microsoft.XMLHTTP");
} catch(failed) {
request=null;
}
}
}
return request;
}
Next is the code to send a asynchronous request
function checkAvailability (username) {
request=createRequest();
if(request==null){
alert("Ajax request not possible on your browser");
return;
}
var url="checkAvailability?username="+username;
request.open("GET", url, true);
request.onreadystatechange = showStatus;
request.send(null);
}
Track the response
function showStatus () {
if(request.readyState == 4) {
if(request.status == 200) {
var response = request.responseText;
if(response == 1){
//username available
} else{
//username not available
}
}
}
}
Suppose you have a DIV in your your Web Page that you want to refresh :
<div id="myDiv"> </div>
To refresh it using javascript you just have to select it and change the html code :
document.getElementById("myDiv").innerHtml = "Your new html code to display"
If you want to deal with forms, database queries ...
You have to use AJAX to call some php scripts for example without reloading the current page ...
You are talking about AJAX
Look at http://api.jquery.com/jQuery.ajax/ for jQuery
But please consider learning the underlying javascript language - you will be better for it in the long run
here is a simple example
http://www.degraeve.com/reference/simple-ajax-example.php
The history behind ajax can be found here http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications

Categories

Resources