PHP variable to JS with JSON - javascript

I am having a very tough time transfering a php variable to javascript through json.
I have debugged it throughly and Ive come to the conclusion that something must be wrong with the javascript code. I am saying this because I output the json encoding in my php and see that I get {"result":"4","success":true}, where 4 is the variable value.
But when I try to get the variable in javascript like this:
$('#add').on('submit',function(){
var that = $(this), contents = that.serialize;
console.log("after serialize");
$.ajax({
url: 'caradded.php',
contentType: 'json',
data : contents,
type: 'post',
success : function(data){
/*
try {
var result = JSON.parse(data);
alert(result);
} catch (e) {
alert("Output is not valid JSON: " + data);
}*/
console.log("result0!! " + data.result);
console.log("result1!! " + data);
try{
localStorage.setItem("storageName",data);
} catch (e) {
alert("couldnt set item: " + data);
}
}
});
/*
error: function (request, error) {
alert(" Can't do because: " + error);
},
*/
//dataType: 'json',
//data: contents,
//So we do not submit data:
//return false;
// console.log(arguments);
});
then I get the following output on submit (a form submission):
result0!! null
result1!! [Object object]
The following is my php json encoding:
header("Content-type:application/json");
echo json_encode(array(
'result' => $GLOBALS['price'],
'success' => true
));
exit();
If I change $GLOBALS['price'] with a string like "test" then it works just fine. Again note that $GLOBALS['price'] outputs a value in my console.
Anyone who has any idea what Im doing wrong?
Thank you very much!
Best regards
William.

Related

Unable to bind data to textbox in ajax success function

[WebMethod]
public static List<SalesInvoiceFinalCalculationEntity> salesInvoiceFinalCalculaiton(string InvoiceNo)
{
List<SalesInvoiceFinalCalculationEntity> list = new List<SalesInvoiceFinalCalculationEntity>();
list = SalesInvoiceManager1.salesInvoiceFinalCalculaiton(InvoiceNo);
return list;
}
Above code returns list of some values which i want to bind to textboxes. I cant understand that why these values are not getting in ajax Success function below:
function salesInvoiceFinalCalculaiton() {
var invoice = {};
var InvoiceNo = $("#txt_InvoiceNo").val();
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/AjaxRequestToServer.aspx/salesInvoiceFinalCalculaiton", //URI
data: "{InvoiceNo:'" + InvoiceNo + "'}",
dataType: "json",
success: function (data) {
//Commented code working Fine
//if (!$.trim(data)) {
// alert("What follows is blank: " + data);
//}
//else {
// alert("What follows is not blank: " + data);
//}
//bootbox.alert("Hi", function (e) { });
//But cannot Bind data in textbox
$('#txtinvoicevalue').val(data.d[0].totalprice);
$('#txtTotalDiscount').val(data.d[0].discountamt);
$('#txtGrandTotal').val(data.d[0].grandtotal);
},
error: function (xhr) {
if (xhr.statusText == "Invalid Request") {
sessionStorage.clear();
}
}
});
}
Here Success function working fine. And Commented code also gives right output. But I cant assign the data to textboxes. Thanks in advance.
try using getElementById instead and see if that helps, also check to see if you can print the values into your debug console.
pressing F12 will usually show you the development console on browsers, check your script errors there.

CakePHP AJAX-Call: An error occured: undefined

I am trying to get some sample ajax app running with cakephp. I started off reading this blogpost: http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/ which I tried to adapt do my architecture.
Now I am stuck here:
When I change the selection of the first select-box, I get an error-alert: undefined.
When I trie to call the AJAX-URL directly in the browser, it actually returns the correct html-content that is supposed to be updated in the second select-box but I see there is an 500 Server-Error also being returned which sais it cannot load the recource http://localhost/favicon.ico. Is that the problem why the ajax-call sais "an error occured"? I don't know why this resource is even called and why it is looking in localhost/ and not the app-folder. Can anybody tell me what I need to do to get the ajax-sample running? This is the JS-Code for the ajax-call:
<script>
$(function() {
$('#countries').change(function() {
var selectedValue = $(this).val();
var targeturl = $(this).attr('rel') + '?id=' + selectedValue;
$.ajax({
type: 'get',
url: targeturl,
beforeSend: function(xhr) {
alert(targeturl);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
},
success: function(response) {
alert(response);
if (response.content) {
alert("content");
$('#provinces').html(response.content);
}
},
error: function(e) {
alert("An error occurred: " + e.responseText.message);
console.log(e);
}
});
});
});
</script>
These are my controller-functions:
public $components = array('Session','RequestHandler');
...
public function chained_dropdowns() {
$countries = $this->TestRun->find('list');
$countryProvinces = array();
foreach ($countries as $key => $value) {
$countryProvinces = $this->TestRun->TestStepRun->find('list',array('conditions'=>array('TestStepRun.test_run_id'=>$key)));
break;
}
$this->set(compact('countries', 'countryProvinces'));
}
public function country_provinces_ajax() {
//$this->request->onlyAllow('ajax');
$id = $this->request->query('id');
if (!$id) {
throw new NotFoundException();
}
//$this->viewClass = 'Tools.Ajax';
//$this->loadModel('Data.TestStepRun');
$countryProvinces = $this->TestRun->TestStepRun->find('list',array('conditions'=>array('TestStepRun.test_run_id'=>$id)));
$this->set(compact('countryProvinces'));
}
}
And I added in my routes.php:
Router::parseExtensions();
Router::setExtensions(array('json'));
[Update]
I just changed the error-output-line to:
alert("An error occurred: " + e.responseText);
Now, I get as error-message: "An error occured: <option value="">..."
This is the data from the json-view, which should be passed to the success-function. I just don't know, why it throws an error.
could it be, that it's rather a problem with your jQuery-request configuration?
Maybe try to add
dataType:"html",
in your $.ajax configuration.
to solve the issue. Normally CakePHP just outputs what you enter into your .ctp - file.
If you don't define json there, you will not get any object (regardless of what the console sais).

jQuery 1.8 ajax call returns null although post response has value

I'm having problems with the return value of a jQuery ajax call. I can debug the whole thing server side and I know everything is working correctly and the return value is properly being calculated. I can look under the NET tab in FireBug and see that the response is:
{"d":false}
But when I test the value in the Success function of the ajax call, msg is NULL. Why?
Here's the ajax call:
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (msg) {
alert(msg); // for debugging
if (msg)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (msg) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
Other, similarly structured client-side calls work fine. This is a same-domain request.
try changing the name of the variable to something other than msg. I think that might be a message box or something similar. Try
function GetStateCertifiable(areaID) {
$.ajax({
url: "../WebServices/AoP.asmx/GetStateCertifiable",
data: '{"AreaID":"' + areaID + '"}',
dataType: 'json',
success: function (result) {
alert(result); // for debugging
if (result)
$("#isCertified").slideDown("fast");
else
$("#isCertified").slideUp("fast");
},
error: function (result) {
alert("An error occured. \nStatus: " + result.status
+ "\nStatus Text: " + result.statusText
+ "\nError Result: " + result);
},
complete: function () {
}
});
};
It turns out the problem was that my web service (../WebServices/AoP.asmx/GetStateCertifiable) returned a bool and from the post response, I know that was properly sent back to the client. Ajax, however, didn't like that. Once I changed the web service to return the strings "true" or "false", everything worked.
Does jQuery ajax only work for strings or is there something I should have done to prepare the msg object to receive a bool?

Function called by jQuery Form Plugin's beforeSubmit not returning value

The beforeSubmit function in my jQuery Form plugin needs to check whether the selected file already exists on the server. Here's that relevant code:
$('#frmSermonUpload').ajaxForm({
beforeSubmit: function() {
// Reset errors and clear messages
ClearForm(false);
var formValid = true,
fileExists = CheckFileExists();
console.log('beforeSubmit fileExists: ' + fileExists);
if (fileExists === 'true') {
$('#uploadedFile').addClass('inputError');
$('#fileErrorMsg').append(' A file with that name already exists on the server.');
formValid = false;
} else {
if (!ValidateUploadForm()) {
formValid = false;
}
}
console.log('formValid: ' + formValid);
if (!formValid) {
return false;
}
},
...
Here's the CheckFileExists() function:
function CheckFileExists() {
var fileName = $('#uploadedFile').val().replace(/C:\\fakepath\\/i, ''),
dataString;
dataString = 'checkFileExists=' + fileName;
console.log('fileName: ' + fileName);
console.log('dataString: ' + dataString);
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
return 'true';
} else {
return 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
//console.log('Current value of returnResult: ' + returnResult);
//return returnResult;
}
As you can see I'm using console output to check what's going on. In the CheckFileExists() function, fileName and dataString are being reported correctly. On the PHP side, I know that the POST data is getting there due to some logging I've got going on there.
Here's the PHP code that uses the POST data:
if (isset($_POST['checkFileExists']) && $_POST['checkFileExists'] !== '') {
$log->lwrite('**Checking if file exists.**');
$fileToCheck = $targetPath . $_POST['checkFileExists'];
$log->lwrite('file_exists: ' . file_exists($fileToCheck));
if (file_exists($fileToCheck)) {
echo 'existsTrue';
} else {
echo 'existsFalse';
}
}
What's happening is, in the console, the line console.log('beforeSubmit fileExists: ' + fileExists); is returning "undefined" (beforeSubmit fileExists: undefined).
Here's all of the console output for an upload where the file already exists, so the beforeSubmit should be stopped:
fileName: 042913sermon.mp3
dataString; checkFileExists=042913sermon.mp3
beforeSubmit fileExists: undefined
formValid: true
serverResult: existsTrue
It must be significant that the serverResult line is displaying after everything else. Does that have to do with how long the ajax call takes? If so, is there a way to delay the rest of the script until the ajax call is done executing?
UPDATE
As aorlando pointed out, the order of the console output signified that I needed to add async: false to my $.ajax call. After doing so, the console output was correct, but the function CheckFileExists() is still getting reported as undefined in beforeSubmit.
Ok. Now the problem is the scope of return.
If you use "async: false" you can return in this way (not so elegant)
var returnValue='';
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
returnValue = 'true';
} else {
returnValue= 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
return returnValue;
You must declare a var returnValue out of the scope of the ajax call. Inside the ajax function you can modify the value of returnValue;
This is a solution which use closure, a quite complex javascript feature. Further read something about scope of a variable in javascript: What is the scope of variables in JavaScript?
This is not a very nice solution; is better if you call a function inside "success" function of ajax call as my previous example.
That's all folks!
You are using an AJAX async call.
Your method CheckFileExists()n return a value before the ajax call complete.
So the simplest solutions is to use:
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false ...
if you want to use async call (the default as you can see: http://api.jquery.com/jQuery.ajax/
you must call (for ex.) a postcall function in the success function of the ajax call:
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
postFn('true');
} else {
postFn('false');
}
}, ...
Be carefull with the scope of the postFn
funcion postFn(_result){
console.log(_result);
}
I hope to be clear.
That's all folks!

Undefined Value in AJAX

I had a function below which stores distances from two locations using google maps api. those results are stored in volunteerDist and there is a defined jid array. Document.write in line 5 showed the contents of each element in the array. Now, when I alert the Object.prototype... of volunteerDist, is says object Array. But when I called $.ajax and transferred volunteerDist into data and alert it (as shown below), it returns undefined and success (meaning data is stored but the contents are undefined). Any help? Thanks
function getABC(){
for(s=0;s<length;s++){
volunteerlocation = new GLatLng(jlat[s], jlng[s]);
volunteerDist[s] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
document.write(volunteerDist[s] + '<br> ');
document.write(jid[s] + '<br> ');
}
alert(Object.prototype.toString.call(volunteerDist));
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(data){
alert(data);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});
}
Update:
Below is my toDistance.php
<?php
$distance=array();
$volunteerid=array();
if(empty($_GET)){
echo "Hello";
}
else{
$distance = isset($_GET['distance']) ? $_GET['distance'] : 0;
$volunteerid = isset($_GET['id']) ? $_GET['id'] : 0;
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
for($i=0;$i<$distance.length;$i++){
$updateDistance = mysql_query("
UPDATE volunteerbio
SET volunteerDistance = $distance[$i]
WHERE volunteerID = $volunteerid[$i];
");
}
}
?>
It's now the same data variable! It's in other scope.
The data in the success function is what the server returned. Give it other name if it confuses you.
$.ajax({
type:'POST',
url: 'toDistance.php',
data : ({
distance:volunteerDist,
id:jid
}),
success: function(result){ // Data sent from the server. not the data above!
alert(result);
alert('worked');
},
error :function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
complete : function(){
alert('thanks');
}
});

Categories

Resources