I have a select that I am trying to do a jQuery .change event on. For some reason it is not recognizing the id of the select. It is built through another AJAX call to a php file that creates the select and its options.
<script>
$(document).ready(function()
{
$("#unitselector").on('change', function()
{
console.log('made it');
var unit=$('#unitselector').filter(':selected').val();
var dataString = {unit:unit};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/unit_info.php",
data: dataString,
cache: false,
success: function(html)
{
$('.unitinfo').html(html);
}
});
});
});
</script>
relevant PHP:
echo '<select id="unitselector" name="units">';
while( $row = mysqli_fetch_assoc($result))
{
$units[] = $row['unit_name'];
echo '<option value="'.$row['unit_name'].'">'.$row['unit_name'].'</option>';
}
echo '</select>';
It is built through another AJAX call to a php file that creates the select and its options.
That means it's dynamically added to the DOM and as such requires event delegation. jQuery 1.7+ uses the .on() method in order to bind properly.
$("#unitselector").on('change', function()
to
$(document).on('change', '#unitselector', function()
Further, there's really no reason to try and get the value like you're doing. You're inside of the element and therefore can access it through this which is the native javascript object, or $(this) which is a jQuery object, either way will work fine.
var unit = $(this).val();
//or
var unit = this.value;
Related
I am using this jQuery plugin for making toggle, but I have an issue that when I make multiple toggles that have same ids and class so in that case I am not able to identify particular toggle for applying auto load ajax on changing value.
I would to ask that how I make same toggle with this same plugin but different ids or class or name so I make ajax function like when I click toggle it will update in PHP without submitting submit button.
The plugin I am using is this one
The code I am using is this:
HTML
<p>Default: <span class="easyswitch"></span></p>
<p>Checked: <span class="easyswitch" data-default="1"></span></p>
SCRIPT
<script>
$('.easyswitch').easyswitch();
</script>
AJAX
$('MY_CLASS_NAME').change(function(){
var mode= $(this).prop('checked');
$.ajax({
type:'POST',
dataType:'JSON',
url:'test.php',
data:'mode='+mode,
success:function(data)
{
$("body").html('Operation Saved');
}
});
You can not handle easyswitch's change event. you need to create click event of it, and from it you can get the status of current toggle.
$('.easyswitch').easyswitch();
$('.easyswitch').click(function () {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
// for all controlls.
$(".easyswitch").each(function() {
var mode = $(this).hasClass('on');
toogleStatus(mode);
});
function toogleStatus(mode)
{
if (!mode) {
alert('checked')
}
else {
alert('unchecked')
}
}
Try using callback option
$('.easyswitch').easyswitch({
callback: function(val, ele) {
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'test.php',
data: { mode: val },
success: function(data) {
$("body").html('Operation Saved');
}
});
}
});
I loaded a json fuction from a php page and I append it to an UL, Which creates a list.When I delete a row, I reuse the same function to re-append the list; it works, but sometime I have to click twice before it removes theselected row.
Is there a way to simplify this process as i am new to jquery?
$(document).on('pageinit', '#two', function () {
var url="http://localhost/budget/items_list.php";
$.getJSON(url,function(result){
console.log(result);
$.each(result, function(i, field){
var budgeted_id=field.budgeted_id;
var name=field.name;
var budget_amount=field.budget_amount;
var trans_amount=field.trans_amount;
var balance=field.balance;
$("#listview").append('<li data-icon="delete">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
});
});
$(document).on("click",'.del',function(){
$("#listview").empty();
budgeted_id = (this.id);
$.post('delete_item.php',{postbudgeted_id:budgeted_id});
var url="http://localhost/budget/items_list.php";
$.getJSON(url,function(result){
console.log(result);
$.each(result, function(i, field){
var budgeted_id=field.budgeted_id;
var name=field.name;
var budget_amount=field.budget_amount;
var trans_amount=field.trans_amount;
var balance=field.balance;
$("#listview").append('<li data-icon="delete">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
})
})
});
IMHO, it isn't a bad idea to reuse the same function, you will be sure to get always the actual data you have on server-side.
From your description of the issue, I believe you just only need to chain the two ajax calls.
Here an example how to do that, adapted on the fly from jQuery documentation:
function createList(result){
$.each(result, function(i, field){
var budgeted_id=field.budgeted_id;
var name=field.name;
var budget_amount=field.budget_amount;
var trans_amount=field.trans_amount;
var balance=field.balance;
$("#listview").empty().append('<li data-icon="delete">'+name+'<span class="ui-li-count">Bal: $'+balance+'</span><a class="del" id="'+budgeted_id+'" href="#"></a></li>').listview("refresh");
});
}
function getListData(){
$.ajax({
url: "http://localhost/budget/items_list.php",
method: "GET",
dataType: "json",
success: function (result) {
createList(result);
}
});
}
$(document).on("pageinit", "#two", function () {
getListData();
});
$(document).on("click", ".del",function(){
var budgeted_id = (this.id);
var request = $.ajax({
url: "delete_item.php"
method: "POST",
data: {postbudgeted_id:budgeted_id}
});
var chained = request.then(function() {
getListData();
});
});
Please, note this is untested, but you got the idea. If there is an ajax error, your list will remain untouched, up to you to trap these errors and display in your web page a toaster notification.
If chaining the ajax calls won't work, maybe you should investigate your backend.
I've been looking for a good 3 hours and haven't found a way that works.
I'm super new to JQuery, Ajax, PHP.
All I'm looking for is how to set a callback parameter from an Ajax request using jsonp.
So basically im looking for this:
www.mysite.com/service.php?callback=value
How can I change 'value' to whatever I want from an Ajax request...
Here's the last thing I tried
$(document).ready(function(){
var output = $('#results');
$.ajax({
url: 'www.mysite.com/service.php',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback:'select',
timeout: 5000,
success: function(data,status){
var result = data;
output.append(result);
});
},
error: function(){
output.text('Failed.');
}
});
});
My service.php is this
<?php
$callback = $_GET['callback'];
echo $callback;
?>
I'd expect to see a 'select' printed on my html.
And my html is just a basic html with a <div id="results"></div> in the body.
Thank you.
First of all, in service.php use return $callback;.
Next, create the select element inside the success function:
var select = document.createElement('select');
var option = document.createElement('option');
option.id = result;
option.value = result;
I recently asked a question about triggering dynamically created divs, and was introduced to the .on() function.
'keyup' works great, 'mouseover' works, a few others I've tested work but 'click' just will not fire.
I created added information to a div via ajax and .php which holds some data like this:
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html);
}
});
}
I wanted to trigger on keyup for an element within that created div and this code works for that:
$("#notebox").on('keyup', '.note-field', function(event){
var thisString = $(this).val();
$keyLength = thisString.length;
$rowCount = Math.ceil($keyLength/40);
$currentRow = $(this).attr("rows");
if($currentRow < $rowCount){
$(this).animate({rows:$rowCount},50);
}
});
This code however does NOT work:
$("#notebox").on('click', '.note-field', function() {
alert("clicked");
});
dynamic DOM and jQuery is a pain. I know its deprecated but I have used in the past with great results: http://api.jquery.com/live/
FWIW - you could also try using bind() - http://api.jquery.com/bind/
I had an .stopPropagation(); somewhere else in the code in the encompassing div, I commented it out for now and it works, thanks.
Is it possible to attach click event after html is appended.
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html).bind('click', function() { /* Click event code here */ }); // id divID is #notebox
}
});
}
You can just use click like this:
$("#notebox").click( function() {
alert("clicked");
});
http://jsfiddle.net/7MBw4/
Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request