Uncaught SyntaxError: missing } after property list in AJAX - javascript

i am doing a little project in laravel with Ajax but i have got this error when i do the validations with ajax.
<script>
$(document).ready(function() {
$(document).on('click','.add_product', function(e) {
e.preventDefault();
let name= $('#name').val();
let price= $('#price').val();
$.ajax({
url: {{ route('add') }},
method: 'post',
data: {name:name, price:price},
success: function(res) { },
error: function(err) {
let error = err.responseJSON;
$.each(error.errors, function(index, value) {
$('.errMsgContainer').append('<span class="text-danger">'+ value+ '</span>' + '<br>');
});
}
});
});
});
</script>

inside the ajax in the url make it like this
URL: "{{ route('add') }}",
add the route inside quotations.
<script>
$(document).ready(function() {
$(document).on('click', '.add_product', function(e) {
e.preventDefault();
let name = $('#name').val();
let price = $('#price').val();
$.ajax({
url: "{{ route('add') }}",
method: 'post',
data: {
name: name,
price: price
},
success: function(res) {
},
error: function(err) {
let error = err.responseJSON;
$.each(error.errors, function(index, value) {
$('.errMsgContainer').append('<span class="text-danger">' + value + '</span>' + '<br>')
});
}
});
})
});
</script>

Related

Compare data with ajax response using jquery

I have Script is as below
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
success : function(response) {
$.each(response, function(index, value) {
response.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
});
$('.tree').append( response.join('') );
},
error : function(res, textStatus) {
var msg = "Unable to load Subfolder";
alert(msg);
}
});
setStatus($(this));
});
});
In this I want to compare data means id to some response element like
success : function(response) {
$.each(response, function(index, value) {
if(id==value.rootId){
response.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
}
else{
response.push('<li class="tree-title" ></li>');
alert("Append Failed");
}
});
$('.tree').append( response.join('') );
},
But it s not working
How could i achieve this? Can anybody suggest me?
You can supply properties to your success callback and access them from within the closure using this. Example this.id The custom properties you specify can't already be defined in the ajax prototype, otherwise you'll rewrite the default values. Try this:
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
id : id,
success : function(response) {
afterSuccess(response , this.id);
function afterSuccess(data, i) {
$.each(data, function(index, value) {
if(i==value.rootId){
data.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
}
else{
alert("Append Failed");
}
});
$('.tree').append( data.join('') );
}
}
});
setStatus($(this));
});
});
You could load your results into a separate variable like contents
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
id : id,
success : function(response) {
afterSuccess(response , this.id);
function afterSuccess(data, i) {
var contents = "";
$.each(data, function(index, value) {
if(i==value.rootId){
contents += '<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>';
alert("Appended Successfully");
}
else{
alert("Append Failed");
}
});
$('.tree').append( contents );
}
}
});
setStatus($(this));
});
});

How to add error message for DropDown List in MVC Project?

I use ajax to take list of items from JSON for my DropDown List(Because i Have Cascade DropDown). Now i need to add error message if is nothing choiced for "Pravec":
Dropdown code:
#Html.DropDownList("Pravec", new SelectList(string.Empty, "Value", "Text"), "Изберете Релација", new { #class = "form-control", required = "required" })
and ajax code:
$(function () {
$.ajax({
type: "GET",
url: "/relacii/getPravecList",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#Pravec').append('<option value="' + value.r1ID + '">' + value.relIme + '</option>');
});
}
});
$('#Pravec').change(function () {
$('#DatumRID').empty();
service_id = $('select[name=\'Pravec\']').val();
$.ajax({
type: "POST",
url: "/relacii/getRelaciiList1?rID=" + service_id,
datatype: "Json",
data: { relacijaID: $('#Pravec').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#DatumRID').append('<option value="' + value.relID + '">' + value.DatumForDisplay + '</option>');
});
}
});
});
});
You need to add a default option like
$('#Pravec').append('<option value="-1">'--------Please Select One-------'</option>');
before append the result from the ajaxcall. Then you can check the value at the change event of the first dropdown(i.e #Pravec).
The whole code may be like bellow
$(function () {
$.ajax({
type: "GET",
url: "/relacii/getPravecList",
datatype: "Json",
success: function (data) {
$('#Pravec').append('<option value="-1">'--------Please Select One-------'</option>');
$.each(data, function (index, value) {
$('#Pravec').append('<option value="' + value.r1ID + '">' + value.relIme + '</option>');
});
}
});
$('#Pravec').change(function () {
$('#DatumRID').empty();
service_id = $('select[name=\'Pravec\']').val();
if (service_id=="-1") {
alert("please select");
}
else {
$.ajax({
type: "POST",
url: "/relacii/getRelaciiList1?rID=" + service_id,
datatype: "Json",
data: { relacijaID: $('#Pravec').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#DatumRID').append('<option value="' + value.relID + '">' + value.DatumForDisplay + '</option>');
});
}
});
}
});
});

how to use json data sent from backend

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
<li>"i want to insert variable here"<li>
},
error: function (data) {
console.log('Error:', data);
}
});
controller returns this
return Response::json($results);
and it gives this
{"results":[{"id":1,"name":"user","nick":"user1"}]}
how can i acces this in ajax part
You can use the data in ajax, sent from controller like this:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) { // <-------- here data is your variable having json received from backend
$.each(data.results, function(key, val) {
// Use your results array here...
$('li.data').each(function(i) {
$(this).find('span.id').text(val.id);
$(this).find('span.name').text(val.name);
$(this).find('span.nick').text(val.nick);
});
});
},
error: function (data) {
console.log('Error:', data);
}
});
You'll get json inside the data variable under the success section of your ajax call
Hope this helps!
In your success method you can access the data returned from the server as:
success: function(data) {
var users = data.results;
var temptale = '';
for (var i = users.length - 1; i >= 0; i--) {
temptale += "<li>Name - " + users[i]['name'] + "<li>"
}
// use temptale to insert in your DOM
},
var queryInfoById= function (id) {
var params = {
"id": id,
};
$.getJSON(prefix + "/queryById.do", params, function (data) {
$("#name").val(data.name);
$("#age").val(data.age);
});
};
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
var array = data.results;
for (var i=0; i < array.length; i++){
var obj = array[i];
var id = obj.id;
var name= obj.name;
var nick= obj.nick;
//Add here the data in your UL>LI elements.
}
},
error: function (data) {
console.log('Error:', data);
}
});

How to make a search with jquery and the wikipedia API

I have read a lot of posts, old, new and the wikipedia documentation.
I have this request that works itself and in the sanbox:
https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=einstein&format=json
https://www.mediawiki.org/wiki/Special:ApiSandbox#action=query&format=json&list=search&srsearch=einstein
but when I try to use it in a javascript script, I can not get the data:
I tried both ajax and Json:
here is the code I used:
a 'GET' request with ajax :
code markup sucks
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var request_url = "?action=query&format=json&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#doit").click(function() {
console.log("Submit button clicked");
var pattern = $("#search").val();
var url = build_wiki_search_url(pattern);
console.log(url);
$.ajax( {
type: "GET",
url: url,
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function(errorMessage) {
console.log("damnn");
}
});
console.log("end");
});
})
a 'POST' request with ajax following the wikipedia documentation
var base_url = "https://en.wikipedia.org/w/api.php";
$.ajax( {
contentType: "application/json; charset=utf-8",
url: base_url,
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: 'einstein',
origin: '*',
},
dataType: 'json',
type: 'POST',
success: function(data) {
console.log("ok");
// do something with data
},
error: function(errorMessage) {
console.log("damnn");
}
} );
and a getJSON try:
//getJSON atempt.
console.log(url + '&callback=?');
$.getJSON(url + '&callback=?', function(json) {
console.log("ok");
});
Here is the output in my console:
Submit button clicked
https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=einstein
script.js
end
The problem comes in fact from the html:
<form >
<input type="text" id="search"> <button id="doit"> Search!!</button>
</form>
Since the button is in a form, this button normal behavior is to generate a submit action. So the idea is to disable this normal behavior with:
$("#doit").click(function(e) {
e.preventDefault();
The full working code :
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var format = "&format=json";
var request_url = "?action=query&format=json&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#doit").click(function(e) {
e.preventDefault();
console.log("Submit button clicked");
var pattern = $("#search").val();
var url = build_wiki_search_url(pattern);
$.ajax( {
type: "GET",
url: url,
dataType: 'jsonp',
success: function(data) {
console.log(data.query.searchinfo.totalhits);
},
error: function(errorMessage) {
console.log("damnn");
}
});
});
})

Using Wikipedia's API to fetch results from search query

I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :
"use strict";
$(document).ready(function(){
function searchWikipedia(searchCriteria){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);
}
$('#btn').click(function searchCriteria() {
var searchCriteria = $("input[name=Wikipedia]").val();
searchWikipedia(searchCriteria);
})
function processResult(apiResult){
if (apiResult.query.pages[-1]){
console.log("No results");
} else {
for (var i = 0; i < apiResult.length; i++){
$('#display-result').append('<p>'+apiResult+'</p>');
}
}
}
});
So far nothing appends to my html and there's no errors in my console.
#Ali Mamedov's answer is the way to go (it's from Wikipedia)
But the wikipedia link is missing the http:. Also, you can handle the response on your function:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: processResult
});
});
});
function processResult(apiResult){
for (var i = 0; i < apiResult.query.search.length; i++){
$('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
}
}
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + txt + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, item) {
if (i == 1) {
var searchData = item[0];
WikipediaAPIGetContent(searchData);
}
});
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
function WikipediaAPIGetContent(search) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=" + search + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var blurb = $('<div></div>').html(markup);
// remove links as they will not work
blurb.find('a').each(function () { $(this).replaceWith($(this).html()); });
// remove any references
blurb.find('sup').remove();
// remove cite error
blurb.find('.mw-ext-cite-error').remove();
$('#results').html($(blurb).find('p'));
$('#results').html(blurb);
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
</script>
Try this sample:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: function (x) {
console.log('title', x.query.search[0].title);
}
});
});
});
Source
This will show the query result with image:
$(document).ready(function(){
$('#btn').click(function() {
var search_text = $("input[name=Wikipedia]").val();
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
$.getJSON( url + search_text +'&callback=?',function(data){
for(var key in data.query.pages){
var titleArt = data.query.pages[key].title;
var extractArt = data.query.pages[key].extract;
var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
var imgArt;
if(data.query.pages[key].hasOwnProperty('thumbnail')){
imgArt = data.query.pages[key].thumbnail.source;
} else {
imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
}
var contentHTML = '<div class="col-md-4"><div class="box-result"><div class="bg-result"></div><div class="box-content center-block"><div class="article-thumbnail"><img src="' + imgArt + '" alt="" /></div><h1>'+ titleArt +'</h1><p>' + extractArt + '</p></div></div></div>';
$('#display-result').append(contentHTML);
}
});
});
});
function Wiki(lang) {
this.lang = lang || "fr";
this.inuse = false;
}
Wiki.prototype.research = function(s, callback) {
if (this.inuse) {
console.error("Wiki est déjà en cours d'utilisation !");
} else {
this.inuse = true;
var r = new XMLHttpRequest();
r.onload = function() {
Wiki.prototype.inuse = false;
var j = JSON.parse(r.responseText);
callback(j);
}
r.open('GET', "https://" + this.lang + ".wikipedia.org/w/api.php?%20action=opensearch&format=json&origin=*&profile=normal&search=" + encodeURIComponent(s));
r.send();
}
}
var c = new Wiki();
c.research("Victor Hugo", function(result) {
console.log(result);
});
//EXEMPLE
var c = new Wiki("en");
c.research("Victor Hugo", function(result) {
console.log(result);
}

Categories

Resources