PHP,Jquery(ajax) post uncaught syntaxerror:unexpected token < - javascript

guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}

Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}

try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);

change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});

Related

javascript no action on dropdown click

When I click twice on my dropdown I have this error message
error :SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data on the second click
Do you know where is the problem?
Thank you.
HTML code
$content .= '<div id="myAjax">';
$content .= HTML::selectMenu('move_to_category_id[]', $category_tree, $current_category_id, 'id="move_to_category_id"');
$content .= '</div>';
$categories_ajax = CLICSHOPPING::link('ajax/products_categories.php');
the javacript (updated works fine now)
<script>
window.addEventListener("DOMContentLoaded", (event) => {
console.log("DOM entièrement chargé et analysé");
document.querySelector('#myAjax')
.addEventListener('click',function(e){
var selectedOptionVal = document.querySelector('#move_to_category_id').value
,options_html="";
fetch("{$categories_ajax}?"+selectedOptionVal)
.then(function(response) {
return response.json();
})
.then(function(jsonResponse) {
// équivalent à success d'ajax
console.log("data is :",jsonResponse);
for(var index in jsonResponse){
let category_id = jsonResponse[index].id;
let category_name = jsonResponse[index].text;
let selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
}
$('#move_to_category_id').html(options_html);
})
.catch(function(err) {
//équivalent à error d'ajax
alert("error :"+err);
});
});
});
</script>

Simple JSON code doesn't work

This code tries to populate a dropdown list in a form with values. I have tested the PHP separately and the query is ok (small wonder !). I have a similar form whith 3 connected dropdown lists and they work flawlessly. Debugging this in Mozilla, I notice that the success function of JSON is not executed. I cannot understand why.
JavaScript
$(document).ready(function()
{
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
{
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
// var selOption = document.getElementById("selJudet");
// selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
// document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
// selText.value = selText.defaultValue;
selText.value = "Abcgcfkjsdhfsjkdh";
// $("#selText").change();
});
});
PHP (I skipped the database connection code)
$query = '(SELECT 1 AS sc, nume_judet FROM sa_Judet ';
$query .= 'WHERE nume_judet <> "N/A" ) UNION ';
$query .= '(SELECT 2 AS sc, "N/A" FROM sa_Judet) ';
$query .= 'ORDER BY sc, nume_judet';
//print $query;
$result = mysqli_query($db_conn, $query);
$judet = array();
if ($result == FALSE)
{
array_push($judet, 'QUERY_ERROR');
goto _adr1;
}
$rows = mysqli_num_rows($result);
if ($rows == 0)
{
array_push($judet, 'TBD_');
goto _adr1;
}
while ($row = mysqli_fetch_array($result))
{
array_push($judet, $row['nume_judet']);
}
_adr1:
print json_encode($judet);
mysqli_free_result($result);
mysqli_close($db_conn);
?>
Ajax variant of my original Javascript
$(document).ready(function()
{
$.ajax({
url: "/scripts/033A_GetJudet.php",
dataType: 'json',
success: function(data)
{console.log('SUCCESS: ', data);},
error: function(data)
{console.log('ERROR: ', data);}
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
var selOption = document.getElementById("selJudet");
selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
selText.value = selText.defaultValue;
// $("#selText").change();
});
});
It is possibly an error in parsing the data received. HTTP 304 is the same as HTTP 200, only the contents is pulled from cache, not serverside.
$.ajax({
url: url,
data: data,
success: function(response, textStatus, jsqxhr) {
var obj; try { obj = eval(response); } catch(e) { console.error(e); }
// -- do something with obj --
},
fail: function(jqxhr, textStatus, error) {
console.log( "error", textStatus, error);
}
});
Use this function instead and look closer at the data. If data is returned through success, we try to evaluate the json string into an object. Should it fail, an exception is thrown (possibly SyntaxError) and log should show this.
Replace this line
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
with this one
$.getJSON("/scripts/033A_GetJudet.php", function(data)

How can I add php variables to this Javascript?

I'm trying to build a simple news page with ajax filters depending on what category the user wants to see. The javascript below connects to a php file and outputs HTML with data from the mysql database. I need to know how to tell the JS to put the data from the "heading" column into a php variable so that it wraps it in the correct href link.
This is the php that creates the heading and the link
$data_fields = '`id`, `heading`, `date`, `copy`, `summary`, `article`, `press_release`, `video`';
$from = '`media`';
$news_result = $db->selectByStrings($data_fields, $from, $where_conditions, $order_by);
$news = $db->getAllRows($news_result);
foreach ($news as $new) {
echo '<h2 class="news"><a class="news" href="'.$base_href.$new['id'].'">'.$new['heading'].'</a></h2>';
}
I somehow need to include this is the separate JS file, making sure it is only applied to data from the heading column.
Javascript
function makeTable(data) {
var tbl_body = "";
$.each(data, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>" + v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
function getEmployeeFilterOptions() {
var opts = [];
$checkboxes.each(function () {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts) {
$.ajax({
type: "POST",
url: "filter3.php",
dataType: 'json',
cache: false,
data: {filterOpts: opts},
success: function (records) {
$('#employees div').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function () {
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
The php file the above connects to:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
$where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
$where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
$where .= " AND video = 1";
}
$sql = $select.$from.$where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I think you are looking for something like this :
var base_href = 'http://www.stackoverflow.com/';
function makeTable(data) {
var tbl_body = "";
$.each(data, function (index, row) {
var tbl_row = "";
$.each(row, function (k, v) {
if(k == 'heading' && 'id' in row) {
v = '<a class="news" href="' + base_href + row.id +'">' + v + '</a>';
}
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
+ v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}

Populating dropdown menu after ajax call

I am aware that AJAX works asynchronously (that is what the “A” stands for). I moved all the code that depends on the result of the AJAX call inside the success callback. However after the call is being made, I am not getting the select dropdwon box to populate with any data. How can I populate the select dropdown menu after the ajax call?
Jquery/Ajax
<script>
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
function addNewCourse() {
var data;
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: { value : option},
success: function(data){
//alert(data);
//console.log(data);
content += '<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></br>';
}
});
}
addNewCourse();
}
}
</script>
coursesOffered.php
try {
$db_con = new PDO($dsn, $user, $password);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row){
//dropdown values pulled from database
echo '<option value="' . $row['course_id'] . ':'.$row['course_name'].'">' . $row['course_name'] . '</option>';
}
See my comments in code:
function showFields(option) {
for (var i = 1; i <= option; i++) {
(function(i) {
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: {
value: option
},
success: function (data) {
var content += '<select id="coursename_' + i + '" name="coursename_' + i + '" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></br>';
// Insert the `content` into DOM here, you cannot return due to the async nature of AJAX
}
});
})(i); // you have to pass `i` into a function, otherwise when ajax complete, i will equal to `option + 1`
}
}
It seems you have not used return statement in addNewCourse(), try return content; after completion of Ajax.
$(document).ready(function () {
$('#courses_offered').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
function addNewCourse() {
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: { value : option},
success: function(data){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></div></br>';
}
});
return content;
}
content = addNewCourse();
}
$('#course_catalog').html(content);
}
});

undefined error when iterating over json list

i got this code that keep on returning undefined msg instead of the expected html.
Purpose of function:
the purpose of the below function is to return notifications in away similar to fb one's. the code is working fine. but there's something wrong with the getJSON part that i couldn't figure out. so instead of returning "clonex1 likes your post" i get undefined.
the code
function buzzme()
{
jQuery('#cnumber').removeClass();
jQuery('#cnumber').empty();
jQuery('#floating_box').toggle();
var nHeader = '<div id="floating_box" class="fb">' +
'<div id="header"><span id="htext">Notifications</span></div>' +
'<div id="int">' +
'<div id="bodyx">' +
'<ul>';
var nFooter = '</ul>' +
'<div class="jfooter">' +
'See all notifications' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
var nContent;
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
});
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
}
notifications.php - setUpFlayout(); and setUpJSONList()
function setUpFlyout() {
$notify = new se_notify();
$data2 = $notify->notify_summary();
$trk = 0;
if($data2['total'] >= 1) {
for($i = 0; $ $i <= $data2['total']; $i++) {
$nid = $data2['notifys'][$i]['notify_id'];
$im = $data2['notifys'][$i]['notify_icon'];
$img = "<img src='./images/icons/$im' />";
$notifier = $data2['notifys'][$i]['notify_text'][0];
$atype = $data2['notifys'][$i]['notifytype_id'];
$url = '';
$url2 = $data2['notifys'][$i]['notify_url'];
if($atype == 1) {
$url = ' has sent you friend <a href='.$url2.'>request</a>';
}
$trk++;
if($data2['total'] >= 2) {
$ret_arr = '';
if($i == 0) {
$ret_arr = '[';
}
$ret_arr = $ret_arr.setUpJSONList($data2['total'], $nid, $img, $notifier, $url, $trk);
if($i == $data2['total']-1) {
$ret_arr = $ret_arr.']';
}
echo '';
} else if($data2['total'] == 1){
//$ret_arr = '[{"dh3":"'.$data2['total'].'","nid":"'.$nid.'", "img":"'.$img.'","notifier":"'.$notifier.'","url":"'.$url.'"}]';
$ret_arr = '';
echo $ret_arr;
}
if($i == ($data2['total']-1))
break;
}
}
}
setUpJSONList();
function setUpJSONList($total, $nid, $img, $notifier, $url, $track) {
$comma = ',';
$lp = '';
$rp = ']';
$result = '';
if($track == $total) {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"}';
} else {
$result = '{"pos":"'.$track.'","dh3":"'.$total.'","nid":"'.$nid.'","img":"'.$img.'","notifier":"'.$notifier.'", "url":"'.$url.'"},';
}
return $result;
}
thanks
Your usage of nContent after getJSON might be undefined since getJSON is asynchronous and would not have completed initializing nContent. You need to move the code using nContent inside the callback of getJSON.
jQuery.getJSON('notifications.php', {'n':1,'dht':3692}, function(response){
jQuery.each(response, function(i, nt2){
nContent += '<li id="lix">sdfsdfsd'+nt2.img+' '+nt2.notifier+'</li>';
})
alert(nContent);
var nFinal = nHeader+nContent+nFooter;
if (!jQuery('#floating_box').length) {
jQuery('body').append(nFinal);
}
});

Categories