Icon not changing in ajax success handler - javascript

I'm trying to make a function 'add to my list' in my web application.
When user clicks on an icon, this fuction should change the color of the icon after sending data to server.
It doesn't throw any errors, it sends data to server successfully, but it never changes the icon. 'console.log' inside ajax success handler is working fine, so what is the problem here?
Thanks in advance!
<div class="buttons">
<button type="button" class="btn threeButtons" onclick="request_access(this)" id="{{ elem['isbn'].split()[0] }}">
<i class="fas fa-plus"></i>
</button>
</div>
function request_access($this){
console.log("button clicked");
var request_data = $this.id;
var me = $(this);
$.ajax({
url: "/admin_add_books",
type: "POST",
data: request_data,
success: function(){
console.log("data: " + request_data)
me.find('i').addClass('green');
}
})
}

If you want to do sthg just after data is sent but response is not sent from server, then you should do sthg like:
var response = $.ajax({
url: "/admin_add_books",
type: "POST",
data: request_data
});
// Change color just after data is sent
me.children("i").addClass("green");
response.done(function(result){
// Server returned result
me.children("i").addClass("green");
});
*Note:- success is depreciated in modern version of jquery. Link

Related

Button Load with ajax request but click event dont show up the model with ajax success function data

from my php page searching employee retrieve by ajax success function and displayed as button ! when i click on fetched button it works like post request 200 ok! but modal dont show up and not even updated with my new ajax request result !!
I want to display searched employees information via modal!
i have tried many approach!
click function, on click function, delegate function does not work!
click function, on click function, delegate function does not work!
even clcik event on parent element
button fetched by this request
$("#searchEmployeeForm").on('submit',(function(e) {
e.preventDefault();
if ( $("#selectCompany").val()!="" || $("#selectDepartment").val()!="" || $("#selectDesignation").val()!="" || $("#searchByName").val()!="" || $("#searchByID").val()!=""){
$.ajax({
url: "controller/employee/find_Employee.php",
type: "POST",
// Type of request to be send, called as method
data: new FormData(this),
contentType: false,
dataType: 'json',
cache: false,
processData:false,
success: function(data)
{
$('#listOfEmployee').empty();
$.each(data, function (i, empdetail) {
console.log(empdetail);
$('#listOfEmployee').append("<button class='list-group-item d-flex justify-content-between align-items-center viewEmployeeData' id= "+ empdetail.emp_id +">"+ empdetail.first_name + empdetail.last_name + "</button>" );
});
console.log("data:" + data);
}
});
}
else{
alert("Field Can not be Empty ");
}
}));
button on click event
$(document).on('click', '.viewEmployeeData', function (e){
e.preventDefault();
console.log('limon ');
var employee_id = $(this).attr("id");
alert(employee_id);
if(employee_id)
{
$.ajax({
url:"controller/employee/employee_info.php",
method:"POST",
dataType: 'json',
data:{employee_id:employee_id},
success:function(data){
$('.modal-title').html(data.firs_name);
$('#view_employee_data_modal').modal("show");
alert(data);
}
});
}
});
i expected button click event will display modal with my ajax request data!
NB: click event works but only its console.log and alert modal dont show up after ajax success function.
when ajax success return data and add in dom and that dom event can not bind directly so you bind event in main dom it mean return data fill in "listOfEmployee" dom here event bint so work perfectly.
$('#listOfEmployee').on('click','.viewEmployeeData',function(e){
e.preventDefault();
console.log('limon ');
var employee_id = $(this).attr("id");
alert(employee_id);
if(employee_id)
{
$.ajax({
url:"controller/employee/employee_info.php",
method:"POST",
dataType: 'json',
data:{employee_id:employee_id},
success:function(data){
$('.modal-title').html(data.firs_name);
$('#view_employee_data_modal').modal("show");
alert(data);
}
});
}
});

JavaScript - post request to Symfony

I wrote a function to sent a simple request trough Controller via JavaScript in my Symfony project. My alert is triggered when I refresh the page and it should be triggered when I am clicking the Submit button.
What I am doing wrong?
Button:
<button type="button" id="request" data-path="{{ admin.generateObjectUrl('change_status', object) }}" class="btn btn-primary">Submit</button>
My JS code:
var path = $("#request").attr("data-path");
$.ajax({
type: "POST",
url: path,
data: {id : 'aaa'},
"success":function(data){
alert('ok');
}
});
and Controller:
$data = $request->request->get('request');
return new Response($data);
You have to set the onclick property in your button and wrap your JS code in a function that will be called by this onclick

javascript ajax and post value is working all together why

I am having a some problem in my java script and to get the request.
This is the HTML
<form method="post" id="searchform">
<div align="center" class="col-md-10">
<input type="text" id= "contentSearch" name="contentSearch" >
</div>
<div class="form-group"><button type="submit" class="btn btn-default" id="submitSearch">
<i class="fa fa-search"></i> Search
</button></div>
</form>
<----Scenario 1 ---->
This script works fine and post the value and as ajax it never reload the page
<script>
$(document).ready(function () {
$("#submitSearch").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
// Submit data via AJAX§
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
// do i need to do something here !!
}
});
});
});
</script>
When i check the POST value i can see the value is been POST.
The Problem is when i try to get the request data from controller like ---
$post_value = $request->request->get('contentSearch');
print_r($post_value);
OUTPUT : empty
<----Scenario 2 ---->
This script have a problem i think, because it reload the page for returning the result and displaying the value ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
e.preventDefault();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}),
return false;
});
});
</script>
than i am able to get the post value like so--
$post_value = $request->request->get('contentSearch');
But the problem is in the second script the page is always loading when return the request which is not a ajax behave.
And in the first script i think because of the **e.preventDefault();** i am not getting the POST value in my controller.
Expected result ---
Option 1 : Do something so i can get the POST value in my controller
Option 2 : Fix this script so the page do not load to return the result and display
I am working on symfony framework .
Can someone please help me to fix this problem, i am really getting sick of to solve this problem.
Thanks a lot on advanced.
Like I mentioned in the comments, you need to be targeting the submit on the form. Not a click event. When targeting the click you are firing both the click and submit events, hence the reload.
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}
});
return false;
});
});

changing the class of clicked button on ajax function success

i have a several html buttons (not within a form).
When clicked they call a JavaScript function that after conformation, runs an ajax call.
This part all works OK, but i would then like to change the class of whichever button was clicked on success of the ajax call.
i have tried various methods seen on stackOverflow, but none of them seem to work...
can i please ask what am i doing wrong?
here is the simplified HTML (buttons)
<button class="btn btn-primary" onclick="primaryImage(4107,19372,'/abbie1.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-primary" onclick="primaryImage(4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-success" onclick="primaryImage(4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
Please note: the last button is already the active/success button, and i would also like to remove the class on success too (as only one should be active), but that is maybe my next stage....
here is the javaScript, (i have left in some of the methods i have tried, but commented them out)
function primaryImage(eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
alert('The image is now set as the profile image');
//$('button').click(function(){
// $(this).addClass('btn-success');
//});
//$('button').on(data.result=='success', function(e) {
// $(this).toggleClass("btn btn-success"); //you can list several class names
// e.preventDefault();
//});
//$(this).removeClass('btn-primary').addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
I would be very grateful for any advice of what i am doing wrong
(as you can see, i am not too good with JS (yet))
Thanks!
Ford
As noted in your commented out code, you are binding the click event after click event has already been fired.
I would suggest you to pass a reference of the button that was clicked in the primaryImage() function itself as such:
<!-- In your HTML -->
<button class="btn btn-success" onclick="primaryImage(this, 4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
function primaryImage(button, eid,pid){
/** ... */
Then using that referenced button, you can add or remove CSS classes to the element, as well as the siblings of the element (using jQuery's siblings() method).
//your ajax call
success: function(data){
if(data.result=='success') //make sure this really is success
{
alert('The image is now set as the profile image');
$(button).removeClass('btn-primary').addClass('btn-success');
$(button).siblings('button').removeClass('btn-success').addClass('btn-primary');
}
}
As you don't use the jQuery .click() event, I think you need to pass the button in your function args.
So your button will look like
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
Then your function will be like
function primaryImage(el, eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "http://anzvirtuel.org",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
$(el).addClass('btn-success');
alert('The image is now set as the profile image');
// keep doing whatever you want...
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
As I have not fully understood your commented JS I'll let you put the code you want, just remember that your button will be accessible in jQuery with $(el).
Hope it may helps you
You should pass the clicked element to the primaryImage() function, and use it on success to do whatever you like.
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19372,'/abbie1.jpg'); return false;">set as profile image</button>
And in your JS
function primaryImage(element, eid,pid)
{
[...]
success: function(data){
if(data.result=='success')
{
$(element).addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
[...]
}
You could use data-* attributes instead of onclick (MDN Documentation) and then access those throught jQuery, so your code is more clean and HTML / JS are separated.
Try this code, I've created three data attributes (data-eid, data-pid and data-image) for your params and also replaced your JS to make the whole stuff work with those data attributes. Those attributes can be accessed with following jQuery code - var eid = $(this).attr('data-eid'); as an example
This line of code removes the btn-primary class from the clicked button, adds a btn-success class to it and disables it, so it can't be toggled again.
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
HTML
<button class="btn btn-primary" data-eid="4107" data-pid="19372" data-image="/abbie1.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19373" data-image="/abbie2.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19374" data-image="/abbie3.jpg">
profile image
</button>
JS
$(".btn").click(function (e) {
if (confirm("Are you sure you wish to use this as your profile image?")) {
var eid = $(this).attr('data-eid'); //like 4107
var pid = $(this).attr('data-pid'); //like 19372
var image = $(this).attr('data-image'); //like /abbie1.jpg
var pushedBtn = $(this);
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid=" + eid + "&pid=" + pid,
//context: this,
success: function (data) {
if (data.result == 'success') {
alert('The image is now set as the profile image');
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
} else {
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
});

Passing jquery variable into php script in a modal with ajax

i'm having problem getting the value of a variable into the modal which is supposed to be openning. i have tried using post but nothing changed. Both codes are in index.php.
This is the jquery script passing the value
$(document).ready(function () {
$(".issue").click(function () {
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function () {
$("#modal2").modal('show');
}
});
});
});
And i tried echoing the id of class .issue but it doesn't works
<div class="modal fade" role = "dialog" id = "modal2" aria-labelledby = "myModalLabel" aria-hidden = "true">
<div class="dialog">
<div class="modal-content">
<div class="modal-body"><?php echo $_GET["data1"]; ?></div>
</div>
</div>
</div>
You're missing the variable in the success method. It should be success:function(ajaxData){}
So in all:
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function (ajaxData) { // ajaxData is the return data from php
// add the data to the modal
$("#modal2 .modal-body").html(ajaxData);
$("#modal2").modal('show');
}
});
Are you sending the data server side to save it, or grab information from the database? If all you're trying to do is move the data to the modal, ajax isn't necessary.
Part of me suspects you're not properly calling and passing the data to php, if you really do need ajax. The php you send the ajax data to should be a separate file, that receives it, processes it, and echos it back to the ajax success function. Then the ajax function puts the data in the modal and displays the modal.
Hope one of those thoughts points you in the right direction.

Categories

Resources