Passing json results - javascript

I have the following json response:
{"data":[{"series":{"id":"15404","series_code":"TOS","publisher_id":"280","series_short_name":"Tales
of
Suspense","start_year":"1959","end_year":"1968","published":"1959-1968","type_id":"1","no_issues":"99","published_gcd":"January
1959-March 1968","series_long_name":"Tales of Suspense (Marvel
1959-1968)","volume":"1","first_issue":"1","last_issue":"99","comment":"","created_date":"2013-03-24
01:00:00","user_id":"1","last_updated":"2013-03-24
01:00:00","note":"","is_active":"1","wiki_stem":null}}],"error":"boo"}
Here is the ajax call:
$.ajax({
type: 'get',
url: '/series/lookup?year='+json.IssueYear+'&title='+json.Title,
beforeSend: function(xhr) {xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
if (response.error) {
alert(response.error);
console.log(response.error);
}
else {
//console.log(response.content);
alert(response.data[0].series.id);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
I would have thought that this would return the id but it says data is undefined?
alert(response.data[0].series.id)
I must be missing something, any help appreciated.

Need a little bit more information. How are you getting the response back to your code? if this was JQuery, I know that this would work:
$.post("/path/to/script.php", {
var1: 'test',
var2: 'test2'
}, function(response) {
alert(response.data[0].series.id); // This will work here
}, 'json');
That said, this little snippet shows what would work. Without know what your javascript code is, it makes it very near impossible to determine if what you are doing is right or wrong.

Related

jQuery Ajax fails only in Safari but other browsers are working

i have a javascript function to call ajax to write some stuff to database. So far it has worked on chrome and firefox without any problem. However, Safari randomly fails without much clue. (This is tested within localhost)
This is the error :
write failed : {"readyState":0,"status":0,"statusText":"error"}
This is my ajax function :
function writeToDB() {
var data = {
setting: 'some data'
} ;
$.ajax({
type: "POST",
url: 'Admin/write_to_db',
data: {
data:
btoa(unescape(encodeURIComponent(JSON.stringify(data))))
},
success: function(response) {
consoe.log('success');
console.log('response : ' + JSON.stringify(response));
},
error: function(response) {
console.log('write failed : ' +
JSON.stringify(response));
},
complete: function(response) {
console.log('completed');
},
});
}
I simplified the actual function for ease of reading. I have tried many similar responses given for a similar problem but nothing worked. Pls help me with this. Thank You.
Managed to fix the problem.
The above function writeToDB is triggered by a button click. So all that i had to do is add
event.preventDefault()
to the function. That worked!

Passing JavaScript variables to PHP function using AJAX

In my dashboard.php I have a Javascript function that is called based on the user clicking a button. When the button is clicked, it calls a JavaScript function called getTeamMembers and values are passed across to it. The values passed across to this function are then sent to a PHP function (which is also located in dashboard.php).
However I am not getting any success and was hoping that someone could guide me on where I am going wrong. I am a noob when it comes to AJAX so I assume I am making a silly mistake.
I know my function is definitely getting the intended variable data passed to it, after doing a quick window.alert(myVar); within the function.
This is what I have so far:
function getTeamMembers(teamID,lecturer_id) {
var functionName = 'loadTeamMembersChart';
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: { functionName: 'loadTeamMembersChart', teamID: teamID, lecturer_id: lecturer_id },
success: function(){
alert("OK");
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
}
);
}
Before calling the desired php function, I collect the sent varaibles just before my php Dashboard class starts at the top of the file. I plan to pass the variables across once I can be sure that they are actually there.
However, when I click the button, nothing can be echo'd from the sent data.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_POST["teamID"]) && !empty($_POST["lecturer_id"]))
{
$teamID = $_POST['teamID'];
$lecturer_id = $_POST['lecturer_id'];
echo $teamID;
echo " is your teamID";
}
else
{
echo "no teamID supplied";
}
}
you else statement in you success function , and that's not how you set fail callback, try the following and tell us what do you see in the console.
function getTeamMembers(teamID,lecturer_id) {
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: {functionname: 'loadTeamMembersChart', arguments: [teamID, lecturer_id]},
success: function(data) {
console.log(data);
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
});
}
Seems like your function is not returning a success message when getting into the following statement.
if ($result) {
"Awesome, it worked"
}
Please try to add a return before the string.
if ($result) {
return "Awesome, it worked";
}
It can be other factors, but the information you provided is not enough to make any further analysis.

Javascript-POST not working

onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid)
{
alert("test");
$.post('login.php', this.$form.serialize(), function(response) {
// asdasd
}, 'json');
}
}
I get the alert box but the post doesn't seem to work. Is there anything clearly wrong in the above code?
I am using IdealForms.
The request works, there must be an issue in your server side code. Make sure that:
1) login.php exists and it's in the right path.
2) Your PHP script echos JSON. Try a simple test script:
<?php
// login.php
echo json_encode(array('value' => true)); // send as JSON
Then in JavaScript log the response to the console (press F12 or Cmd+Shift+I):
onSubmit: function(invalid, e) {
e.preventDefault();
if(!invalid) {
$.post('login.php', this.$form.serialize(), function(response) {
console.log(response);
}, 'json'); // read as JSON
}
}
The console should output an object {value: true}.
PS: I'm the developer of Ideal Forms.
All you need to do is call JQuery, and use code like this:
$.ajax({
type: "POST",
url: "login.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});

How to handle response of a POST request in jQuery

I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.

No indication jquery ajax call completes

I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};

Categories