Making Ajax call from javascript - javascript

I have the following jquery ajax call and it works fine in a purely jquery file.
var request = $.ajax({
url: "kscript.jsp",
type: "POST",
data: {st:start, sp:stop},
dataType: "html"
});
request.done(function(msg) {
$("#output").html( msg );
alert("Success!!!"+msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Thereafter I rewrote my code as a javascript, but I am now putting the ajax call directly inside a javascript function. This hasn't worked and I am getting 500 Internal Server Error.
function myAjax(){
var request = $.ajax({
url: "kscript.jsp",
type: "POST",
data: {st:start, sp:stop},
dataType: "html"
});
request.done(function(msg) {
$("#output").html( msg );
alert("Success!!!"+msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
I have also tried this:
function ajaxFunction() {
xmlhttp.open("POST","kscript.jsp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("st=start&sp=stop");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("output").innerHTML=xmlhttp.responseText;
}
}
}
but the same error: 500 Internal Server Error. In all these instances, the error is pointing to kscript.jsp .I have ensured that the URL and spelling is correct but hasn't worked. I would appreciate your suggestion to fix this problem.
here is kscript.jsp
<%
String astart = request.getParameter("start");
String sptimes=request.getParameter("stop");
out.print("<h1> Start is: "+start+" -- Stop is"+stop +"</h1>");
%>

it's looks like a folders structure problem, you shoudl ensure that the relative path is fine, I mean, if you are calling from a js you should point to /jsp/yourJsp.jsp , checkit... by the way, are you using the F12 tools to validate the response from the server ?

i think you are making some mistake to call java script method.so check or have you describe ajaxcall inside javascript tag.

You are trying to access the wrong parameters in jsp.
The error occurs here:
String astart = request.getParameter("start");
the parameters are st and sp, not start and stop.
you need:
String astart = request.getParameter("st");
String sptimes=request.getParameter("sp");
Or, you can change the js to pass the correct parameters:
data: {start:start, stop:stop},

Related

Bing Maps REST - Javascript

I am a beginner with JavaScript and I am facing some issues with parsing JSON and display the data I want to.
When I run the URL manualy in browser I get a correct result back.
The JavaScript code looks like this:
request = "URL"
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
var results = data.resourceSets;
console.log(r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + JSON.stringify(e));
console.log("Error" + e.message);
}
});
}
When I run this code I get no error in the console but I still get an alert via the error function: "status":200,"statusText":"OK"
Why do I get this?
And thats why I cannot get my data displayed, what I am doing wrong?
EDIT
so I was able to make a working code out of it, but I still get messages from SUCCESS and ERROR at the same time and I also get my data back?!
<script>
var request = "URL";
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
console.log("working" + r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + e.message + JSON.stringify(e));
console.log("message: " + e.message);
console.log("readyState: " + e.readyState);
console.log("responseText: "+ e.responseText);
console.log("status: " + e.status);
}
});
}
CallRestService(request, GeocodeCallback);
function GeocodeCallback(results) {
console.log(results.resourceSets[0].resources[0].travelDurationTraffic);
document.getElementById("sec").innerHTML=Math.round((parseFloat(results.resourceSets[0].resources[0].travelDurationTraffic) / 60));
}
</script>
Assuming that you put an actually URL into the request parameter this looks fine. A 200 status means it was successful and this likely called the console from your success function. I know you said you removed it to be sure, but the page could of been cached. If you take a look at the network request you will likely see that it was successful as well. Ifs possible that an error in your success function is occurring and triggering the error function. Have you tried adding break points inside of the two functions?
Here is a blog post that shows how to access the Bing Maps REST services using jQuery and other frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/ It looks like your code is very similar.

how to use ajax in jQuery in javascript

I want to post javascript variable to another php file and I search using Ajax may help.I want to get back the data on another php file by "post" method.But I can't use $.ajax({}) directly inside javascript:
function input() {
$.ajax({
url : 'update_service.php',
type : 'POST',
data : {
name: name,
},
success : function(response) {
alert(response);
}
});
The error message said "unexpected function ajax()". How to fix it?
JQuery Version
$.post( "update_service.php", function( data ) {
alert( "Data Loaded: " + data );
});

Using ajax to post a form to php without refresh

I have this written up for send a few variables to a php script:
$(function() {
$('a[class="removeUnread"]').click(function(){
var markedtopicid = $(this).attr("id");
var sessionvar = \'', $context['session_var'], '\';
var sessionid = \'', $context['session_id'], '\';
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
});
});
});
I think this is the correct way to send post data via ajax, but it doesn't appear to be sending. Was I right to wrap the code in the ready function?
I can tell you right off the bat you should not have a semicolon between quickmod and board in your URL. I'm answering here because i cannot post comments yet. One good tool to use in web development ESPECIALLY with GET and POST requests is googles PostMan app. Its free to use and what it does is it will show you the exact output of any link you send it. So you can try putting the link that you make via javascript into postman and see what errors it spits out.
In this example i'm pretty sure your URL is all kinds of screwed up though. Try this instead...
"index.php?action=quickmod&?board="+$context['current_board']
fyi, i did not test that link so it may not work. If it doesnt work, google some ajax examples and javascript string concatenation. You're string is not suitable for ajax.
is should be like this...
$.ajax({
url :'index.php',
type : 'POST',
data : { sessionvar: sessionid, topics:markedtopicid},
success : function (data) {
},
error : function () {
}
Try handling the error:
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});

Post return values with AJAX?

I am using Code Igniter and I have the following Javascript function in my View. I have tried to echo values such as "error" from my handler function in the controller, but the "success" code is always ran in this function below instead.
Do I use echo or return to respond to the AJAX post? What value do I return for success and failure?
<script>
function removeDatacenter(id)
{
var cfm = confirm("Do you wish to delete this datacenter?");
if (cfm==true)
{
$.ajax({
type: "POST",
url: "<?=base_url()?>datacenters/remove_handler.php",
data: { id: id },
success: function(result)
{
document.location.href = document.URL + "?result=success";
},
error: function(result)
{
document.location.href = document.URL + "?result=failed";
}}
);
}
};
</script>
The success-method runs if the ajax-request was successfully sent to your script. It does not say anything about what the request returned.
If you simply do echo "error"; in your PHP-script, you can check the value in the success-method like this:
success: function(response) {
if (response == "error") {
document.location.href = document.URL + "?result=failed";
}
else {
document.location.href = document.URL + "?result=success";
}
}
Edit: People tend to use json_encode in the PHP-code and decode the json-string to an object in the javascript-code. That way you can send more structured data from your script.
Any text you echo will be seen, by AJAX, as a success. Even if it's the word "error". In order for you to trigger the Javascript error handler, you need to trigger some sort of actual HTTP error. If you're just trying to trigger an error for testing purposes, you could throw an exception in your controller. Or point the AJAX request to a URL that doesn't exist on your server (then you'd get a 404 error).
By the way, the error callback you have in your Javascript is slightly off on the API. It might not matter depending on what you do in the error handler, but here's the full call:
error: function(xmlHttpRequest, textStatus, errorThrown) {
//handle error here
}

Jquery - parse XML received from URL

I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.

Categories

Resources