Ajax function (Unexpected token) in AJAX Call - html

so I have been testing a bunch of new different JS code to see if I can get the POST request to send information to a SharePoint list. When I run my newest block, it tells me "Error: Line 20: Unexpected token" when I call $.ajax saying the period is what is unexpected? I truly don't understand.
Here is my JS code:
$(document).ready(function(){
$("#btnSubmit").click(function(){
saveDelivDetails();
});
});
function saveDelivDetails(){
var itemType = GetListItemTpye(listname);
var item = {
"__metadata":{"type":itemType},
"Program":$("#dProgram").val(),
"Deliverable":$("#dDeliverable").val(),
"To":$("#dTo").val(),
"Date":$("#dDate").val(),
"Approved":$("#dApproved").val(),
"Notes":$("#dNotes").val()
};
var requestUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('"+listname+"')/items",
$.ajax({
url: requestUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers:{
"Accept":"application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onError,
});
function onSuccess(data){
alert("New Item Created");
$("#txtSubmitName").val();
}
function onError(error){
alert('error' + error);
console.log(error);
}
function GetListItemType(name){
return "SP.Data."+CharacterData(0).toUpperCase().name.slice(1)+"ListItem";
}

You have a , after line 19.
var requestUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('"+listname+"')/items",

Related

no display fail message from controller

I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});

Json Error In Laravel Ajax

I'm Use Laravel 5.2 And Ajax For Crud
Insert to Database is Correct But When Laravel Response The Browser Show Below Error In Console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Laravel Code:
return response()->json('ok');
Jquery Code:
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
....
error: function(data){// Error...
var errors = $.parseJSON(data.responseText); console.log(errors);
$.each(errors, function(index, value) { $.gritter.add({
title: 'Error',
text: value
});
});
}
RedyState=4
Staus = 200
Can you paste your all controller code related to this error? Make sure you're not echoing anything before returning json response.
For example,
Route::get('/', function () {
echo "hi";
return response()->json('ok');
});
It would cause parse error.
With the Json response, what if you try something like.
return response()->json(['status'=>'ok']);
You javascript code should be
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success:function (xhr){
var data = xhr.data;
},
error: function (error){
}
});
And why are you using var errors = $.parseJSON(data.responseText); ? Your response will be always json, no?

posting json to express - invalid json

I am trying to post some json to a node server running express but it keeps telling me the json was invalid. But its not, its just a plain old object. Currently I get the error 'unexpected token i'
client:
$.ajax({
contentType: 'application/json',
type: "POST",
url: "/admin",
data: {id: '435ghgf545ft5345', allowed: true}
});
server:
var bodyParser = require('body-parser');
app.use(bodyParser({strict: false}));
app.post('/admin', function(request, response) {
console.log(request.body);
});
I have also tried putting bodyParser.json() as the second parameter in the post route and get the error 'invalid json at parse'. I cant figure out why.
This code may help you :
var jsondataResource = JSON.stringify({id: '435ghgf545ft5345', allowed: true});
$.ajax({
type: 'POST', //GET or POST or PUT or DELETE verb
async: false,
url: '/admin', // Location of the service
data: jsondataResource , //Data sent to server
contentType: 'application/json', // content type sent to server
dataType: 'json', //Expected data format from server
processdata: true, //True or False
crossDomain: true,
success: function (msg, textStatus, xmlHttp) {
result = msg;
},
error: ServiceFailed // When Service call fails
});
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
}

Chrome extension transfer to manifest 2 - No ajax response

Hayush!
Been trying to transfer my Chrome extension to manifest 2. Everything is working except for one script which calls an ajax. I have a variable that contains a JSON content which needs to be transferred to the server.
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
For some reason the ajax part is not executed at all. No error message was triggered, nor in the server error log.
All of the inline scripts and scripts in general were included in the popup.js. So it's probably not the issue.
Any thoughts?
Thanks!
The following code works perfectly on previous manifest
function importbookmarks(){
$('#formadd').css('display','none');
$('#importing').css('display','block');
_gaq.push(['_trackEvent', 'chromextension','importbookmarks', username]);
chrome.bookmarks.getTree(function(bookmarks) {
sendlist(bookmarks);
});
}
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
// processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
}
});
}
The problem wasn't with the function. The button execution wasn't calling it correctly.
Here is the code I used to get the function to work in manifest 2
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("import-bookmarks").addEventListener("click", function () {
importbook();return;
});

Ajax Call using jsonp for calling rest webservice from other domain

How I use the jsonp when call to rest webservice from different domain.becouse my simple json does not working for rest webservice.how can i call rest webservice for ajax call.i use both jsonp and javascript for that.server responce i seen on only browser in firebug but how to show it on my application
my JS code.
function callService() {
$.ajax({
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
crossDomain: true,
cache: false,
async: false,
contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
alert("Server Responce Successfully!..");
},
error: function (msg) {
alert('error ' + msg.d);
}
});
}
function countryProvinceWCFJSONMulti() {
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = 'JSON';
script.src = "http://192.168.15.213/myservice/Service.svc/GetEvents";
script.type = "text/javascript";
head.appendChild(script);
varType = "GET";
varData = '{"username": "' + "Suhasusername" + '","password": "' + "suhaspassword" + '"}';
varContentType = "application/JSONP; charset=utf-8";
varDataType = "JSONP";
varProcessData = true;
callService();
}
If the same-origin policy isn't an issue, your code should look something like this:
$.ajax({ url: url,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
alert("Server Response Successful!..");
}
});
Here is a question that talks about circumventing the same-origin policy