Get - Request , to display results in Alert() - php

I would like to create an app that will send out a get request, then take the response and display it on the page,
this is part of my learning process, ultimately i would like to have the response be parsed and turned into
elements etc. but for now i am having trouble accessing the information within the response.
How can i alert() any of the results in the response?
the results of the script below ranged from undefined, to [object ojbect]
<script type="text/javascript">
var bbz;
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "MyDomain - its defined and on the web",
success: function(response) {
bbz = response;
alert(bbz.length);
alert(bbz);
alert(bbz[0]);
}
});
</script>

It looks to me like you are expecting a JSON response...
I am assuming this because of the way you are accessing properties of the response object -
bbz = response;
alert(bbz.length);
You'll want to set your dataType to "json".

If you set the dataType property to html, you should be able to simply return HTML.
You set dataType: "jsonp" which attempts to parse a jsonp object out of the data that is to be returned. However, what you really want is the markup that is in the file you are requesting data from. In order to do this, you must state the correct return type, so that the AJAX knows what data to give you, i.e. you tell the AJAX how to parse the data.

Related

Sending multiple variables in ajax

I have the following ajax request:
var value = $.ajax({
type: "POST",
url: "url.php",
data: { $(someform).serialize(), something: test_number },
cache: false,
async: true
}).success(function(data){
alert("success!");
}).error(function() {
console.log("FAILED");
});
But it is logging FAILED although the url is right. What happens is that the page refreshes the page and the php query isn't done. I guess there are no errors within the url... any idea on why this happens?
You are kind of mixing methods to send your POST data. You can't serialize a query strong and then also append additional data to it using javascript object construct. You will likely need to manually append the last data element to the query string like this:
data: $(someform).serialize() + '&something=' + encodeURIComponent(test_number),
Of course there could still be a problem on the server-side script which is causing a non-200 HTTP response code (and triggering error handler). You just need to fix this first, and if you still have a problem, debug the server-side issue.

ajax request is being sent to PHP to do some maintaining, but errors because it doesnt like php tag?

My AJAX request to pings the server, and the URL but returns an error because it doesnt like the '<' as the open tag for the php script.
AJAX script.
$.ajax({
url: "data.php",
type: "POST",
data: JSON.stringify({"data":transaction}),
dataType: "json",
success: function(data, textStatus, jqXHR){
alert("success");
currentProcesses -= 1;
$("<span>").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
},
error: function(jqXHR, textStatus, errorThrown){
alert("error with ajax call "+textStatus+" "+errorThrown);
}
});
php script
<?php
$win = $_POST['data'];
?>
Am I using the wrong flag settings for the AJAX call?
The body of your POST request is encoded as application/json instead of application/x-www-form-urlencoded.
You aren't doing anything to make the request say that the data is encoded in JSON and you aren't doing anything in PHP to try to parse JSON.
As a result, PHP fails to populate $_POST, because the data is in the wrong format.
The solution is: Don't send JSON. Just give the data property an object as its value, and jQuery will serialise it to application/x-www-form-urlencoded data for you.
data: { "data": transaction },
(Assuming that transaction is not a complex data type (like an array or object).
Additionally, the body variable is undefined. You should either use a string (to make it a selector: "body") or pass the body element directly: document.body.
Is it choking on what it's receiveing? Try this...put an id attribute on your span tag, and reference that.
In the page:
<span id="someName">...</span>
In your ajax call:
$("#someName").html(...
Try making the span more unique using class or id like
<span id="output"></span>
and try this.
$("#output").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
}

JS Ajax calling PHP and getting ajax call data

I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)

handing data returned from jquery get request

I have a simple jquery script as follows:
$('a').click(function()
{
//get the id of the song we want to play
var song_id = $(this).attr("id");
//do a get request to get the information about the song
$.get("http://www.site.com/v4/ajax/get_song_info.php", { id: song_id, }, function(data)
{
alert("Data Loaded: " + data);
});
//alert( song_id );
});
I have gotten it to work and it returns several bits of data 'artist' 'title' 'song duration' and so on.
How do I process my 'data' so I can then update my page with each bit. In this case I want to set a series of '' to hold each of the values returned.
Thanks.
Best practice would be to use a JSON encoding.
Whatever server-language you are using, encode your data as JSON object and send it with
the mime-type application/json.
Javascript/jQuery side make a call to .getJSON() which is aquivalent to
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
However, if you are using jQuery 1.4.x, you now have a JSON object in your data variable.
In a previous version you need to explicitly parse the incoming data into a JSON object. For instance
if(window.JSON) data = window.JSON.parse(data);
This will create a valid Javascript Object which you can treat and access like
data.artist
(Of course you need to create such an object structure serverside before sending)

Handling JSON repsonse

I'm doing an AJAX call using jQuery's JSON feature.
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
pop_word_list(json, paging_value);
}
});
}
As you can see, I'm sending the response to another JavaScript function, but what I'd like to do is send the response to PHP. Is this possible, say to directly convert the response into a PHP array (not using JavaScript) and then use PHP to handle the array, etc?
Thanks in advance.
You could perform another Ajax call to the php script in the success function, passing along the JSON data as a POST param.
do this?
js (ajax) -> php (array conver to ajax) -> js (ajax) -> php ?
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
json["paging_value"] = paging_value;
$.post("x.php", json);
}
});
}
The whole idea doesn't stick together at all... but:
If there is a reason to do that - then You want to do the $.post('phpfile.php',json,function(){},'text or whatever type You want in return');
and the whole json object goes to PHP's $_POST[] as suggested above, but I can see NO case where it should be done that way.
If You get that json from some code You can't change and want to use data in php do:
use cURL to get the data from another thing
use json_decode($data,true) to get assoc table of the whole thing
If You don't know what You're doing :)
just pass the object to another function without useless sending stuff back and forth. You might want to do empty AJAX call to trigger the php file, nothing more.

Categories