简体   繁体   中英

Unexpected token s in JSON at position 0

I am using ajax to get texts from an input field and check them through php than store them in the database...But somewhere on the line, something is wrong and I am getting Unexpected token s in JSON at position 0 this error...

 $(".df-sub").on('click',function(e){ e.preventDefault(); resetErrors(); $('.inputTxtError').children('form input').css({'border-color' : '','box-shadow' : ''}); var data = {}; $.each($('form input, form select'), function(i, v) { if (v.type !== 'submit') { data[v.name] = v.value; } }); $.ajax({ dataType: "JSON", type: "POST", data: data, cache: false, url: "/ajax/diet/diet-page-error-display.php", success: function(result){ if(result === "true"){ console.log('raboti do tuk'); $(".df-sub").submit(); window.location = "http://www.homepage.co.uk/thankyou"; return false; }else { console.log('ne raboti'); $.each(result, function(i, v) { //console.log(i + " => " + v); // view in console for error messages var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>'; $('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg); }); var keys = Object.keys(result); $('input[name="'+keys[0]+'"]').focus(); } return false; }, error: function(jqXHR, textStatus, errorThrown) { //console.log(JSON.stringify(result)); alert(jqXHR.status); alert(textStatus); alert(errorThrown); } }); function resetErrors() { $('form input, form select').removeClass('inputTxtError'); $('label.diet-error').remove(); } }); 
 <?php header('Content-type:application/json;charset=utf-8'); if(isset($_POST)){ if (filter_var($_POST['age'], FILTER_VALIDATE_INT) === false){ $_SESSION['errors']['age'] = 'Моля използвайте само цифри в полето за Вашата възраст!'; } if (filter_var($_POST['height'], FILTER_VALIDATE_INT) === false){ $_SESSION['errors']['height'] = 'Моля използвайте само цифри в полето за Вашата височина!'; } if (filter_var($_POST['weight'], FILTER_VALIDATE_INT) === false){ $_SESSION['errors']['weight'] = 'Моля използвайте само цифри в полето за Вашато тегло!'; } if (filter_var($_POST['budget'], FILTER_VALIDATE_INT) === false){ $_SESSION['errors']['budget'] = 'Моля използвайте само цифри в полето за Вашият бюджет!'; } if (filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false){ $_SESSION['errors']['email'] = 'Моля въведете валиден имейл адрес!'; } if(empty($_POST['email'])){ $_SESSION['errors']['email'] = 'Моля въведете имейл за връзка'; } if(empty($_POST['age'])){ $_SESSION['errors']['age'] = 'Моля въведете Вашата възраст!'; } if(empty($_POST['height'])){ $_SESSION['errors']['height'] = 'Моля въведете Вашата височина!'; } if(empty($_POST['weight'])){ $_SESSION['errors']['weight'] = 'Моля въведете Вашето тегло!'; } if(!isset($_POST['sex'])){ $_SESSION['errors']['sex'] = 'Моля изберете пол !'; } if(!isset($_POST['activity'])){ $_SESSION['errors']['activity'] = 'Моля изберете активност! !'; } if(!isset($_POST['goal'])){ $_SESSION['errors']['goal'] = 'Моля изберете цел !'; } }// if(count($_SESSION['errors']) > 0){ if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { echo json_encode($_SESSION['errors']); unset($_SESSION['errors']); exit(); } echo "<ul>"; foreach($_SESSION['errors'] as $key => $value){ echo "<li>" . $value . "</li>"; } echo "</ul>"; unset($_SESSION['errors']); exit(); }else{ $age = clean_xss_int($_POST['age']); $height = clean_xss_int($_POST['height']); $weight = clean_xss_int($_POST['weight']); $email = clean_xss($_POST['email']); $sex = clean_xss($_POST['sex']); $activity = clean_xss($_POST['activity']); $goal = clean_xss($_POST['goal']); $diseases = clean_xss($_POST['diseases']); $liked_foods = clean_xss($_POST['liked_foods']); $hated_foods = clean_xss($_POST['hated_foods']); $budget = clean_xss_int($_POST['budget']); $intership = clean_xss($_POST['training']); $description = clean_xss($_POST['eat_usually']); $data = array( 'age' => $age, 'height' => $height, 'weight' => $weight, 'email' => $email, 'sex' => $sex, 'activity' => $activity, 'goal' => $goal, 'diseases' => $diseases, 'liked_foods' => $liked_foods, 'hated_foods' => $hated_foods, 'budget' => $budget, 'intership' => $intership, 'description' =>$description ); //Here is the query usually echo json_encode($data); ?> 

No matter what I do it's always returning Unexpected token s in JSON at position 0 .For now i have tried to remove DataType: "JSON" used Content-Type header, use json_encode() (there is the result from JSON encode)

Link to network response tab

Also tried utf8_encode() before json,but it require a string not array. Thank you!

OK so i was on this error whole day, there is the solution which worked for me.

First i checked if JSON is valid in www.jsonlint.com and it was valid.

Second my clean_xss_int function was wrong, i was imploding the input value if it is array, so the end result was strings for number fields and arrays for text fields.

Third (because i am new to ajax) I checked the whole php side, and realized that even if there is empty field aka must return error or return the data array ajax got it both for successful operation.Plus that there is no need to pass the $data array to json again,because i need it only for the insert query. So i wrote array which i am returning as success in ajax which is array('0' => 'true'); And i am making it string in ajax and checking if success is equal to string 'true'.There is how code looks like:

  $.ajax({ type: "POST", data: data, dataType: "JSON", url: "/ajax/diet/diet-page-error-display.php", success: function(result){ JSON.stringify(result);// <---- new ;d if(result == "true"){ <--- comparing with 2 x = instead of 3 $(".df-sub").submit(); window.location = "http://www.musclevale.com/diet"; return false; }else { $.each(result, function(i, v) { var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>'; $('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg); }); var keys = Object.keys(result); $('input[name="'+keys[0]+'"]').focus(); } return false; }, error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR.status); alert(textStatus); alert(errorThrown); } }); 
 <?php $age = clean_xss_int($_POST['age']); $height = clean_xss_int($_POST['height']); $weight = clean_xss_int($_POST['weight']); $email = clean_xss($_POST['email']); $sex = clean_xss($_POST['sex']); $activity = clean_xss($_POST['activity']); $goal = clean_xss($_POST['goal']); $diseases = clean_xss($_POST['diseases']); $liked_foods = clean_xss($_POST['liked_foods']); $hated_foods = clean_xss($_POST['hated_foods']); $budget = clean_xss_int($_POST['budget']); $intership = clean_xss($_POST['training']); $description = clean_xss($_POST['eat_usually']); $data = array( 'age' => $age, 'height' => $height, 'weight' => $weight, 'email' => $email, 'sex' => $sex, 'activity' => $activity, 'goal' => $goal, 'diseases' => $diseases, 'liked_foods' => $liked_foods, 'hated_foods' => $hated_foods, 'budget' => $budget, 'intership' => $intership, 'description' =>$description ); $fields = implode(',',array_keys($data)); $values = '\\'' . implode('\\', \\'', $data) . '\\''; $query = mysqli_query($connect,"INSERT INTO buyed_diets ($fields) VALUES ($values)"); echo json_encode(array('0' => 'true'));// <----new ;d ?> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM