简体   繁体   中英

Submitting ajax on page load

So I am submitting my AJAX just before the page is loaded and calling it on the same page like this after ajax.

<input type="text" class="hidden" id="storeID" value="<?php echo $_GET['store']; ?>">
$(document).ready(function()
{
var store = $("#storeID").val();
$.ajax(
{
  url: '../user-style.php',
  method: 'POST',
  data: {"store":store}
});
});
<link rel="stylesheet" href="../user-style.php" media="screen" />

user-style.php

if(isset($_POST['store']))
{
$stmtgetstyle = $mysqli->prepare("SELECT * FROM store_style_configuration WHERE store_id=?");
$stmtgetstyle->bind_param("i", $_GET['store']);
$stmtgetstyle->execute();
$getstyle = $stmtgetstyle->get_result();
$style = $getstyle->fetch_assoc();
$stmtgetstyle->close();
}

But user-style.php isn't getting any data neither any thing is from database is coming.

You'll want to pull the content of the CSS and return it. Now you can dynamically put it in a jQuery Object :

$.ajax({
    url: '../user-style.php',
    method: 'POST',
    data: {"store":store},
    success: function(data) {
        var $cssStyles = $('<style/>');
        $cssStyles.attr('type', 'text/css');
        $cssStyles.html(data);
        $cssStyles.appendTo($('head'));
    }
});

Another method would be to pass it to the current script via the URL parameters with $_GET :

<link rel="stylesheet" href="../user-style.php?store=store" media="screen" />

Or with jQuery and $_GET :

$(document).ready(function() {
    var store = $("#storeID").val();
    var $cssStyles = $('<style/>');
    $cssStyles.attr({ 'type': 'text/css', 'href': '../user-style.php?store=' + store });
    $cssStyles.appendTo($('head'));
});

You are posting your data in the ajax call, but are binding to the variable $_GET['store'] . Just change that to $_POST['store'] and it should work. This should have also sent out a notice error stating there was an undefined index 'store' in $_GET on line ... . This is why turning on error_reporting(E_ALL) is good when in development.

Edit: actually, on second thought, it might not have thrown an error because when using a variable by reference creates a variable if it doesn't exist and doesn't throw an error. I assume this is the same for undefined array indexes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM