Decoding Json String From Javascript in PHP - javascript

I have the following json sent (POST) from my javascript to the php
function boardToJSON() {
return JSON.stringify({
"pieces" : gPieces, // gpieces and gdestinations is an array
"destinations" : gDestinations,
"boardSize" : kBoardHeight // boardSize is an integer value 9
});
// Below function is called on Button Click and url contains PATH to the php file.
function makeMove() {
var move;
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
dataType: "json",
async: false,
data: boardToJSON(),
success: function(msg) {
move = msg;
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Unable to connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested URL of HalmaAI not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Data from HalmaAI was not JSON :( Parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
On the server side (in PHP) I am trying to get it like this
$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString);
echo $myJson["boardSize"]; // also tried $myJson.boardSize etc
Issue is that I am unable to decode JSON in PHP. Can someone guide me here please ? Thanks

You should set the contentType property on AJAX request to application/json. This will set proper header on request such that server will not attempt to populate $_POST in favor of you working with the raw input.
function makeMove() {
var move;
$.ajax({
type: 'POST',
url: url,
contentType: "application/json"
dataType: "json",
async: false,
data: boardToJSON(),
success: function(msg) {
move = msg;
}
});
}
Assuming this works, you can access the boardSize property at:
$myJson->boardSize;
The other problem you have is that since you specify dataType: "json" you need to make sure you send back valid JSON, which you currently are not.
This is not valid JSON:
echo $myJson["boardSize"];
This would be (of course this is a trivial example):
$returnObj = new stdClass();
$returnObj->boardSize = $myJson->boardSize;
echo json_encode($returnObj);

If you want decode json to array in PHP, you should set the 2nd argument of json_decode to true.
Example:
$jsonString = file_get_contents("php://input");
$myJson = json_decode($jsonString, true);
echo $myJson["boardSize"];

Related

ajax call throwing not working due to long-script running error in browser

I am using ajax call, and it is throwing "not responding due to a long-script is running" in browser and gives a button to stop script.
the url is coming perfectly and the console.log(4) inside the success function is not even loading, it just hangs.
The issue is happening for certain scenarios only for others it is working. I have even compared the data, there is no change in data structure also.
Please helpme out
$.ajax({
timeout: 3000,
type: "POST",
url: serviceURL,
data: JSON.stringify(apiInput),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
console.log(4);
if (onsuccess !== null) {
onsuccess(data);
}
},
error: function (x, y, z) {
if (onerror !== null) {
onerror(x, y, z);
}
}
});
I am not sure what the onsucces part of your Ajax success method is trying to do here.
Try this and look a the console for the errors
$.ajax({
type: "POST",
url: serviceURL,
data: JSON.stringify(apiInput),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
error: function (x, e) {
if (x.status == 0) {
console.log('You are offline!!\n Please Check Your Network.');
} else if (x.status == 404) {
console.log('Requested URL not found.');
} else if (x.status == 500) {
console.log('Internel Server Error.');
} else if (e == 'parsererror') {
console.log('Error.\nParsing JSON Request failed.');
} else if (e == 'timeout') {
console.log('Request Time out.');
} else {
console.log('Unknow Error.\n' + x.responseText);
}
}
});
I think you were trying to check if the API call was successful or not, the way Ajax works is on the status of the request essentially if the request returns a status of 200 (which means it's ok) then it will hit the success part of the method, if it's an error foe example 404 (cannot find the URL) or 500 (internal server error) then the error part of the function will be hit, then just console.log that data and view it as you need to.

Ajax request not working locally

I have a script where I am doing an Ajax request to the server:
var answers = JSON.stringify(Controller);
$.ajax({
type: "POST",
url: "/utdanningstesten/ws/answers/",
dataType: "json",
contentType : "application/json",
data: answers,
success: function(res){
console.log(res);
if (lang === 'nb') {
window.location.replace("/utdanningstesten/resultPage.php?id="+res);
}
else {
window.location.replace("/utdanningstesten/resultPage.php?id="+res+'&lang='+lang);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.readyState == 4) {
console.log('HTTP error');
}
else if (XMLHttpRequest.readyState == 0) {
console.log('Network error (i.e. connection refused, access denied due to CORS, etc.)');
}
else {
console.log('something weird');
}
}
});
}else{
//$('.btnG').append('<div class="alert">');
blink('.btnG', 6, 150)
}
And this works fine on the live server, when I am trying to test this on the local server, with the local address http://velgriktig.dev:8888 it doesn't work. In the console I get that the request to that endpoint is pending, no errors, just pending forever.I have tried with adding also http://velgriktig.dev:8888 to the endpoint, so that I have the full URL, but that didn't help either, why can't I get this work locally?

Redirect somewhere else upon JSON success?

My Code:
<script>
$('#form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
}
});
return false;
});
</script>
The FORM:
<form id="form" class="center" action="http://localhost/products/index.php?route=checkout/cart/add" method="post">
<input type="text" name="cname">
<input type="hidden" name="product_id" value="51">
<input type="submit">
</form>
When the form presses submit it goes to the action page which is just a JSON success message, what I want to do is redirect to a different page other than the action page, but my code does not seem to be working?
What exactly is wrong with my code, can someone help me fix it?
I would be so grateful if you could help me out, many thanks!
You aren't posting any data which makes a POST fairly useless .
Also you have no error handler either
Try:
$(function(){
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function(){
// do something when request fails - See $.ajax docs
}
})
return false;
});
});
You can used this code for error handling! You also check this question on stackOverflow for redirecting to another page using jQuery/JavaScript:
click here
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
},
});
});
You need to have separate error and success handlerS like below.
In success method you can redirect to other pages/sites (window.location.href = "http://www.EXAMPLE.com";)
var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully, //Separate method for handling success
error: showError //Separate method for handling error
};

jQuery ajax not returning error or success or always

I'm going crazy here... no matter what I do, I don't get ANY console.log or alert, just this error: GET https://externalURL/?callback=jQuery111301768235498533206_1458134520045&_=1458134520046
This is my code, I have left in the commented lines so you can see what I have tried until now. I'm usign jQuery 1.11.1.
var dataa = {
input: {
id : "12",
tripDate : "2016-02-01"
}
};
jQuery.ajax({
//method : "POST",
type : "POST",
url: "https://externalURL/",
//contentType: 'application/json; charset=utf-8',
dataType: "jsonp",
//crossDomain: true,
//data : JSON.stringify(dataa),
//data : dataa,
data : {input:{id:12,tripDate:"2016-02-01"}},
//data : {id:12,tripDate:"2016-02-01"},
//processdata: true,
/*error: function (jqXHR, textStatus, errorThrown) {
console.log('nem' + jqXHR)
},*/
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
},
success : function(r) {
console.log(r);
}
})
.done(function() {
console.log( "success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
Could this be because it's an external url? Would appreciate any help! Thanks!
Try changing dataType: "jsonp" to dataType: "json".
This Article was helpful when I went into the same issue once.
Well, it turns out, that the external URL provided incorrect information for the dataa variable. Thanks everyone for the useful tips!

how to write/update the data in html page depeding upon the json response in ajax jquery

i am working with javascript jquery. I m sending request to the url for getting json response and i want that json response should be displayed in another html page with some good format may be in table or smoother format.then how can i do that.and also i want to update data in my html page depending upon the json response dynamically.so how can i do that.and am working with phonegap then which technology should i use for server side ?
$.ajax({
type: "GET",
url: "url",
data: null,
contentType: "application/json; charset=utf-8",
success: function(data) {
alert("success");
}
}, error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
replace with this code
$.ajax({
type: "GET",
url: "url",
data: null,
contentType: "application/json; charset=utf-8",
success: function(data) {
alert("success");
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
Rather than the alert("sucess") you could use some code like this
myDiv = document.getElementById('htmldiv');
myDiv.innerHTML = "Success";
But basically just dynamically update part of your page. You could also display the responce see below, the result of that will depend on what is the results of the AJAX call.
myDiv.innerHTML = jqXHR.responseText;

Categories

Resources