AJAX GET JSON seems to returns nothing - javascript

I am creating an Android application using Intel XDK and for some reason It seems to work on the emulator but on the mobile it seems to fail. Below are the screenshots of what it looks like on the emulator and on the device.
Both are using the exact same code and are pointed to the correct database and server. Below is the code I'm using, the PHP and JavaScript code.
function getSessionData(callback) {
$.ajax({
url: 'http://sm.script47.net/api/v1/modules/sessionData/sessionData.php',
"type": "GET",
dataType: "json",
async: true,
success: function (data) {
callback(data);
},
error: function (xhr, textStatus, error) {
alert(xhr.statusText);
alert(textStatus);
alert(error);
},
});
}
Then in another file called home.js.
window.onload = function () {
getSessionData(function (data) {
window.token = data.token;
window.userID = data.userID;
window.username = data.username;
window.emailAddress = data.emailAddress;
alert(window.userID);
getElement("userDetails").innerHTML = "Hello <strong> " + window.username + "</strong>"
});
};
Then to get the session data I'm using the below on a PHP server hosted by namecheap (shared hosting).
<?php
session_start();
// I added the code below in the comment block to try and make it work.
/******************************************************/
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
/******************************************************/
$sessionData = array(
"token" => htmlspecialchars(trim($_SESSION['token'])),
"userID" => htmlspecialchars(trim($_SESSION['userID'])),
"username" => htmlspecialchars(trim($_SESSION['username'])),
"emailAddress" => htmlspecialchars(trim($_SESSION['emailAddress']))
);
echo json_encode($sessionData, JSON_PRETTY_PRINT);
I don't know why it won't work or what is causing it to not work which is why I'm not sure what the fix is. I've talked to the namecheap customer support and they said AJAX requests should work, and they do as I use them to login/register but getting the JSON session data on an actual mobile device doesn't seem to work. Also the success/error callback doesn't return anything either.

Related

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.

Ajax and PHP, post request not working

So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});

Using angular.js to send data to a php file

Right so I have a angular function that is sending data to a php file using the http method.The php code I want to process the data and echo it back onto the page to confirm that the php file has processed it. I'm currently getting undefined alerted back to me, surely I should be getting the vaule of email back to me?. Thanks all
I'm following this tutorial https://codeforgeek.com/2014/07/angular-post-request-php/
var request = $http({
method: "post",
url: "functions.php",
data: {
email: $scope.email,
pass: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
//.then occurs once post request has happened
//success callback
request.success(function (response) {
alert(response.data);
},
//error callback
function errorCallback(response) {
// $scope.message = "Sorry, something went wrong";
alert('error');
});
My php code...
//receive data from AJAX request and decode
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$email = $request->email;
#$pass = $request->pass;
echo $email; //this will go back under "data" of angular call.
From the documentation:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
Your code should look like this:
request.then(
function( response ) {
var data = response.data;
console.log( data );
},
function( response ) {
alert('error');
}
);
Now, you need to encode the response from the server in a JSON format, so replace echo $email; with:
echo json_encode( array(
'email' => $email
) );
And you can access the email property from the angularjs $http.success promise callback function (it's the first function inside the then closure) by response.data.email

AJAX error status code 500 internal server error

I have this code:
<a href="#">
<i class="icon-heart" id="icon_heart" value="20"></i>
</a>
var some_value = $("#icon_heart").attr("value");
$('[id=id_heart]').click(function() {
$.ajax({
url: "<?=base_url(); ?>controller/save",
type: "post",
data: { some_value: some_value },
success: function(dat){
alert(dat);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
PHP:
function save()
{
$post = $this->input->post();
$some_value = $post['some_value'];
$dtl['some_field'] = $some_value;
$dtl['date_insert'] = date('Y-m-d H:m:s');
$this->db->insert('resep_like',array_filter($dtl));
$this->db->set('is_like', 'is_like+1',FALSE);
$this->db->where('some_field', $some_value);
$this->db->update('some_table');
echo "success";
}
The insert and update queries is success, but the AJAX response returns error: status code 500 internal server error. Why can that be? It's successful but the result is error, and the echo from PHP is not displayed. How can i handle the response if it success but the AJAX response show error
Dont know if this the best answer or not..
I just solve this problem by change the url: <?=base_url();?>controller/save to url: <?=base_url();?>save.php
I point url of my ajax to my single file of php placed in root of document and not using the ci controller again to do the insert and update queries, then voila its work
If there a better method of this, please let me know it.
Thanks

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.

Categories