jquery=>Sending data - javascript

Iam working on adding an event planner to my Html form ,
and i cant figure out how to pass this data ("meetup","startEvent","break") from html to my Database .
ive used jQuery to show the data on my browser console like this and it work
$(document).ready(function(){
$('#bang').on("click", function(){
$("#editable > li").each(function(){
$e=($(this).text());
console.log($e);
but i cant get it to send to another page
$(document).ready(function(){
$('#bang').on("click", function(){
$("#editable > li").each(function(){
$e=($(this).text());
console.log($e);
$("#submit").click(function(){
$.ajax(
{
url: "test.php",
type: "POST",
data: {$e},
success: function (result) {
alert('success');

jQuery('#bang').on("click", function () {
var data = [];
jQuery("#editable > li").each(function () {
data.push(jQuery(this).text());
});
console.log(data);
jQuery.post('test.php', data).done(function () {
console.log('Done!');
}).fail(function () {
console.log('Nopo!');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="editable">
<li>test</li>
<li>me</li>
<li>out</li>
</ul>
<button id="bang">bang!</button>

Related

JQuery sortables, how to keep sorting after ajax request_

So, I am doing a laravel project where I am using Jquery sortables to sort some data and then using ajax to update the order in my database.
laravel blade code
<div id="gallery" style="width: 80%">
<div id="image-container">
<ul id="product-list" >
#foreach ($images as $key=>$image)
<li id="product_{{$key}}" class="inline-block" style="width: 20%">
<img id="li_product_{{$key}}" src="s3 source">
</li>
#endforeach
</ul>
</div>
</div>
JQuery Code :
<script>
$(document).ready(function () {
var dropIndex;
$("#product-list").sortable({
update: function(event, ui) {
dropIndex = ui.item.index();
var productIdsArray = [];
var i = 0;
$('#product-list li').each(function (index) {
var id = $(this).attr('id');
var split_id = id.split("_");
productIdsArray .push(parseInt(split_id[1]));
});
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/update",
type: 'post',
data: {
productIds: productIdsArray,
},
success: function (response) {
console.log(response);
}
});
}
});
});
</script>
It is working fine for the first time...updating data in the databse. and If I refresh the page and try again, it is fine. But If I keep changing order without refreshing, then it is not changing the dom...and the order is getting messed up. I need to know, how do I keep sorting the order without refreshing the page properly.

submit button is not working on first click

I have a submit button inside a form like-
jQuery(document).ready(function() {
$("#VEGAS").submit(function() {
$('#One').click(function() {
var form_data = $("#VEGAS").serialize();
var routeUrl = "<?= url('/') ?>/vpage";
$.ajax({
url: routeUrl,
type: "POST",
data: form_data + '&jegy=' + test,
success: function(result) {
$('#alert').html('successfully added!');
$('#msg-group').delay(1000).hide('slow');
}
});
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button id="One" type="submit" name="submit_5" class="submitBTN addnowBtn" value="Light Nightclub">Add Now</button>
Every thing is working fine but above button is not working on first click. How can i get rid of this issue ?
$('#One').click(function(){...})
should be registered in
jQuery(document).ready(function () {...})
as
jQuery(document).ready(function () {
$('#One').click(function(){...})
});
since, in your code you are registering the $('#One').click() in $("#VEGAS").submit() therefore the $('#One').click() is registered when the $("#VEGAS").submit() gets called for the first time. Hence, in the first attemp this doesn't works but works in the second attempt.
Try this: you are binding click event handler for one button inside form submit hence it is binding click event handler on first click and on second click it is calling click handler.
You can remove click event for button and use below jquery code
HTML:
<button id="One" type="submt" name="submit_5" class="submitBTN addnowBtn" value="Light Nightclub">Add Now</button>
jQuery:
jQuery(document).ready(function () {
$('#VEGAS').on("click",function (event) {
event.preventDefault();
var form_data = $("#VEGAS").serialize();
var routeUrl = "<?= url('/') ?>/vpage";
$.ajax({
url: routeUrl,
type: "POST",
data: form_data + '&jegy=' + test,
success: function (result) {
$('#alert').html('successfully added!');
$('#msg-group').delay(1000).hide('slow');
}
});
});
Inside submit() the .click() is unnecessary:-
Remove $('#One').click(function () {
Use either one (either .submit() or .click())
So:-
Either
<script>
jQuery(document).ready(function () {
$("#VEGAS").submit(function (e) {
e.preventDefault();
var form_data = $("#VEGAS").serialize();
var routeUrl = "<?= url('/') ?>/vpage";
$.ajax({
url: routeUrl,
type: "POST",
data: form_data + '&jegy=' + test,
success: function (result) {
$('#alert').html('successfully added!');
$('#msg-group').delay(1000).hide('slow');
}
});
return false;
});
});//missed in your code
</script>
Or
<script>
jQuery(document).ready(function () {
$('#One').click(function (e) {
e.preventDefault();
var form_data = $("#VEGAS").serialize();
var routeUrl = "<?= url('/') ?>/vpage";
$.ajax({
url: routeUrl,
type: "POST",
data: form_data + '&jegy=' + test,
success: function (result) {
$('#alert').html('successfully added!');
$('#msg-group').delay(1000).hide('slow');
}
});
});
return false;
}); //missed in your code
</script>
Note:-
if you have multiple id which are same then it's completely wrong. either covert them to class or give different id to each-one
Check your browser developer console to see all errors which are raised and rectify all of those
var routeUrl = "<?= url('/') ?>/vpage";
Here is the error. use static path here.
<script>
$(document).ready(function () {
$("#VEGAS").submit(function () {
var form_data = $("#VEGAS").serialize();
var routeUrl = "vpage";
$.ajax({
url: routeUrl,
type: "POST",
data: form_data + '&jegy=' + test,
success: function (result) {
$('#alert').html('successfully added!');
$('#msg-group').delay(1000).hide('slow');
}
});
return false;
});
});
</script>

Chosen plug-in is not working when i create the element dynamically

Chosen plug-in is not working when i create the element dynamically
i created Select list dynamically from ajax response and the problem is Chosen plug-in not working with it , Please help me to solve it
here is my code:
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: '/Home/GetSubCategoriesByAjax',
type: 'GET',
datatype: 'Json',
data: { id: ID },
success: function (data) {
if (data.length > 0) {
console.log(data)
$("#SubListSelect").empty();
var $SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>');
$SubListSelect.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
$SubListSelect.append('<option value=' + value.SubCategoryId + '>' + value.SubCategoryName + '</option>');
});
$("#Div1").empty();
$("#Div1").append($SubListSelect);
}
else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
and and plugin code:
$(document).ready(function ($) {
$(function () {
$("#SubListSelect").chosen();
});
Thank you
My proposal:
in my demo I used a different url for the ajax and I figured out a possible HTML.
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: "https://api.github.com/users",
type: 'GET',
dataType: "json",
data: { id: ID },
success: function (data) {
if (data.length > 0) {
var SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>')
.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
SubListSelect.append('<option value=' + value.id + '>' + value.login + '</option>');
});
$("#Div1").empty().append(SubListSelect);
$("#Div1").find(SubListSelect).chosen()
} else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
$(document).ready(function ($) {
$("#SubListSelect").chosen();
$('#btn').on('click', function(e) {
GetSubCategories('1');
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<!--
The next two lines are the include files for chosen plugin
-->
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<div id="Div1">
This is the starting div:
</div>
<button id="btn">Click Me To Create New chosen object into DIV</button>
I assume the select is in #Div1 which you are emptying, then re-appending.
in that case you need to re-initialize it:-
$("#Div1").empty();
$("#Div1").append($SubListSelect);
$("#SubListSelect").chosen();
A better option though would be to only empty the select and re-append the options to the select without emptying the #Div1. then call:-
$("#SubListSelect").trigger("chosen:updated");
also, this
$(document).ready(function ($) {
and this
$(function () {
mean the same thing, with the latter being short hand. Therefore you only need one.

jQuery ajax not remove spinner on success

After successing ajax request and saving data in database i have problem when i try to remove active class from button. On click i show spinner and when ajax finish i want remove active class. On click spinner start but never stop. I try to debug it with alert() inside success and i get message. WHat can be problem?
submiteComment: function() {
$("body").on("click", '.submit-comment', function(e) {
e.preventDefault();
var post_id = $(this).data('post');
var comment_text = $(".comment_text");
if($.trim(comment_text).length) {
$(this).addClass('active');
$.ajax({
type: "post",
url: baseurl + '/comment/create',
data: {'post': post_id, 'comment_text': comment_text.val()},
success: function() {
$(this).removeClass('active');
alert("Success");
}
})
}
});
},
And html:
<button type="submit" class="btn btn-xs btn-default submit-comment has-spinner" data-post="<?= $post->post_id;?>">
<span class="spinner"><i class="fa fa-spinner fa-spin"></i></span>
Comment
</button>
Are you sure that the this in $(this).removeClass('active'); is equal to your DOM element when your code is executed? Looks like you need rewrite part of your code as
success: (function() {
$(this).removeClass('active');
alert("Success");
}).bind(this)
you can assign $(this) as a var outside of ajax like
var $this = $(this);
$this.addClass('active');
$.ajax({
type: "post",
url: baseurl + '/comment/create',
data: {'post': post_id, 'comment_text': comment_text.val()},
success: function() {
$this.removeClass('active');
alert("Success");
}
})

Add one or two more PHP variables to the javascript code

I am a decent PHP programer and recently I got stuck in a javascript code.
I have the code below:
$(function () {
$('.more').live("click", function () {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("div#updates").append(html);
$("#more" + ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
This code submit without problems one PHP variable to the process page loadmore.php using this input
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
<a href="#" class="more" id="<?php echo $load_id; ?>">
load more
</a>
</div>
How can put more variables in the input and the javascript code to work with them on the process page?
I want to set one or two more variables.
UPDATE:
I updated the code like this:
HTML input:
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
load more</div>
JAVASCRIPT CODE:
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: {"lastmsg="+ ID, "act="+ ACT},
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
I am not sure if the data lines was writed properly because the script looks like it's frozen now
SOLVED:
I just used a datastring like this
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
var dataString = 'lastmsg='+ ID + '&act=' + ACT;
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: dataString,
//data: {"lastmsg="+ ID, "act="+ ACT },
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
Just send data as an object:
data: {
"lastmsg": "lastmsg="+ ID,
"anotherData": "someData"
}
You'll retrieve them in your PHP script as follows:
$_POST["lastmsg"];
$_POST["anotherData"];

Categories

Resources