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');
}
});
});
Related
So I'm building a social network as a personal hobby but, recently, when I try to Like a post the console log returns that error above. The code was working just fine in the last days but out of no where this error popped up.
Restapi code for liking a post:
if ($_GET['url'] == "likes")
{
$postId = $_GET['id'];
$token = $_COOKIE['SNID'];
$likerId = $db->query('SELECT user_id FROM tokens WHERE token=:token', array(':token'=>sha1($token)))[0]['user_id'];
if (!$db->query('SELECT user_id FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$postId, ':userid'=>$likerId))) {
$db->query('UPDATE posts SET likes=likes+1 WHERE id=:postid', array(':postid'=>$postId));
$db->query('INSERT INTO post_likes VALUES (\'\', :postid, :userid)', array(':postid'=>$postId, ':userid'=>$likerId));
//Notify::createNotify("", $postId);
} else {
$db->query('UPDATE posts SET likes=likes-1 WHERE id=:postid', array(':postid'=>$postId));
$db->query('DELETE FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$postId, ':userid'=>$likerId));
}
echo "{";
echo '"Likes":';
echo $db->query('SELECT likes FROM posts WHERE id=:postid', array(':postid'=>$postId));
echo "}";
}
script desing:
$.ajax({
type: "GET",
url: "restapi/posts",
processData: false,
contentType: "application/json",
data: '',
success: function(r) {
var posts = JSON.parse(r)
$.each(posts, function(index) {
$('.timelineposts').html(
$('.timelineposts').html() + ' <li class="list-group-item" id="'+posts[index].postId+'" style="border-color: #cbcbcb;"><blockquote class="blockquote"><p class="mb-0" style="color: rgb(0,0,0);">'+posts[index].PostBody+'</p><footer class="blockquote-footer">Posted by '+posts[index].PostedBy+' on '+posts[index].PostDate+'</footer></blockquote><button data-id="'+posts[index].postId+'" class="btn btn-primary" type="button" style="background-color: rgba(0,0,0,0);color: rgb(0,0,0);width: 142px;font-family: Alegreya, serif;" > <i class="icon-fire" data-bs-hover-animate="rubberBand" style="color: rgb(36,0,255);" ></i> '+posts[index].Likes+' likes</button><button class="btn btn-primary" type="button" style="background-color: rgba(0,0,0,0);color: rgb(0,0,0);width: 142px;font-family: Alegreya, serif;" onclick="showCommentsModal()" data-postid="'+posts[index].postid+'" > <i class="typcn typcn-pencil" data-bs-hover-animate="rubberBand" style="color: rgb(255,0,0);"></i> Comentários</button> </li> </ul> '
)
$('[data-postid]').click(function() {
var buttonid = $(this).attr('data-postid');
$.ajax({
type: "GET",
url: "restapi/comments?postid=" + $(this).attr('data-postid'),
processData: false,
contentType: "application/json",
data: '',
success: function(r) {
var res = JSON.parse(r)
showCommentsModal(res);
},
error: function(r) {
console.log(r)
}
});
});
$('[data-id]').click(function() {
var buttonid = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "restapi/likes?id=" + $(this).attr('data-id'),
processData: false,
contentType: "application/json",
data: '',
success: function(r) {
var ress = JSON.parse(r)
$("[data-id='"+buttonid+"']").html(' <i class="icon-fire" data-bs-hover-animate="rubberBand" style="color: rgb(36,0,255);"></i> '+ress.likes+' likes</span>')
},
error: function(r) {
console.log(r)
}
});
})
})
},
error: function(r) {
console.log(r)
}
});
});
Already verify all queries and they work fine in the sql.
EDIT::
Try
echo"<pre>";print_r($_GET); exit();
and see if you get any data in the backend
when you send data form the backend, do so in the following format
function listOfComments(){
$response=[
"success"=>0,
"message"=>"",
"data"=>[]
];
//database queries
if($databaseResponse){
$response=[
"success"=>1,
"message"=>"",
"data"=>$databaseResponse
];
}else{
$response["message"]=>"No Data"
}
return json.encode($response);
}
On the front end in javascript you could do
var ress = JSON.parse(r);
if(ress.success){
// render UI
}else{
alert(ress.message);
}
I'd be willing to help you out if you could share the link to your git hub repo.
Use https://json2html.com/ to render data on the front end.
Use onClick event on a class and not a custom attribute.
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);
},
})
});
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);
});
});
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);
}
});
});
});
I have this html markup:
<!-- ko foreach: Orders -->
<div class="row">
<div>
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }">
</select>
</div>
<div>
<a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right">
<span class="glyphicon glyphicon-cloud-download"></span> Download
</a>
</div>
</div>
<!-- /ko -->
There will be n number of items in the foreach loop, that will not be known in the moment of development.
What I want to do is when the $root.RequestImage is clicked, the code needs to check if there is selection made in the respected dropdown for that row, if the selection is made then proceed further, otherwise display alert box with 'error' message.
So in the RequestImage that action should happen, this is the RequestImage function currently:
self.RequestImage = function () {
};
How can I achieve this?
Update
OrdersVM:
var self = this;
self.Orders = ko.observableArray([]);
$.ajax({
type: "POST", url: "/webservices/InfoWS.asmx/GetOrders",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
var orderIds = [];
ko.utils.arrayForEach(data.d, function (item) {
item._teacherOrders = ko.observable();
$.ajax({
type: "POST",
url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount",
contentType: "application/json; charset=utf-8",
data: "{'orderId': " + JSON.stringify(item.OrderId) + "}",
dataType: "json",
success: function (data) {
if (data) {
return item._teacherOrders(data.d);
}
},
error: function (n) {
alert('Error retrieving teachers for orders, please try again.');
}
});
item.TeacherNames = ko.computed(function () {
return item._teacherOrders();
});
self.Orders.push(item);
orderIds.push(item.OrderId);
});
}
},
error: function (data) {
var response = JSON.parse(data.responseText);
console.log("error retrieving orders:" + response.Message);
}
});
I would do it this way:
add an observable selectedTeacher to every order object
add value: selectedTeacher to your selects:
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select>
check that observable in your RequestImage event
if ( !data.selectedTeacher() ) {
alert('Error: select teacher')
} else {
alert('Success')
}
A working demo - Fiddle