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>
Related
I have read a lot of similar examples here on S.O yet, I cannot figure out what is the problem. The item.picture image is successfully displayed on the html and its url can also be printed on the console.
However, the favico displays undefined both on the console and on html.
Here is the sample code:
$(function () {
jQuery.ajax({
type:'GET',
url:"api/wedding/?format=json&limit=20",
dataType:"json",
success :function (data) {
var listA=$("#wedding_id");
for(var i=0;i<data.results.length;i++) {
var item=newDiv(data.results[i])
listA.append(item);
}
},
error:function (e) {
console.log(e) // Better for debugging
// alert("Error" + e)
}
});
});
function newDiv(item)
{
if (item.pic) {
var wed_pic = item.pic.split(",")[0];
}
if (item.favico) {
var favicon = item.favico.split("/")[0];
}
console.log(item.pic); // <--- can display the pic_url on console
console.log(favicon); //shows 'undefined'
var template = '<ul class="wedding-list" id='+ item.wedding_id +'>'
+ '<a class="wedding-icon" href="#">' + favicon + '</a>' //<--- where I think lies the problem
+ '<a class="wed_img" target="_blank" href=' + item.url + '>'
+ '<img src=' + wed_pic + '>'
+ '</a> </ul>' +
return template
}
What could possibly be the cause of the undefined error? Thank you for helping.
for a start
const listA = document.querySelector('#wedding_id')
;
fetch ('api/wedding/?format=json&limit')
.then (res => res.json())
.then (data =>
{
for (let row of data.results)
listA.appendChild( newDiv(row))
})
.catch (err => console.error(err))
;
function newDiv(item)
{
let
e_UL = document.createElement('ul')
, wed_pic = !!item?.pic ? item.pic.split(',')[0] : ''
, favicon = !!item?.favico ? item.favico.split('/')[0] : ''
;
console.log('item ----->', JSON.stringify(item,0,2) )
console.log('wed_pic ->', wed_pic )
console.log('favicon ->', favicon )
e_UL.id = item.wedding_id
e_UL.className = 'wedding-list'
e_UL.innerHTML = `
<a class="wedding-icon" href="#"> ${favicon} </a>
<a class="wed_img" target="_blank" href="${item.url}">
<img src="${wed_pic}">
</a>`
return e_UL
}
I would like to prevent focusing out to create an additional change event on a text input field.
I validate the form as I type in the text input filed using keyup(), and change() events when hit enter using ajax.
When I click on save button it goes and validates the form once again and if OK saves the form to database.
Problem happens when I type on the text field, leave the cursor there and click on the save button. This first generates change event (because of focusout) and validates the form, since save was clicked it saves once, then save button click event is executed and this saves the form once again.
HTML
<form id="scheduling" name="scheduling" method="post">
<div id="prodSchedContainer">
<div>
<input type="text" name="inputText" id="tInput-1" class="testInputField">
</div>
</div>
<button type="button" id="saveButton-scheduling" name="saveButton" class="sharedButton saveButton" title="Save">
</form>
JS:
$('#prodSchedContainer').on('change', '.testInputField', function () {
infoLine = 'TEST INPUT CHANGED: >>>>> id: ' + $(this).attr('id') + ' >>>>> ' + $(this).val();
renderInfoBox(infoLine);
performScheduleValidation($(this));
});
$('#prodSchedContainer').on('keyup', '.testInputField', function () {
infoLine = 'TEST INPUT KEYUP: >>>>> id: ' + $(this).attr('id') + ' >>>>> ' + $(this).val();
renderInfoBox(infoLine);
performScheduleValidation($(this));
});
$('#schedulingContainer').on('click', '.saveButton', function () {
infoLine = 'SAVING SCHEDULE: >>>>> id:' + $(this).attr('id') + ' >>>>> ' + 'WHAT:' + $(this).attr('what') + ' / TYPE:' + $(this).attr('apptType') + ' / APPT:' + $(this).attr('appt') + ' >>>>> ' + $(this).val();
renderInfoBox(infoLine);
performScheduleValidation($(this));
});
function performScheduleValidation(sObj) {
objID = $(sObj).attr('id');
if (objID == 'saveButton-scheduling') {
action = 'save';
} else {
action = 'validate';
}
valData.push(['action', action]);
valData.push(['formData', formData]);
var ajaxData = JSON.stringify(valData);
var URL = BASE_DIR + 'schedulingValidation.php';
$.ajax({
url: URL,
type: 'POST',
data: { data: ajaxData },
success: function (theResponse) {
var responseData = $.parseJSON(theResponse);
isValid = responseData['valid'][0];
if (!isSaved) { //--- If the Schedule is not Saved
// Do some stuff within the form
} else { //--- The Schedule Is saved ---------- /
$('#schedulingContainer').html(''); //---- Clear up the scheduling container /
$('#product_idx_selector').val(0);
count_db_table('ota_scheduling');
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
}
});
}
PHP:
require_once("includes/connection.php");
require_once("/includes/functions.php");
$lang = $_SESSION['Language'];
$data = json_decode($_POST['data']);
$action = $data[0][1];
// ---- More Data
$weeklySchedule = $data[9][1];
$objID = $data[10][1];
//--- Validation Part
$schVal = 1; // This is 1 or 0 depending on the validation calculations
//--- SAVING Part
if ($action == 'save' && $objID=='saveButton-scheduling' && $schVal == 1) {
$query = "INSERT INTO ota_scheduling ( ";
$query .= "product_idx, ";
$query .= "trainers, ";
$query .= "coupons ";
$query .= ") ";
$query .= "VALUES ( ";
$query .= $productRow['id'] . ", ";
$query .= "'".$multiAppointments[0]['trainers'] . "', ";
$query .= "'".$multiAppointments[0]['coupons'] . "' ";
$query .= " )";
$result = mysql_query($query, $connection);
if(!$result) {
die("Database query failed at 'schedulingValidation.php' while Adding a Parent Schedule # ota_scheduling: " . mysql_error());
} else {
$parentID = mysql_insert_id();
}
}
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) {
}
});
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;
}
Ok so all of the other functions I've done this same way have worked so far. This one for whatever reason will not work.I don't know if there is something I"m missing or if maybe a potential error in the code earlier could cause this. Here is my code:
jQuery("#teamTab_addPlayerForm").on('change', 'select#teamTab_suggestedPlayer', function(e) {
e.preventDefault();
alert('It Worked');
});
And here is the PHP file that calls it:
$output .= '<div id="ld_addPlayerFunction" style="clear:both; width:100%;"><h3>Add Player</h3>';
$standins = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'kdc_user_sync ORDER BY computedMMR ASC');
$output .= '<form id="teamTab_addPlayerForm" action="" method="POST">
<select id="teamTab_suggestedPlayer" name="suggestedPlayer">
<option value="base">Suggested Player</option>';
foreach($standins as $standin){
$playerID = $wpdb->get_var('SELECT ID FROM ' . $wpdb->prefix . 'leagueDesigner_players WHERE userID = ' . $standin->userID);
$test = true;
if($playerID != ''){
$leagueTest = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_league_players WHERE playerID = ' . $playerID);
foreach($leagueTest as $test){
if ($test->leagueID == $leagueID){
$test = false;
}
}
}
if($standin->computedMMR < ($suggestedMMR + 100) && $standin->computedMMR > ($suggestedMMR -100) && $test == true){
$output .= '<option value="' . $standin->userID . '">' . substr($standin->profileName, 0, 20) . ' - ' . $standin->computedMMR . ' MMR</option>';
}
}
$output .= '</select><br />';
$output .= '</form>';
The output is then echoed later in the script. So one user has told me to use document instead of #teamTab_addPlayerForm and it works, but I'm wondering why this previous code worked fine and that one didn't:
jQuery("#teamTab_teamListForm").on('change', 'select#teamTab_teamSelect', function (e) {
e.preventDefault();
jQuery(this).attr('disabled', true);
var teamID = jQuery(this).val();
jQuery('select#teamTab_leagueSelect').attr('disabled', true);
var leagueID = jQuery('select#teamTab_leagueSelect').val();
data = { action: "leagueDesignerTeamsTabLoadTeamPlayers", leagueID: leagueID, teamID: teamID };
jQuery.ajax({
type: 'POST', url: ajaxurl, data: data, dataType: 'html', success: function(response) {
if (response == "error") {
jQuery('select#teamTab_teamSelect').attr('disabled', false);
alert('There was an error processing your request');
}
else {
jQuery('select#teamTab_teamSelect').attr('disabled', false);
jQuery('select#teamTab_leagueSelect').attr('disabled', false);
jQuery('.ld_teamEdit').remove();
jQuery('#ld_addPlayerFunction').remove();
jQuery('div#ld_teamTabTeamInfo').remove();
jQuery('#teamTab_teamListForm').after(response);
}
}});
});
That was the code that is dealing with select boxes in the same way. And here is the PHP code:
function leagueDesignerTeamsTabLoadLeagueTeams () {
global $wpdb;
$leagueID = $_POST['leagueID']; //Pull the POST'd leagueID
$output = '<select id="teamTab_teamSelect" name="team"><option value="">Choose a Team</option>'; //Output...
$errors = 0; //Error checking...
$teams = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_teams WHERE leagueID = ' . $leagueID);
foreach($teams as $team){
$output .= '<option value="' . $team->teamID . '"';
if ($_POST['team'] == $team->teamID){
$output .= ' selected';
}
$output .= '>' . $team->teamID . '. ' . $team->teamName . '</option>';
}
if (!$teams) {
$errors++;
}
$output .= '</select>';
if ($errors == 0) { echo $output; } else { echo 'error'; }
die(); // this is required to return a proper result
}
The element is created after page load so you need to bind it to an already existing element (see below)
$(document).on('change', '.class-name', function () {
//Commands to run on change
});