jquery ajax get return value - javascript

i want to get the 'printed value' of html pages.
i tried below query, but showGetResult() just return 'null value'
but my apache server logs printed i accessed index.php when i try this code.
(index.php just print helloworld)
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"><\script>
<script type="text/javascript">
function showGetResult( name )
{
var result = null;
jQuery.ajax({
url: 'http://localhost/index.php',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
result = data;
}
});
return result;
}
document.write(showGetResult('test'));
</script>

This is the way AJAX works (asynchronously, like the name suggests). The showGetResult function returns before the AJAX call completes. showGetResult will therefore simply return null since that's what you've assigned to result.
Move any code that depends on the result of the AJAX call inside the success callback. Alternatively, you could make the call synchronous, but that's not usually what you want.

I think what you want to do is this.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"><\script>
<script type="text/javascript">
function showGetResult( name )
{
jQuery.ajax({
url: 'http://localhost/index.php',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
}
showGetResult('test');
</script>

AJAX requests are aynchronous by default; you can't return their result in a function, you need to use callbacks. The easiest way to achieve what you want is to put your code that handles your data in your success handler:
success:function(data)
{
alert(data);
result = data;
document.write(showGetResult('test'));
}
Also, don't use document.write.

You have the wrong dataType per the documentation for jQuery.ajax:
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
So you want to use html:
...
dataType: 'html',
...
In addition, as others have said, the ajax request is asynchronous. So you need to restructure your code. For example:
function showGetResult( name )
{
var result = null;
jQuery.ajax({
url: 'http://localhost/index.php',
type: 'get',
dataType: 'html',
success:function(data)
{
alert(data);
result = data;
document.write(result);
}
});
}
showGetResult('test');

You're missing a fundamental point here. The success method is not run when you call showGetResult. It is run asynchronously.
At the point that you put return result; it is still null (because success has not yet been invoked).
What you need to do is have document.write execute after success is invoked. Either like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"><\script>
<script type="text/javascript">
function showGetResult( name )
{
var result = null;
jQuery.ajax({
url: 'http://localhost/index.php',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
return result;
}
//document.write(showGetResult('test'));
showGetResult('test');
</script>
Or with a callback:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"><\script>
<script type="text/javascript">
function showGetResult( name )
{
var result = null;
jQuery.ajax({
url: 'http://localhost/index.php',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
writeToDocument(data);
}
});
}
function writeToDocument(data) {
document.write(data);
}
showGetResult('test');
</script>

Rather than using document.write on what you expect the function to return, the success callback can take care of that for you, like so:
success:function(data) {
document.write(data);
}

jQuery.ajax({
async: false, //add async false
url: 'http://localhost/index.php',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
result = data;
}
});

Related

Ajax success callback call error function always

I have this function getResult()
<script>
function getResult()
{
dataString = "un="+user+"&pw="+password+"&cid="+cid;
$.ajax({
type: "POST",
url: "http://myexamplesite.com",
data: dataString,
crossDomain: true,
cache: false,
success: function(result){
alert(result);
},
error: function(result){
alert(result);
}
});
}
</script>
when i call the function, i am getting the value in background what i want, means this gives me success output but this function always call error function on success call back
I am not sure and even not found what is wrong with this script.
Thanks in advance.

how to use ajax response data in another javascript

I am working with google map.My map data come from php using ajax response.
My ajax code:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
Now I have need to put my response data in my map var location
function initialize() {
var locations = [
//Now here I put my ajax response result
];
How can I do that?
You'll have to refactor your code a little. I'm assuming you call initialize from the success callback.
Pass the locations array as an argument to initialize.
function initialize(locations) { ... }
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
Then you can cut down even more and just do success: initialize, as long as initialize doesn't expect other parameters.
Here is a fiddle with an example using $.when but its for SYNTAX only not making the call
http://jsfiddle.net/2y6689mu/
// Returns a deferred object
function mapData(){ return $.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text'
});
}
// This is the magic where it waits for the data to be resolved
$.when( mapData() ).then( initialize, errorHandler );
EDIT** function already returns a promise so you can just use
mapData().then()
per code-jaff comments
This is done using callbacks, http://recurial.com/programming/understanding-callback-functions-in-javascript/ , here's a link if you want to read up on those. Let's see your current code here:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
console.log(result);
}
});
</script>
As you noticed, the 'result' data is accessible in the success function. So how do you get transport it to another function? You used console.log(result) to print the data to your console. And without realizing it, you almost solved the problem yourself.
Just call the initialize function inside the success function of the ajax call:
<script type="text/javascript">
$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
initialize(result);
}
});
</script>
Is expected dataType response from $.ajax() to mapajax.php call text ?
Try
$(function () {
function initialize(data) {
var locations = [
//Now here I put my ajax response result
];
// "put my ajax response result"
// utilizing `Array.prototype.push()`
locations.push(data);
// do stuff
// with `locations` data, e.g.,
return console.log(JSON.parse(locations));
};
$.ajax({
type: "POST",
url: "mapajax.php",
dataType: 'text',
success: function (result) {
initialize(result);
}
});
});
jsfiddle http://jsfiddle.net/guest271314/maaxoy91/
See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

simple PHP AJAX : How to call a php script

I'm trying to get my javascript function to use ajax to call a php script. The php script will update a MYSQL table but I've tested the PHP script and it works fine.
This is my function:
function rate()
{
$.ajax({
data: '' ,
url: 'update.php',
method: 'GET',
success: function(msg) {
alert(msg);
}
});
}
and the function is called later with:
rate();
The php script doesn't need any information given to it, it just needs to be called, can anyone point out where I'm going wrong.
Just use like in this example:
<script>
function rate() {
$.get("update.php");
}
</script>
If you dont need to pass the data to the PHP page, you can omit 'Data' from the ajax parameters.
<script>
function rate(){
$.ajax({
url: 'update.php',
method: 'POST',
success: function(msg) {
alert(msg);
}
});
}
rate();
</script>
Have you included jquery library
Try this
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
function rate()
{
$.ajax({
data: '' ,
url: 'update.php',
method: 'GET',
success: function(msg) {
alert(msg);
}
});
}
rate();
</script>
Here is an example of how I use the ajax call:
$.ajax({
type: "POST",
url: "page_url",
dataType: 'json',
data: {
'date1' : date1,
'call': 'function_name'
},
beforeSend: function(){
$("#loading").show();
},
success : function(response){
},
complete: function(){
$("#loading").hide();
}
})
and on php part I add:
function function_name($request){
your code here
}
if (!empty($_POST['call'])) {
die($_POST['call']($_POST));
}
i show my all working code, try it:
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.8.2.js"></script>
<script>
function rate() {
$.get("update.php");
}
</script>
</head>
<body>
<button onclick="rate()">Click me</button>
</body>
</html>

Jquery set HTML via ajax

I have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});

How to ensure that code is run when when ajax call is finished?

I'm used to writing ruby where I get data, then I manipulate it, then I display it.
In javascript land, I'm getting some json, on success: manipulate and display.
I want to separate out my code to look like this
$("#uiElement").click(function(){
data = getData();
upDateUi(data);
})
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
return data;
//I don't want to manipulate the ui in this code;
//upDateUi(data)
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}
You can separate the logic that updates the UI from the logic that retrieves the data from the server using a callback pattern:
$("#uiElement").click(function(){
var upDateUi = function(data) {
/* ... logic ... */
};
getData(upDateUi);
})
function getData(callback){
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
callback(data);
},
error: function(req,error){
console.log(error);
}
})
}
For more information on functions and scopes:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
For more information on how I defined the upDateUi function:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Recursion
Hard to tell what your question is, but success is any function, so this:
...
success: function(data){
upDateUi(data);
},
...
Can be equivalently written as:
...
success: upDateUi,
...
Other than that, not sure what you mean by "I don't want to manipulate the ui in this code".
Define a callback, and then in the success method invoke the callback:
$("#uiElement").click(function(){
data = getData(upDateUi);
})
function getData(callback) {
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
if (callback !== undefined) {
callback(data);
}
},
error: function(req,error){
console.log(error);
}
})
}
The only way to do that is to use a synchronous fetch, which waits for the response, but its a bad idea, as no other javascript can run (and in some browsers - nothing can run) until the response is received.
If you really, really, really want it though:
$("#uiElement").click(function(){
data = getData();
upDateUi(data);
})
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
async: false,
success: function(data){
fishes = data;
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}
I'm not shure if is this what you want.
successFunction(data){
//you can do everything here
}
errorFunction(req,error){
console.log(error);
}
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: successFunction,
error: errorFunction
})
return fishes;
}
This code might be good for your needs:
var myData = $.parseJSON($.ajax({
url: "./somewhere",
type: 'get|post',
async: false,
data: { what: "ever" }
}).responseText);
Then you just proceed with whatever you want to do with the results.
$("#uiElement").click(function(){
var myData = $.parseJSON($.ajax({
url: "./somewhere",
type: 'get|post',
async: false,
data: { what: "ever" }
}).responseText);
upDateUi(myData);
})
You should probably get used to event-based programming. Your code could use callbacks:
$("#uiElement").click(function(){
getData(upDateUi); // make sure upDateUi is defined, it will be passed data
})
function getData(callback){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
//I don't want to manipulate the ui in this code;
//upDateUi(data)
callback(data);
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}

Categories