AJAX SyntaxError: Invalid character - javascript

The logic flow I'm trying to achieve is as following:
Select filters from popup => Generate the main view layout with headers and buttons => clicking button will render datatable inside
div id="#Model.ContainerSafeName-activitytable"
Below are relevant bits:
Main layout:
#model Models.Model
#using Helpers;
#{
Layout = "~/Views/Shared/PartialPrint.cshtml";
}
<div class="card card-block">
<div class='container'>
<div class="card row">
<div class="card-header text-center text-white" role="tab" id="Heading">
<h5>Activities</h5>
</div>
<div>
<button role="button"
data-type="Activity"
type="button"
class="btn btn-outline-primary btn-sm col-sm-12 col-md-12"
data-filters='#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.filters))'
data-url="#Url.Action("Activity_Page_activity", "Activity", new { Area = "Activity" })"
data-containername="#Model.ContainerSafeName-activitytable"
id="btnReport_activity">
Show Data
</button>
</div>
<div id="#Model.ContainerSafeName-activitytable">
</div>
</div>
Javascript bit:
$('#btnReport_activity').click(function () {
var url = $(this).data('url');
var filters = $(this).data('filters');
//var filtersstring = JSON.stringify(filters)
var containername = $(this).data('containername');
debugger
$.ajax({
cache: false,
url: url,
data: filters,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'GET'
})
.done(function (result) {
alert("good");
$("#" + containername).html(result);
$(this).toggle();
})
.fail(function (jqXHR, status, errorThrown) {
alert(errorThrown);
});
});
Ajax fails with Invalid character error. Filters are just a list of values passed to mainLayout from controller. I suspect it returns something bad.
Can anyone please point me where it possibly could go wrong? Please let me know if I need to provide any additional information.
PS: I'm not posting it on a whim, I have done a lot of research prior to that (including json.stringifying data, etc.), literally banging myself against the wall at this point.

I do not need a datatype being a JSON. I had to make corrections as below in order to get a proper response:
$('#btnReport_activity').click(function () {
var url = $(this).data('url');
var filters = $(this).data('filters');
//var filtersstring = JSON.stringify(filters)
var containername = $(this).data('containername');
$.ajax({
cache: false,
url: url,
data: JSON.stringify(filters),
contentType: 'application/json; charset=utf-8',
type: 'POST'
})
.done(function (result) {
alert("good");
$("#" + containername).html(result);
$(this).toggle();
})
.fail(function (jqXHR, status, errorThrown) {
alert(errorThrown);
});
});

Related

Jquery .html() does nothing with element with random html ID created with laravel (php)

So my problem is that i have multiple elements on the page with a random id.
But jquery does nothing when the code is running (but finds the element), But does when the id is hardcoded;
Generate id:
#php
$id = \Illuminate\Support\Str::random(5);
#endphp
Blade (with hardcoded "a" to prevent numbers from being in the first slot):
<div id="a{{$id}}" class="#if(isset($class)) {{$class}} #endif">
<div class="text-center p-5">
<div class="spinner-border" role="status"></div>
</div>
</div>
Script tag (below the Blade html code):
window.onload = function () {
let url = '{{$url}}';
$.ajax({
'url': url,
'method': 'GET',
dataType: 'html',
success: function (html) {
$(`#a{{$id}}`).empty()
$(`#a{{$id}}`).html(html)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('e')
}
})
};
What i tried:
Different "quote" types " ' `
Hardcoded id (That works :S )
Frontend HTML code on render:
<div id="aGwGES" class="">
<div class="text-center p-5">
<div class="spinner-border" role="status"></div>
</div>
</div>
<script>
window.onload = function () {
let url = '/blablabla';
$.ajax({
'url': url,
'method': 'GET',
dataType: 'html',
success: function (html) {
$(`#aGwGES`).empty()
$(`#aGwGES`).html(html)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('e')
}
})
};
</script>
Result:
Nothing happens (exept for the ajax call)
Loader stays there
Extra images:
Frontend html: https://i.ibb.co/fFGrmGN/image.png
Console: https://i.ibb.co/QpY11Vm/image.png
Element that should be empty (no loader):
https://i.ibb.co/8DYVDVt/image.png
it might just be that success is never reached cause of 'method' & 'url' format. try this
window.onload = function () {
let url = '{{$url}}';
$.ajax({
url: url,
method: 'GET',
dataType: 'html'
}).done( function (html) {
$(`#a{{$id}}`).empty()
$(`#a{{$id}}`).html(html)
}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log('e')
});
};
You did maybe try the first code with .get() then switched to .ajax()
I found the problem. The problem was this line:
window.onload = function () {
I am not 100% sure if I am correct, But the problem was that I overwrite the onload function.
And that made only 1 work, The last one.
Example:
https://jsfiddle.net/fvcmrn4z/
it skips all other scripts and goes to the last one,

jquery ajax form submit with edit values

I have a datatable where I have the detail column with an edit button. When the user clicks on the edit am passing the id as a parameter. I am fetching all the values for that id and displaying in the form. Now when I edit the values and submit the form using PUT method it is getting inserted in the table, the values are passing as a parameter and it shows the empty form. How to solve this issue.
HTML:
<form class="container" id="myform" name="myform" novalidate>
<div class="form-group row">
<label for="position" class="col-sm-2 col-form-label fw-6">Position</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" required>
</div>
</div>
<div class="form-group row">
<label for="location" class="col-sm-2 col-form-label fw-6">Location</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="location" name="location" placeholder="Location" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PUT Method Script:
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
GET method script:
<script type="text/javascript">
$(document).ready(function(){
var id_val;
var params = new window.URLSearchParams(window.location.search);
id_val = params.get('id');
console.log(id_val);
var url1=id_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
type: "GET",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
console.log(typeof(data));
$("#position").val(data.position);
$("#location").val(data.location);
},
error: function(data) {
console.log(data);
}
});
});
</script>
After submitting the form the page should remain the same with edit form values. only the edited values should be inserted. How to achieve this.
$('#myform').on('submit', function (e) {
e.preventDefault();
..........
I have checked your code in my editor. There are some changes which i made in ajax request, and it now works for me. here is the code. Try it
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
e.preventDefault();
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
method: 'POST', //or you can use GET
dataType : "json", //REMOVED CONTENT TYPE AND ASYNC
data: {send_obj:JSON.stringify(parms)}, //ADDED OBJECT FOR DATA
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
Adding prevent default in form submit handle is enough. You're handling the post request by ajax call.
e.preventDefault();
There are 2 changes in your code.
This code will prevent your page from reloading and also you are not sending the data in proper format.
$("#myform").submit(function(e) {
e.preventDefault(); // 1. Dont reload the page
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: parms, // 2. Just send the parms object bcoz you already defined the dataType as json so it will automatically convert it into string.
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});

How to print json console.log data in browser?

I'm trying to output Json data in browser using javascript but i was only able to output in console.log i don't know what to search of. I'm a beginner in javascript please help me out here.
script.js
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});
index.php
<input id="movie" type="text" /><button>Search</button>
This code output all the data in console.log but i wanna do is it should display data in browser and i wanna output some specific objects like title of movie and overview and image.
Retrieve the specific values using key and show it. The object have keys and values. Doing object.key will give the value
$(document).ready(function() {
var url = 'https://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
$("#title").text(json.title);
//$("#movTitle").prop('src'); // add image path here
$("#overview").text(json.overview) //overview is a key
},
error: function(e) {
console.log(e.message);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<!-- Search This: 346364 -->
<div id="title">
</div>
<div>
<img id="movTitle" src="" alt="">
</div>
<div id="overview">
</div>
To output your JSON data to the browser, you need to modify the HTML of the page.
First, add a few elements to your index.php like so:
index.php
<input id="movie" type="text" /><button>Search</button>
<h1>Movie info:</h1>
<p>Movie title: <span id="movie-title"></span> </p>
<p>Movie budget: <span id="movie-budget"></span> </p>
Then, in your success callback that you are defining in the jQuery ajax request, you can grab the span elements and replace their text by using jQuery's text function like so:
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
// grab the span elements by ID and replace their text with the json text
$("#movie-title").text(json.title);
$("#movie-budget").text(json.budget);
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});

save dynamic input form data into database kendo ui

i have populated dynamic input form fields. its populated successfully.i do not have an idea how to save data into database by using put/post api. as i used get api.
html code
<div id="renderform" class="form horizontal-form form-body">
<!-- container UL to host input fields -->
<div class="row" data-template="fieldsTemplate" data-bind="source:fields">
</div>
<!-- button to save changes -->
<button id="save" class="btn btn-circle btn-sm btn-default" type="button">Save</button>
</div>
kendo template
<script id="fieldsTemplate" type="text/x-kendo-template">
<div class="form-group">
<label class="control-label" data-bind="attr: { for: name}, text: ItemLabel"></label>
<div class="">
<input class="form-control-static" type="text" />
</div>
</div>
</script>
ajax function
<script type="text/javascript">
// retrieve the model from an API call
$.ajax({
url: crudServiceBaseUrl + "FormItemsDesign/GetFormItemsDesignList?parentid=" + formdesignid,
//url :"json.txt",
type: "GET",
dataType: "json",
success: function (model) {
// convert the JSON to observable object
var viewModel = kendo.observable(model);
// bind the model to the container
kendo.bind($("#renderform"), viewModel);
}
});
</script>
Post/Put api's will be like
url: crudServiceBaseUrl + "FormItemsDesign
type:Post
type:Put
please help me, how to make/use ajax function to call Post/Put to save/update data by each dynamic field into database. i appreciate your valuable time and effort thanks in advance.
After reading more articles finally I found this solution. Its working for me.
$("#save").on("click", function () {
$("#renderform input").each(function () {
var dataModel = {
parentid: $(this).attr("id"),
ItemOrder: "1",
ItemFieldType: "1",
ColWidth: "100",
RowHeight: "100",
ItemText: $(this).val(),
ItemLabel: $(this).attr("name")
};
$.ajax({
type: 'POST',
url: crudServiceBaseUrl + "FormsItem?firmid=" + firmid + "&createdby=" + clientid,
data: JSON.stringify(dataModel),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
alert("Data Saved successfully");
});

Not able to submit field value with Ajax

I know that there was a similar questions to this, but I tried everything and nothing seems to work. I'm not that good with ajax thats why i posted this question.
$("#buttons_holder").find("#add_users").click(function() {
var ob = document.getElementById('all_users[]');
var selected = new Array();
for (var i = 0; i < ob.options.length; i++) {
if (ob.options[i].selected) {
selected.push(ob.options[i].value);
}// if
}// for
var selected_users = selected;
var link = $("#buttons_holder").find("#add_users").attr('href');
$.ajax({
url: link,
type: 'POST',
data: {
s : selected_users
},
'success': function(data){
alert ('succes');
},
'error' : function(data) {
alert ('fail');
}
});
});
And I always get fail alerted. I try to alert all parametes(selected_users, link) before function and everything seems ok. Can anyone tell me what could be a problem? Thanks you all very much for your answers.
EDIT: Here's my HTML Code:
<div class="main_content">
<div id="users_holder">
<div class="div_grids">
<div class="inline_wrapper">
<h4>Users that belong to selected company:</h4>
<label for="company_users">
<select multiple="" name="company_users[]" id="company_users[]">
<option value="1">admin#sms.com</option>
<option value="3">b#bba.com</option>
<option value="5">dfsdf#dmfkdmf.com</option>
</select>
</label>
</div>
<div style="margin-top:2%; margin-left:5%; margin-right:5%" id="buttons_holder" class="inline_wrapper">
<div class="common_add_button">
<a id="remove_users" name="remove_users" href="http://localhost/cake/crawler/companies/1/manage-agents/remove"> >> </a>
</div>
<div class="common_add_button">
<a id="add_users" name="add_users" href="http://localhost/cake/crawler/companies/1/manage-agents/add"> << </a>
</div>
</div>
<div class="inline_wrapper">
<h4>All users:</h4>
<label for="all_users">
<select multiple="" name="all_users[]" id="all_users[]">
<option value="4">11111#qweqwe.com</option>
</select>
</label>
</div>
</div>
SOLUTION:
$("#buttons_holder").find("#add_users").click(function() {
var selected_users = $('#all_users option:selected').map(function() {
return this.value
}).get();
var link = '{$add_users_link}';
$.ajax({
url: link,
type: 'POST',
data: {
'new_users' : selected_users
},
'success': function(data) {
App.Messages.showOkFlashMessage(data);
},
'error': function(data) {
App.Messages.showErrorFlashMessage(data.responseText);
}
});
return false;
});
When I use Ajax and arrays, I always pass the data as string and deserialize on the server.
Since the parameters seem to be ok to you, maybe you can try this:
$.ajax({
url: link,
type: 'POST',
data: { s : JSON.stringify(selected_users) },
'success': function(data) { alert ('success'); },
'error': function(data) { alert ('fail'); }
});
#Marko Vasic Ajax require Json format data so you have to send data in json format like
JSON.stringify({ s: selected_users })
var selected_users = selected;
var link = $("#buttons_holder").find("#add_users").attr('href');
$.ajax({
url: link,
type: 'POST',
data:
JSON.stringify({ s: selected_users }),
'success': function(data){
alert ('succes');
},
'error' : function(data) {
alert ('fail');
}
});
});

Categories