How can I load data from my PHP response via ajax into a panel?
My PHP outputs correctly and I can see a table in the response, but I can;t get it to build the data on my webpage.
Here is my jquery/ajax so far. It passed the value to PHP correctly and PHP builds the table via its echo, but what am I missing for AJAX to display the table?
PHP:
<?php
foreach ($lines as $value) {
echo "<input name='data[]' value='$value'><br/>";
}
?>
JQUERY:
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
$('#panel').load(result);
}
})
return false;
});
});
The answer to this was two fold.
I was attempting to append to my main div, which apparently can't happen. I created a new empty div and was able to load the results there.
Beyond that, the comments to change .load(results) to .html(results) were needed.
The correct jquery code is below.
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
console.log(result);
$('#test').html(result);
}
})
return false;
});
});
move your function from:
$.ajax({...,success: function(){...}});
to
$.ajax({..}).done(function(){...});
if it doesn't work, try to add async:false into the ajax object...
$.ajax({...,async:false}).done(function(){...});
Hope it helps... =}
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');
}
});
}
});
function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
}
})
});
</script>
<?php
}
I got this function in my Wordpress Plugin. I parse in some data in the function and then i do a ajax request in Javascript. That all works just fine and i get the data array as response.
The Question is, how do i get the data from the Array in Javascript into my Variable in PHP so i can put the Data into my Wordpress Options?
Try this.
you need to parse the response.
function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
var obj = jQuery.parseJSON( data);
console.log(obj.somedata);
}
})
});
</script>
<?php
}
You need to have a PHP script that gets called by the AJAX request that will write the data into your options table. There's a specific way of doing this with Wordpress: https://codex.wordpress.org/AJAX_in_Plugins
In a nutshell, you need to add an action parameter to your POST data and then hook your PHP callback function to this parameter. In your callback, you can then use update_option().
My knowledge of this is very limited, but I figured that the problem that I have is in this function. What it does is that it displays some options to be selected in an item post. From what I see it only loads when a category is changed. Because of that when you edit this post, this function will not display unless you change category to another one and then revert back to the one you want. I would like it to display every time, except for those categories that are in the if statement.
Please assist....
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function(){
if($(optgroups).children("option:selected").length){
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function(data) {
if(data) {
$("#condition-container").html(data);
}
}
});
}
});
});
You just need to trigger your change event on document load. So under you on change function put this code
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function () {
if ($(optgroups).children("option:selected").length) {
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function (data) {
if (data) {
$("#condition-container").html(data);
}
}
});
}
});
});
//Trigger change
$(document).ready(function () {
$("#catId").trigger("change");
});
hi I assume you want the function fired on document load and on change, but for that you will need to use 2 triggers.
1) you allready have the on change trigger
2) use the $(document).ready() (https://learn.jquery.com/using-jquery-core/document-ready/) wrapper for onload.
There is possibly a much more gracefull solution, but I'm no JS expert so this will only get you to a working, although not the pretiest state
I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.
Im using the jquery .load function to query a php file that will output some data. Now sometimes the script will return nothing. In this case, can I have the load function not put any data into my specified div? (right now it clears out the div and just puts a blank white area.
Thanks!
try using $.get;
$.get('<url>',{param1:true},function(result){
if(result) {
$('selector').html(result);
}
else {
//code to handle if no results
}
});
Use $.get
http://api.jquery.com/jQuery.get/
in addition to #jerjer's post, you can also use this:
var paramData= 'param=' + param1 + '&user=<?echo $user;?>';
$.ajax({
type: "GET",
data:paramData,
url: "myUrl.php",
dataType: "json", // this line is optional
success: function(result) {
// do you code here
alert(result); // this can be an any value returned from myUrl.php
},
statusCode: {
404: function() {
alert('page not found');
}
}
});