I am having issue with handlebars. Its not compiling the data - javascript

I've shifted my server, Handlebar is working fine on my previous server. The same code is not working on my new linux server. Data is not being compile.
My json response is fine its returning data properly. Any guide please!
Code:
var $deferredsLocal = [];
$deferredsLocal[0] = $.ajax({ url: tabUrl, type: "POST"});
$deferredsLocal[1] = $.ajax({url: 'templates/tabs_contact_detail.html', type: "GET", cache: true});
$.when.apply(null, $deferredsLocal).then(function (json, htm) {
var htmls = htm[0];
var template = Handlebars.compile(htmls);
var completeHtml = template(json[0]);
$('#content').empty();
$('#content').html(completeHtml);
$('#content').find('td.question_label').each(function (index, element) {
$(this).html($('<div/>').html($(this).html()).text());
});
$("#preloader").hide();
});
// tabUrl is returning json response

Hi Guys there was json format issue. The data i was getting was looking into json format but it was not in json actually. I just moved the header: header('Content-Type: application/json'); up and placed it in the start of my code.

Related

jQuery Ajax Input Text and File can't get the value after processing to success function

I have jQuery input text and input file submit using ajax.
$("#uploadForm").on('submit',(function(e)
{
e.preventDefault();
var badgeID = $("#badgeID").val();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var emailAddress = $("#emailAddress").val();
var firstNameMask = $("#firstNameMask").val();
var lastNameMask = $("#lastNameMask").val();
var emailAddressMask = $("#emailAddressMask").val();
$.ajax(
{
url: "updateAccountSetting.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
alert(data.firstNameVal);
$("#firstNameMask").val(data.firstNameVal);
$("#lastNameMask").val(data.lastNameVal);
$("#emailAddressMask").val(data.emailAddressVal);
$(".firstName").html(data.firstNameVal);
$("#btnUpdateAvatar").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');
$('#firstName, #lastName, #emailAddress').attr('readonly', false);
$('.uploadSuccess').show();
$("#btnUpdateAvatar").attr('disabled', true).addClass('btn_inact').removeClass('btn_act');
}
});
}));
I have tried the above code until processing to PHP file and it's working perfect.
But why I can't get value when I try to:
alert(data.firstNameVal);
The result of the alert is : undefined.
If I alert only data
alert(data);
the result is:
Try this:
success: function(data)
{
var result = JSON.parse(data);
alert(result.firstNameVal);
// rest of your code
}
Explanation:
For JS it is just a string what you get. You have to convert it to JSON-Object.
You may solve adding the correct header information in PHP or parsing the response in JavaScript.
PHP solution: add this row before output (on top of your script, maybe)
header('Content-Type: application/json');
JS solution: parse response string as json:
var dataObj = JSON.parse(data);
You get JSON response from updateAccountSetting.php url. JSON (JavaScript Object Notation) is a lightweight data-interchange format. You have to convert JSON data to Javascript object.
Have a look at below
success: function(data)
{
var data =$.parseJSON(data);//convert json data to javascript object
$("#firstNameMask").val(data.firstNameVal);
$("#lastNameMask").val(data.lastNameVal);
$("#emailAddressMask").val(data.emailAddressVal);
$(".firstName").html(data.firstNameVal);
$("#btnUpdateAvatar").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');
$('#firstName, #lastName, #emailAddress').attr('readonly', false);
$('.uploadSuccess').show();
$("#btnUpdateAvatar").attr('disabled', true).addClass('btn_inact').removeClass('btn_act');
}

Getting json array to create products index problems using Php, json, JS and JSON

Having a few problems creating a products index.
It looks like you're pushing down html as well in the products.php page. Make sure the output of the php that you're retrieving from only returns JSON.
Also, check the syntax on your script:
$.get({
type: "GET",
url: "products2.php",
data: 'id=' + userid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("decription").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
document.getElementById("stock").innerHTML = data[3];
}
});
You were using $rows but attempting to access data. Adding a simple console.log(data); in the success function will dump the results to the console in chrome/firefox so you can see what is being returned. (Be sure to check the network tab as well, as it can give you some tips as to why the data isn't being properly fetched.)
I've done something similar and this worked fine for me:
<?php
$array['status'] = 0;
...
echo json_encode($array);
Populate the array with whatever you need.
And then:
$.ajax({
type: "type",
url: "url",
data: {
data: data
},
success: function (data) {
console.log(data.status);
}
});

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

JSON Data returned from Ajax on Safari is converted into a javascript list

This is something I recently found out, I have the following piece of code in JS:
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(data) {
var places = JSON.parse(data);
// do something
},
error: function(data) {
// do something else
}
});
The data returned from my backend is indeed in JSON format, and var places = JSON.parse(data); this line works perfectly in Chrome and Firefox, it parses my JSON data into a JS list; however, in Safari, var places = JSON.parse(data); gives me error, because data is already a JS list. Instead of doing var places = JSON.parse(data), just changing to var places = data solved the error, I am wondering why it is converted automatically?
Thanks in advance
Your best solution would be to tell jQuery that the response is json so that you will always receive it as js object
$.ajax({
type: 'POST',
url: '/requestHandle',
data: data,
success: function(obj) {
// do something
},
error: function(data) {
// do something else
},
dataType: 'json' // reponse is json so it will always be pre-parsed
});

Post JSON data to server and parse the response in JavaScript

I need to POST the JSON format data to the server URL. The server will send the response in same JSON format. I need to parse it and get the data. How to do it? please help me with an example.
at client side (to convert into the json)--->
var myJSONText = JSON.stringify(myObject, replacer);
& at server side to get the actual data--->
var dynObj = JsonConvert.DeserializeObject(myJSONText);
php--->
<?php
$jsonTxt = '{"abc":1111,"xyz":222}';
var_dump(json_decode($jsonTxt));
var_dump(json_decode($jsonTxt, true));
?>
You can use JSON.parse() which may be supported in most browsers.
var response = {"success":true, "data":"My data"};
var json_res = JSON.parse(response);
console.log(json_res.data)
Alternatively, if you are using some javascript library, for example jQuery you may have an helper. See this similar question
Should look something like this.
var data = $(":input").serializeArray();
$.ajax({
url: url,
data: JSON.stringify(data),
type: "GET",
dataType: 'json',
contentType: 'application/json'
});
On Server side :
public static function createFromJson( $jsonString )
{
$object = json_decode( $jsonString );
return new self( $object->firstName, $object->lastName );
}

Categories

Resources