Access array in Javascript - javascript

I cannot seem to understand why I cannot access an array I get send back by PHP.
I send this back when AJAX makes a call: $response['success'] = true;
I do this by echo json_encode($response); in my PHP file.
Now I want to access it in Javascript, but response.success doesnt work, it logs 'undefined' in the console. Now I check the response, and that is this: {"success":false}
But if I check for if(response.success) it always sends back false, because response.success is undefined. Does anyone know what I mean and what is causing this issue?
This is my AJAX call:
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(response) {
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
},
});

The answer by #SZenC is fine, there's a point though about best practices:
The reason jQuery didn't recognize the response as JSON is because the server probably didn't send a Content-type header, so just add to your server-side code a call to -
header('Content-type: text/json');
You won't need the explicit call to JSON.parse in each API call, you'll get better integration with test tools, and your app will be better self-documented for other folks who use/will-use this code (including yourself should your code need some future maintenance).
In any case it is advised also to document the expected input on the client side by either explicitly specifying dataType as json or by making the API call using a shortcut method such as $.getJSON().

Your ajax-call will return a string, you need to decode it with JSON.parse. You'd get something like this then.
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(r) {
var response=JSON.parse(r)
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
}
});

Related

POST request - String parameter is not present

I am using AJAX to send data to server. It works if I put all data to URL, so everything is OK. But when I put all data to "data" in AJAX, server writes - required String parameter is not present. Eventhough I can see all data in requests body (in browser). What might be wrong?
const data = {
firstName: name,
surname: surname,
email: email,
password: pass1,
roles: roles
};
state.search.method("POST", "users", JSON.stringify(data));
method(type_, url_, data_){
$.ajax({
url: proxy + url_,
type: type_,
contentType: "x-www-form-urlencoded",
dataType: "json",
headers: {
'Authorization': 'bearer ' + localStorage.access_token
},
data: data_,
success: function(result){
alert("OK METHOD");
},
error(XMLHttpRequest, textStatus, errorThrown){
alert('Error: ' + errorThrown + ", " + textStatus);
console.log(XMLHttpRequest.status + ' ' +
XMLHttpRequest.statusText);
}
});
}
Maybe the server is trying to read information through query string only, which means you should use GET method instead of a POST submission.
Try changing your method() function like this:
method(type_, url_, data_){
$.ajax({
url: proxy + url_,
type: "get", //Send using GET method
headers: {
'Authorization': 'bearer ' + localStorage.access_token
},
data: data_,
success: function(result){
alert("OK METHOD");
},
error(XMLHttpRequest, textStatus, errorThrown){
alert('Error: ' + errorThrown + ", " + textStatus);
console.log(XMLHttpRequest.status + ' ' +
XMLHttpRequest.statusText);
}
});
}
And then, you call it without the json stringfy like this:
state.search.method("POST", "users", data);
Can't say i am 100% on this answer but i have assumed 2 things here
That you are actually wanting to perform a 'GET' request here instead of post, as you have said you have tried the URL in the browser and then i assume what you mean is you have keyed this into the address bar then that would be a 'GET' request.
What you can use in JQuery is the $.params function to build your query. so then your code may look something like this.
Your Data object
const data = {
firstName: 'name',
surname: 'surname',
email: 'email',
password: 'pass1',
roles: 'roles'
}
Ajax method
let queryString = $.param(data)
let url = 'https://your base url';
$.ajax({
url:url+'?'+queryString, //Building your url for getting the data
method: 'GET',
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus) // You can console.log the other values for debugging
}
});
I think there will be a little work to do to map your values form where you are gettin them into your object and then also into the ajax method.
if you can give me more details about how these are pull together then i can happoly provide an update with more specific information
Hope this helps
NOTE if it is a POST of the data just need to understand what the payload would need to be like.
You are posting JSON:
state.search.method("POST", "users", JSON.stringify(data));
You claim you are posting x-www-form-urlencoded data
contentType: "x-www-form-urlencoded",
If you are trying to post JSON, then send it with the correct Content-Type: application/json
If you are trying to post URL encoded data then:
Send it with the correct Content-Type (it's the default for jQuery so omit the contentType parameter entirely, or get it correct (application/x-www-form-urlencoded).
Send data in that format: state.search.method("POST", "users", data); (jQuery will encode an object in that format by default).
It works if I put all data to URL
If you want to post all the data in the URL, then you should be making a GET request and encoding it properly.
So:
Specify GET and, again, pass an object not a sting of JSON: state.search.method("GET", "users", data); (and jQuery will properly encode the data in the query string).

Ajax HTTP request changes JSON with array in request body

The JSON response body of the HTTP request is being distorted on the server side. It has one key and its element is an array. This is my HTTP request using jQuery ajax:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
When I print JSON.stringify(event_arr) to console, this is what it looks like:
{"results": [{"event_client": "name1","event_date": "date1"}, {"event_client": "name2", "event_date": "date2"}]}
Then, on the server side, here are my various attempts at understanding the response body and playing around with the JSON format:
// returns [object, Object], cannot be passed into JSON.parse
console.log(request.body);
var temp = JSON.stringify(request.body);
var temp2 = JSON.parse(temp);
// prints {"{\"results\":":{"{\"event_name\":\"name1\",\"event_date\":\"date1\"},{\"event_name\":\"name2\",\"event_date\":\"date2\"}":""}}
console.log(temp);
// prints { '{"results":': { '{"event_name":"name1","event_date":"date1"},{"event_name":"name2","event_date":"date2"}': '' } }
console.log(temp2);
The JSON.stringify() that was called in my dbInsert() seems to mess up how the JSON is read, and I don't how to work around this internal formatting error!
You need to set: contentType: "application/json", in your $.ajax({}) function.
Something like this:
function dbInsert(event_arr) {
$.ajax({
url: "http://localhost:5000/insertdata",
type: "POST",
data: JSON.stringify(event_arr),
contentType: "application/json",
success: function(events) {
console.log("TestInsert was successfully executed");
},
error: function(textStatus, errorThrown) {
console.error("The following error occurred: " + textStatus, errorThrown);
}
});
}

slim framework and ajax. '/' character as a parameter

I'm making an ajax call to a Slim framework web service. This is for sending notes to my database.
The problem is that the users can write for example "send 1/2 piece". So when I make the call, the URL throws 404 not found because of the '/' character.
Is there any way to avoid this problem?
notes = 'send 1/2 piece'
$.ajax({
type: 'GET',
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + notes,
dataType: "json", // data type of response
beforeSend: function(xhr, settings){
},
success: function(data){
},
error: function(xhr, status, errorThrown){
errorPopup(errorThrown);
},
complete: function(xhr, status){
}
});
You need to run EncodeURIComponent against notes, only.
Before your ajax call:
notes = 'We have funny characters in here like /es';
encNotes = EncodeURIComponent(notes);
Then, create your url string using the encoded string.
url: 'http://Myserver/orders/notes/' + MyOrder + '/' + encNotes,

Ajax call error with JSON

I am making an ajax call below and getting an error I do not understand. The variable response in the success function looks like
{"status": "complete", "username": "test", "error": "0", "message": ""}
however when I call my three alert functions inside the success function, the first one prints out the value above, but the next two print out undefined. I know the error key exists, however the javascript does not recognize it. As a result my window crashes.
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
alert(response); //prints correct response
alert(response.error); //prints undefined
alert(response["error"]); //prints undefined
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});
Can somone explain what is happening and how to fix this?
This is due to a combination of two factors:
The server is sending the JSON with the wrong content type
You've used the wrong capitalization for overriding it
Consequently, jQuery is interpreting the JSON as (probably) plain text (which is why alerting the value gives you the raw JSON and not [Object object]).
You should fix this by making sure the server sends the JSON with:
Content-Type: application/json
Since it looks like you are using PHP, you can do that with:
header("Content-Type: application/json");
You should also either remove datatype: 'json' or change it to dataType: 'json'.
that because response is not parse as JSON object to do that you can do it like this:
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
var data = jQuery.parseJSON(response); // <---- Here parse it as JSON
alert(data.error);
// Todo with data
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});

PHP not correctly returning JSON for an AJAX call

I have a PHP function that is supposed to return a JSON object to an AJAX call, but instead it is returning a string. Here is the PHP that I am calling from an AJAX call.
<?php
echo json_encode(array("error", 0, "Success!"));
?>
Here is the AJAX call.
$.ajax({
type: "POST",
url: "../api/login.php",
data: { id: username, password: password },
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
When this function returns, I try to access response in the console, and this is what happens
response
> "["error",0,"Success!"]"
response[0]
> "["
If you are expecting an object then specify the dataType:json in the ajax settings. It will also ensure that if there are any invalid JSON being sent from the server, it gets erred out with parse error. Most probably you don't have a content-type (application/json; charset=utf-8) specified in your response header which lets jquery to determine the mime type itself, so specify the dataType ensure that you get an object or an error back(incase of invalid JSON).
$.ajax({
type: "POST",
dataType:'json'
url: "../api/login.php",
data: { id: username, password: password },
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
Your implementation appears to be using jQuery, or some mock-up of jQuery. If it is not using jQuery, I will be happy to share more solutions to your problem.
Add dataType
$.ajax({
dataType: 'json',
type: "POST",
url: "../api/login.php",
data: { id: username, password: password },
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
The problem is that, by default, jQuery expects a string.
var foo = "bar";
foo[1] === "a"; // true
Documentation: jQuery.ajax
add a param in your ajaxcall
$.ajax({
type: "POST",
url: "../api/login.php",
data: { id: username, password: password },
dataType: "json" //-< add this param.
success: function(response) {
alert( "Data Saved: " + response );
$("#login_username").val("");
$("#login_password").val("");
}
});
http://api.jquery.com/jQuery.post/

Categories