I created an Ajax navigation system but I've an issue when I want to send a variable.
I've an index.php like this
<script src="navigation.js" type="text/javascript"></script>
<div id="pageContent"></div>
page1
profile
This is navigation.js
$(document).ready(function(){
checkURL();
$('a').click(function (e){
checkURL(this.hash);
});
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
}
}
});
}
And this is the load_page.php page:
<?php
if(!$_POST['page']) die("0");
$page = $_POST['page'];
include('pages/'.$page.'.php');
?>
This is the issue: when I load profile.php page I want to see values by GET... example:
<?php
$nome_utente = $_GET['user'];
if(!$_GET['user']) {
print 'Attention! You have to insert a username';
}
else
{
print $nome_utente;
}
?>
To do this I tried to change the link in index.php
profile
But this doesn't work because load_page.php doesn't find the "profile?user=test.php" page.
What do I have to do to send a GET variable at profile.php, from a link in index.php?
I've to edit JS or PHP code?
Mixing get/post variables is considered poor practice, but is easily done:
function loadPage(url) {
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php?user=whatever_you_want_here",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^---your 'get' query
The other optiont would be to add the 'user' parameter to your ajax data line:
data: { page: url, user: whatever_you_want_here }
The first one would make 'user' available in $_GET, the second one would make it available in $_POST.
Related
I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard
I am using AJAX to load content from mysql database when I CLICK on LINKS.
once I load the content successfully, I refresh the container every 5 seconds so the new content will be displayed.
the content gets loaded fine and the refresh part works fine too.
but the issue that I have is that when the refresh happens, the loaded content gets lost.
by "it gets lost" i mean that it will display the LAST result from the mysql database.
so, to help you understand the situation I will explain it further:
Lets say I have 3 results stored in mysql database.
I create <a></a> from each result in mysql using PHP. i am doing this without any issue.
I click on the link 2. (works fine)
the content of the link 2 will load on the page using AJAX. (works fine)
The container of content will refresh every 5 seconds. (works fine)
(THIS IS WHERE THE PROBLEM STARTS) once the refresh happens, the content of link 3 will be displayed even though I haven't clicked on the link 3!
so basically, for some strange reason, the content of the last Link or last mysql result will be displayed at all time which is un-wanted. I need to load the content of the CLICKED link and make it stay until another Link is clicked.
I hope I haven't confused you. :)
here is my html code:
<div id="chattercontent" style="width:90%; height:150px; resize:none; border:solid 1px #ccc; background:#F2EDF0; overflow:scroll; text-align:left;"></div>
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
}
load();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".list-group-item").click(function(e) {
e.preventDefault();
$("#chattercontent").load(this.href);
return false;
});
});
</script>
and PHP code for the links:
while (mysqli_stmt_fetch($stmt)) {
$product_list .= "<a id='listc' class='list-group-item' href='file.php?u_id=".$u_id."' >".$u_id." ".$date_added." <img src='light-red-flash.gif' width='20' /></a>";
}
}
any help would be appreciated.
Thanks
edit:
this is the code for file.php
<?php
session_start();
if (isset($_GET['u_id'])) {
$u_id = $_GET['u_id'];
$sql = "SELECT * FROM chat WHERE u_id='$u_id' ";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$user_message = $row["user_message"];
}
} else {
echo "Sorry, there was an error.";
exit();
}
echo $user_message;
}
?>
as I mentioned before, the file.php returns the result properly according to the link that have been clicked on but then it will JUMP on the last result after each refresh!
You need to keep track of the current url the user has selected:
$(document).ready(function () {
//set url 1st time
var currentUrl = "file.php?u_id=<?php echo $u_id; ?>";
//variable to reference the timeout
var timer;
function load(url) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: url,
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
timer = setTimeout(function(){
load(currentUrl);
}, 5000);
}
});
}
load(currentUrl);
$(".list-group-item").click(function(e) {
e.preventDefault();
//update url on click
currentUrl = this.href;
//cancel existing timer
clearTimeout(timer);
load(currentUrl);
});
});
You aren't loading your dynamic content with the javascript function. Check out the following, hope it will fix your problem.
function load(href) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(function() {
load(href);
}, 5000)
}
});
}
var _currentUrl;
function load(href) {
if (!href) {
href = _currentUrl;
}
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
_currentUrl = href;
}
I am a bit confused. I would be glad if you would explain it a bit more with some examples.
Anyway from what I could get from your text is that, the previous result is being overwritten.
In order to stop that, as we do while making a chatbox, you need to add the response "after" the previous result as in -
<script type="text/javascript">
/* A variable to hold the last response */
var lastResponse = "";
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
/* Check if it is the same response or not */
if (lastResponse != response)
{
/* Save the last response */
lastResponse = response;
/* Add content after the previous */
$("#chattercontent").html($("#chattercontent").html()+response);
}
setTimeout(load, 5000)
}
});
}
load();
});
</script>
I am submitting a form using ajax. Then it is processed in PHP, and in the response i get the whole PHP/HTML code back. What is the right method to send back a "response" as variables from the PHP?
My JS
$.ajax({
url: 'index.php',
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});
and my PHP simply accepts the posted Input value and manipulates it:
if (isset($_POST["myInput"])) {
// doing something - and I want to send something back
}
Just echo and exit:
if (isset($_POST["myInput"]))
{
// doing something - and I want to send something back
exit('Success');
}
Then in your JS:
success: function(response) {
if (response == 'Success') {
// do something?
}
}
For example:
test.php single page html + php post handler
<?php
// Post Handler
if (count($_POST))
{
// do something with posted data
echo "You Posted: \r\n";
print_r($_POST);
exit();
}
// dummy data outside of the post handler, which will never be sent in response
echo "Test Page";
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.post('test.php', { "hello": "world" }, function(result) {
alert(result);
});
});
</script>
Outputs:
$.ajax({
url: 'index.php', // change your url or give conditional statement to print needed code
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});
I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.
This is a page using a single jQuery.ajax posting to the same page and is working fine.
<?php
if (!isset($_POST['varA'])) {
?>
<html>
<head>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123"},
success: function(data)
{
$("#test").html(data);
}
});
}
</script>
</head>
<body>
<span id="test"></span>
</body>
</html>
<?php
}
else
{
print_r($_POST['varA']);
}
?>
Situation: I have another variable that I wish to set using another separate jQuery.ajax. However, my page content duplicated itself when I put them altogether like this.
Bad Example (depicting what I'm trying to do)
<?php
if (!isset($_POST['varA'])) {
?>
<html>
<head>
<script type="text/javascript">
$(document).ready(bingo);
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123"},
success: function(data)
{
$("#test").html(data);
}
});
}
function buttony() //added 2nd independent jQuery.ajax function
{
jQuery.ajax({
type: "POST",
data: {varB: "456"},
success: function(data)
{
$("#test2").html(data);
}
});
}
</script>
</head>
<body>
<span id="test"></span>
<span id="test2"</span> //added 2nd span
<input type="button" value="Clicky" onclick="buttony()"/> //added
</body>
</html>
<?php
}
else
{
print_r($_POST['varA']);
}
if(isset($_POST['varB'])) //added isset() checking
{
print_r($_POST['varB']);
echo 'varB Okay';
}
else
{
echo 'varB Not';
}
?>
Additional information: Posting of variables for both jQuery.ajax of "Bad Example" are working fine.
Note: Pictures below are not from the codes above, just an example of what I meant by "content duplicated itself".
Before
After
Question: May I know where should I put my 2nd jQuery.ajax function and isset() checking of the POST variable, in such a way that both jQuery.ajax functions will work correctly and won't conflict with each other?
You shouldn't have to pass the bingo function the document ready function. Try
$(document).ready(function() {
function bingo()
{
jQuery.ajax({
type: "POST",
data: {varA: "123"},
success: function(data)
{
$("#test").html(data);
}
});
}
bingo();
function buttony() //added 2nd independent jQuery.ajax function
{
jQuery.ajax({
type: "POST",
data: {varB: "456"},
success: function(data)
{
$("#test2").html(data);
}
});
}
buttony();
}); //end document ready
I used window.location to replace the use of 2nd jQuery.ajax to avoid complication.
Sample example
Inside JavaScript function
window.location = "samePage.php?varB=abc";
Checking of POST variable varB
if(isset($_REQUEST['varB'])
{
$getValue = $_REQUEST['varB'];
}
I'm leaving the question open for the community to tackle on how to do proper nesting of using 2 or more jQuery.ajax in the same page.