I am sending a JSON object to a PHP file, The PHP does some manipulation and returns a JSON string:
$('button#indexOpener').on('click', function() {
var aUsername = $('input#edUsername').val();
var aPassword = $('input#edPassword').val();
if (($.trim(aUsername) != '') && ($.trim(aPassword) != '')) {
var str = $("#form_login :input").serializeArray();
$.post("<?php echo URL; ?>ajax/checklogin", str, function(data) {
alert(data.edUsername);
});
}
else {
alert('Please insert a valid username and password');
alert("<?php echo URL; ?>/ajax");
}
});
the PHP echoes a JSON object:
echo json_encode($_POST);
but when I try to alert the data with jQuery:
function(data) {
alert(data.edUsername);
}
is displaying the message undefined. I am sure it is something stupid but I cannot see what I am doing wrong, can you help?
I see no dataType set for $.post(). jQuery will try to recognize returned content type, but you need to set correct headers. So, you need to add:
header("Content-Type: application/json");
before echo json_encode, or you should set dataType:"json" in JS code (fourth parameter of $.post()):
$.post("<?php echo URL; ?>ajax/checklogin", str, function(data) {
alert(data.edUsername);
}, "json");
This way, jQuery will know that the data returned is in JSON format and should be parsed. Without it, jQuery will check the Content-Type header and apply parser according to it. Suppose if no custom content type headers set, it will return return data as HTML. Actually, that is a usual string.
If I just alert(data) is returning {"edUsername":"qqq"
"edPassword":"qqq"} but if I alert alert(data.edUsername); I get
"undefined"?
JSON is a regular string which should be parsed on client side. jQuery detects your response as plain text or HTML and does not parse JSON to Javascript object. In case of data being an object, you would get [object Object] in alert window.
I think this should be this way using $.getJSON():
var str = $("#form_login").serialize();
$.getJSON("<?php echo URL; ?>ajax/checklogin", {data:str}, function(data){
alert(data.edUsername);
});
Related
I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>
To try and be as short and sweet, yet as descriptive as possible i am having issues grabbing a PHP Object through Jquery Ajax.
I am a semi-new PHP developer and i have created an object containing some strings and variables as shown here:
calculation.php
$return = new stdClass;
$return->success = true;
$return->errorMessage = "Oops, something went wrong!";
$return->Score = number_format($scoreFromSheet,1);
$return->roi = number_format($roiFromSheet,1);
$return->dvScoreAnalysis = $scoreAnalysis;
$return->className = $className;
$json = json_encode($return);
echo $json;
I have constructed a very crude Ajax call to the PHP file to try to access the json_encoded object. As shown here:
finalPage.php
$(document).ready(function(){
var data;
$.ajax({
dataType: "json",
url: './dvs_calculation/calculation.php',
data: {data:data},
success: function (json) {
alert('working');
console.log(json[0].Score);
},
error: function(xhr, textStatus, errorThrown) {
alert( "Request failed: " + textStatus );
}
});
});
I have echo'd the object to the DOM to display the output of my object, and it looks pretty solid:
$json output
{
"success":true,
"errorMessage":"Oops, something must've gone wrong!",
"Score":"65.5",
"roi":"25.8",
"ScoreAnalysis":"High Deal Viability"
}
When using the Ajax function i receive a parse error and it prints out nothing from the success function. Not sure where i am going wrong. Any help or reference greatly appreciated.
Access the Score value from the json response as
json.Score //gives you the value of Score key from json
Also according to the code provided, you aren't passing anything to the php side as the data variable is just defined
I have this jquery function
function updateStatus(){
$.getJSON("<?php echo $_SESSION['filnavn']; ?>", function(data){
var items = [];
pbvalue = 0;
if(data){
var total = data['total'];
var current = data['current'];
var pbvalue = Math.floor((current / total) * 100);
if(pbvalue>0){
$("#progressbar").progressbar({
value:pbvalue
});
}
}
if(pbvalue < 100){
t = setTimeout("updateStatus()", 500);
}
});
}
Is it possible to get the JSON from a PHP session variable instead of a json file?
As I have understood I can get the session data from the session like this:
//json test
var jsonstr = $_SESSION['json_status'];
//parse json
var data = JSON.parse(jsonstr);
But I do not know how I can do that with out the getJSON function?
You're reading too much into it. .getjson is just a $.ajax() call that EXPECTS to get a json reponse from the server. That's all.
It doesn't matter WHERE PHP gets data from, as long as it spits out json text.
Whether that json text was just retrieved from a file/db, or dynamically generated with json_encode(), as long as the browser receives json text, things will "work".
Your best bet here is to create a php file that can act as the target of getJSON that returns the json from your session.
<?php
session_start();
if (isset($_SESSION["filnavn"])){
echo $_SESSION["filnavn"];
// Or, if the key contains an object instead of a json string, use
// echo json_encode($_SESSION["filavn"]);
} else {
// echo the json you want here if the session variable is not set
echo "{}";
}
?>
Then in your jquery code change the getJSON to this
$.getJSON("/path/to/php/file.php", function(data){...});
I'm still in AJAX stuff since morning so maybe thats the reason why some things does't work as they schould - let's forget about it. To sum up, my problem is coincident with passing HTML via JSON. An example of the PHP code:
$list = "<strong>This is test</strong>";
$response = array('success'=>true, 'src' => $list);
echo json_encode($response);
Basicly that's the main part of the code which is responsible for passing the HTML to AJAX. Now, let's have a look on part of AJAX code:
success: function(output)
{
alert(output);
json = $(output).find(".content").text();
var data = $.parseJSON(json);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
Some of you will ask what am I doing in this part:
json = $(output).find(".content").text();
The answer is: I retrieve the json string from the ".content" box, so when I alert variable "json: i get:
{"success":true,"src":"1. dsfasdfasdffbcvbcvb<\/span>Edytuj<\/span> <\/a>Usu \u0144<\/span><\/div>2. vbnvbnm454t<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div>3. ndfhgndgfhndfhgndfhd<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div><\/div>"}
The problem is that I do not get this HTML... I get only text witout any HTML tags, styles etc...
String which I get, rather than HTML:
"1. dsfasdfasdffbcvbcvbEdytujUsuń2. vbnvbnm454tEdytujUsuń3. ndfhgndgfhndfhgndfhdEdytujUsuń"
Please don't try to look for anything smart or gunius in the above string because u won't - it's only a test string.
Acording to the part of PHP code - in my case I get "This is test" rather than "This is test".
To sum up my question is, how to pass these HTML tags or whole HTML code via json from PHP to AJAX.
I think you're misunderstanding how jQuery.ajax() works. You just need to tell it that dataType: 'json' (meaning that you're expecting JSON output from the server), and it takes care of the rest. You don't need to use jQuery.parseJSON(). The success() method will be given a JavaScript object representing the server response.
success: function(output)
{
// output is a JS object here:
alert(output.success); // true
// ...
},
To get your HTML from that point, you would just access output.src.
You can specify dataType: 'json' in your ajax request and receive an object(i.e. json already parsed) in your success call. eg
$.ajax(url, {
dataType: 'json',
success: function(output)
{
if(output.success == true)
{
obj_a.parents(".row").append(output.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
if you can't change dataType you would call $.parseJSON on output
function(output)
{
alert(output);
var data = $.parseJSON(output);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
I am very new to ajax and jquery, but I came across a code on the web which I am manipulating to suit my needs.
The only problem is that I want to be able to respond to the ajax from PHP.
This ajax POSTS to a php page (email.php).
How can I make the email.php reply back if the message is sent or if message-limit is exceeded (I limit the nr of messages sent per each user)?
In other words, I want ajax to take a 1 or 0 from the php code, and for example:
if(response==1){ alert("message sent"); } else { alert("Limit exceeded"); }
Here is the last part of the code: (If you need the full code just let me know)
var data_string = $('form#ajax_form').serialize();
$.ajax({
type: "POST",
url: "email.php",
data: data_string,
success: function() {
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}//end success function
}) //end ajax call
return false;
})
Thanks
The success function of an $.ajax call receives a parameter, usually called data though that's up to you, containing the response, so:
success: function(data) {
// Use the data
}
(It also receives a couple of other parameters if you want them; more in the docs.)
The data parameter's type will vary depending on the content type of the response your PHP page sends. If it sends HTML, data will be a string containing the HTML markup; if your page sends JSON, the data parameter will be the decoded JSON object; if it's XML, data will be an XML document instance.
You can use 1 or 0 if you like (if you do, I'd probably set the content type to "text/plain"), so:
success: function(data) {
if (data === "1") {
// success
}
else if (data === "0") {
// failure
}
else {
// App error, expected "0" or "1"
}
}
...but when I'm responding to Ajax requests, nine times out of ten I send JSON back (so I set the Content-Type header to application/json), because then if I'm using a library like jQuery that understands JSON, I'll get back a nice orderly object that's easy to work with. I'm not a PHP guy, but I believe you'd set the content type via setContentType and use json_encode to encode the data to send back.
In your case, I'd probably reply with:
{"success": "true"}
or
{"success": "false", "errMessage": "You reached the limit."}
so that the server-side code can dictate what error message I show the user. Then your success function would look like this:
success: function(data) {
var msg;
if (typeof data !== "object") {
// Strange, we should have gotten back an object
msg = "Application error";
}
else if (!data.success) {
// `success` is false or missing, grab the error message
// or a fallback if it's missing
msg = data.errMessage || "Request failed, no error given";
}
if (msg) {
// Show the message -- you can use `alert` or whatever
}
}
You must pass an argument to your "success" function.
success: function(data)
{
if(data == '1')
{
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
}
And in your php file, you should just echo the response you need
if(mail())
{
echo '1';
}
else
{
echo '0';
}
Anything you echo or return in the php file will be sent back to you jquery post. You should check out this page http://api.jquery.com/jQuery.post/ and think about using JSON formatted variables to return so like if you had this in your email script:
echo '{ "reposonse": "1" }';
This pass a variable called response with a value of 1 back to you jquery script. You could then use an if statement how you described.
just have email.php echo a 0 or 1, and then grab the data in the success event of the ajax object as follows...
$.ajax({
url: 'email.php',
success: function(data) {
if (data=="1"){
...
}else{
...
}
}
});
what you do is, you let your ajax file (email.php) print a 1 if successful and a 0 if not (or whatever else you want)
Then, in your success function, you do something like this:
function(data) {
$('form#ajax_form').slideUp('slow').before('');
if(data==1){ alert("message sent"); } else { alert("Limit exceeded"); }
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
So you capture the response in the data var of the function. If you a bigger variety in your output, you can set you dataType to "json" and have your php file print a json_encoded string so that you can access your different variables in your response via for example data.success etc.
PHP can only return to AJAX calls, by its output. An AJAX call to a PHP page is essentially the same as a browser requesting for the page.
If your PHP file was something like,
<?php
echo "1";
?>
You would receive the "1" in your JavaScript success callback,
that is,
success: function(data) {
// here data is "1"
}
As an added note, usually AJAX responses are usually done in JSON format. Therefore, you should format your PHP replies in JSON notation.