I have a PHP page with 2 sections side by side. The left pane has a MySQL query that runs and produces a list of categories as links. The right pane should have subcategories that appear when links in the left pane are clicked.
I have some AJAX in an attached JS file that should pass the ID in the links from the left pane, into a query in the right pane. The query should run. It runs if I take out a variable.
The PHP/SQL Queries work fine. JS does not.
I think this is the appropriate way of doing this.
ajax.js
$( document ).ready(function() {
$( 'a' ).on( 'click', function() {
var a = $( this ).attr( 'id' );
$.ajax({
type: "POST",
url: "categories.php",
data: "ajax="+a,
success: function(response){
alert( a );
},
error: function() {
alert('Error');
}
})
});
});
I am being told everything works, but I cannot call $_POST['ajax'] in PHP. Perhaps my page is not being refreshed. There is no form on the page.
Lastly, my file hierarchy has categories.php comprised of a list of includes, which are in a folder that is not public.
I think your ajax syntax is wrong. Try this if your argument is a and your post identifier is ajax:
$( document ).ready(function() {
$( 'a' ).on( 'click', function() {
var a = $( this ).attr( 'id' );
$.ajax({
type: "POST",
url: "categories.php",
data: {ajax : a},
success: function(response){
alert( a );
},
error: function() {
alert('Error');
}
});
});
});
Try setting async: false on your $.ajax call. Also, how is the data being return from php? Are you using JSON_ENCODE for the data?
Related
I got a simple POST call to a PHP file on my website. For some reason it's not working though. The console.log shows"undefined"
function check() {
var url = "../API/keychecker.php";
var spullen = $("keyval").val;
$.ajax({
type: "POST",
url: url,
data: {
key: spullen
},
success: function(data) {
console.log(data);
}
})
}
Here is the PHP file:
<?php
echo json_encode($_POST['key']);
?>
Your keyval call doesn't specify the type of element identifier. jQuery won't find the element you're looking for as you currently have it.
You must specify:
For classes:
$( ".keyval" ).val();
For ID
$( "#keyval" ).val();
For input name
$( "input[name=keyval]" ).val();
That should attach the value to the POST request.
var url = "API/keychecker.php";
var spullen = $( "keyval" ).val();
I have used used the chosen function in my file but it is given an error when i tried to access this function as follows:
TypeError: $(...).ajaxChosen is not a function
here is the code that i am using :
$.post( woocommerce_admin_meta_boxes_variations.ajax_url, data, function ( response ) {
$( '#bto_config_group_inner .bto_groups' ).append( response );
$( "#bto_ids_" + bto_groups_metabox_count ).chosen();
$( "#bto_ids_" + bto_groups_metabox_count ).ajaxChosen( {
method: 'GET',
url: woocommerce_admin_meta_boxes.ajax_url,
dataType: 'json',
afterTypeDelay: 100,
data: {
action: 'woocommerce_json_search_products',
security: woocommerce_admin_meta_boxes.search_products_nonce
}
}, function (data) {
var terms = {};
$.each( data, function (i, val) {
terms[i] = val;
} );
return terms;
} );
$( 'input#_per_product_pricing_bto' ).change();
$( '#bto_product_data' ).unblock();
$( '#bto_product_data' ).trigger( 'woocommerce_bto_component_added' );
} );
return false;
} );
Have you included https://github.com/meltingice/ajax-chosen in your project? Looks like it is not visible in your code.
You will need to download the file - https://github.com/meltingice/ajax-chosen/blob/master/lib/ajax-chosen.min.js
Place it in your project so that it can be referenced with your other assets and include it using the
<script type="text/javascript" src="path/to/ajax-chosen.min.js"></script>
Ideally you would use NPM to bring down the asset, but just simply copying the file locally will suffice to get you up and running
I was unable to find a CDN link for this file, so its going to have to be done manually.
I want to get a variable from ajax to php. I'm using the Yii framework.
So my problem is, when I want to transfer a variable from ajax to a php script I get this error:
Fatal error: Class 'Yii' not found in
/var/www/vhosts/adappter.de/comamos/protected/views/store/search_area.php
on line 44 store.js:1308:13
This is how my Ajax Call looks like
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "../protected/views/store/search_area.php",
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
and this is my php script to line 44
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION['search_type']='';
if (isset($_GET['s'])){
$_SESSION['kr_search_address']=$_GET['s'];
$_SESSION['search_type']='kr_search_address';
}
unset($_SESSION['kr_item']);
unset($_SESSION['kr_merchant_id']);
$marker=Yii::app()->functions->getOptionAdmin('map_marker');
if (!empty($marker)){
echo CHtml::hiddenField('map_marker',$marker);
}
?>
The jQuery call is only when I click on a checkbox. So the value of the selected box gets pushed in an array. I want to return the array to the php script.
When I'm loading the site, I don't get such an error. So I don't know why this error occurs.
You need to use controller with action. Not only view file. You try to call view file from web. But it is wrong, because all code in protected directory. All requests must processing from index file. In index file connected framework. Here a small example. Controller:
class SiteController extends Controller
public function actionTest()
{
//... example
echo CHtml::button('test');
}
js:
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "/site/test", // url for your action
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
I was wondering if its possible to send a query to the database on the beforeunload event.
$(window).on('beforeunload',function() {
console.log('beforeunload called. run query');
});
If so, how would I do it? I need to run a query to insert dynamic values into the database.
You could try this, but beware that the onbeforeunload event is limited for certain browsers..
window.onbeforeunload = mySession;
function mySession(){
$.ajax({
url: "/../../myPHP.php",
async: false,
type: "GET"
});
return "WhatEverMessageYouFeelLike";
}
and your PHP executing query from AJAX handling..
$delete = "DELETE FROM MyTable WHERE id=" .$_SESSION['mySessionVariable'];
// your query..
Use a jQuery AJAX call. Assuming you're POSTing your data, try this:
$.post(
'your/url',
{
your : "Post Vars"
},
function(data) {
// not sure if you'll need to do anything here actually.
},
'json' // or 'html', or whatever you want your return format to be
);
I thinks the best way to use post by jQuery is $.post() method.but u can also use $.ajax
Sample way to use is
jQuery
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
jQuery Ajax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
What I'm tring to do is to load information from different pages, without having to refresh the whole main page...
Could you tell me how to adapt this code for loading files with different names (like about.html and project.html?
Note: this code is made just for loading 'page_.html' files.
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Here is the php file:
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
You can make multiple ajax requests this is the jquery load method:
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
do that 2x and your well off!
Keep in mind for this to work you'll need the jquery library.
I was doing a similar thing on my site here is my code:
window.setInterval("check()",60000);
//request information notice is inside a function called check() (it's not required to put inside function I only do this if I will be making the same request multiple time throughout the program)
function check() {
var request = $.ajax({
url: "file.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
//when request is done:
$(".wheretoputnewdata").html(msg);
});
request.fail(function(jqXHR, textStatus) {
//if request failed do this:
alert( "Request failed: " + textStatus );
});
}
Replace this line
if(file_exists('pages/page_'.$page.'.html'))
with this
if(file_exists('pages/'.$page.'.html'))