I am trying to get several variable results from php with jquery json. The problem is that I get null values in the console (on title for example) and script failed. With this script I am trying to populate some input fields with data that is being send from php. I am a noob in ajax json. Please help me.
HTML
<input id="titledata" type="text" name="siteTitle" value="" />
<textarea id="itemDescription" name="description"></textarea>
<input id="suggestkeyworddata" type="text" name="proposalForKeywords" value="" />
JQUERY - here I am trying to get the variables and store them into jquery variables:
var title = data.titledata;....
<script type="text/javascript">
$(function checkdomain() {
jq2('#metaTagButtonz').on('click', function (e) {
$.ajax({
type: 'post',
url: 'getallinfos.php',
data: $('#urlpr').serialize(), // sending data to php from this field
dataType: 'json',
success: function (data) {
$("#domain-hits").html(data);
// here i am trying to get data from php
var title = data.titledata;
var description = data.descriptiondata;
var keywords = data.keywordsdata;
// here I am trying to populate the data into the
// input fields
$('#titledata').val(title);
$('#itemDescription').val(description);
$('#keywordswebsite').val(keywords);
}
});
e.preventDefault();
});
});
</script>
PHP
//$title, $descr, and $keywords are strings
(sometimes empty sometime have values depending on the website)
$data = array(
'titledata' => $title,
'descriptiondata' => $descr,
'keywordsdata' => $keywords,
);
$data = json_encode($data);
1 Answer 1
You just need to print the actual content from your php script:
header('Content-Type: application/json');
echo json_encode($data);
answered May 22, 2014 at 17:31
Stefano Ortisi
5,3163 gold badges35 silver badges44 bronze badges
Sign up to request clarification or add additional context in comments.
7 Comments
user3650099
ok, working on getting the data now, but is not populating the fields.
user3650099
In the console I am getting
"{\"titledata\":\"TITLE OF SITE\",\"descriptiondata\":\"DESCRIPTION OF SITE\",\"keywordsdata\":\"KEYWORDS OF SITE\"user3650099
Tried on doing an
alert(titledata); And I get the alert box containing object HTMLInputElementStefano Ortisi
So now you need to fix your backend code. It depends on what you're doing before printing the data.
user3650099
All of the variables in php mentioned contain the data, but it's not outputted correctly, don't understand why not.
|
default