How to pass php variables to jquery AJAX? - php

I have started learning jquery AJAX. I have run into a problem, and was wondering if you guys could help me. I am trying to pass a php variable back to jquery, but it displays as [object Object]. I will be posting my code below.
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function() {
$("p").text($.get("return.php"));
});
});
</script>
</head>
<body>
<p>This is a test!</p>
<button>Click Here</button>
</body>
</html>
return.php:
<?php
$message = "Another test!";
echo $message;
?>
So what is it that I need to do to pass php variable $message into the paragraph using jquery ajax?
I know I could simply do if I changed index.html to index.php, but then if $message later changes, I have to reload the page. I am trying to learn how to make dynamic content without having to reload the page.
Thanks ahead of time for any help you provide! :-)

You'll have to wait until the data is returned before you can use it:
$(document).ready(function(){
$("button").click(function() {
$.get("return.php", function(data) {
$("p").text(data);
});
});
});

Add a callback to get.
$.get("return.php", function(data) {
$("p").text(data);
});

You can use callback function in .get function.
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
});
});
});
Here you can pass the datatype as well in which form you want the response from server.
Suppose you want to return anyother datatype(i.e. json)from server, just use datatype with it like this :
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
},"json");
});
});
For more detail,refer : http://api.jquery.com/jQuery.get/

Related

jquery addclass keeps reseting inside setinterval

I have an HTML DIV which is updated by ajax function using setinterval. What I'm trying to do is addclass to the result of ajax. But when setinterval the addedclass is reset and displays the initial class. how to solve this issue.
<html>
<body>
<div id="something"></div>
<script>
$(document).ready(function(){
var id;
setInterval(function(){
somepage();
addactiveclass();
}, 5000);
function somepage(){
$.ajax({
url:"fetchcontents.php",
method:"POST",
success:function(data){
$('#something').html(data);
}
})
}
function addactiveclass(){
$('#list-'+id).addClass("active");
}
// UPDATED
$(document).on('click', '.mycontents', function(){
id = $(this).data('id');
$('#list-'+id).addClass("active");
}
});
</script>
</body>
</html>
UPDATE: fetchcontents.php
<?php
$output .= '<div class="list-item mycontents" data-id="'.$row['id'].'" data-name="'.$row['username'].'" id="list-'.$row['id'].'">';
//.... some php function to generate some contents inside the above div.....
// Contents do not interfere with this question.
$output .= '</div>';
echo $output;
?>
What happens is the active clas is not added to the div id="list-'.$row['id'].'". As you know setinterval keeps on executing ajax function after 5sec and the active class is reset and not displayed.
Could anyone please guide me to accomplish this issue.
Thanks in advance.
I just ran your code in jsfiddle, but replaced the ajax with a string defining a new div as contents of #something, and it works.
However it did require me to put the js inside a $(document).ready block
$(document).ready(function() {
//your js in here
})
Try that. What this does is not define the js until all the HTML is rendered. My guess is that you were referencing #something before it existed.
EDIT:=============================================
You have changed your code considerably since my answer was written, but to backup my claim to have a solution to what I believe was your question, I have re-done my jsfiddle test: https://jsfiddle.net/uf5h0sgw/
<html>
<body>
<div id="something">AAAA</div>
<script>
$(document).ready(function(){
var id;
var cnum = 1;
setInterval(function(){
somepage();
addactiveclass();
}, 1000);
function somepage(){
$('#something').html('<div class="abc">BBBB</div>');
/*$.ajax({
url:"fetchcontents.php",
method:"POST",
success:function(data){
$('#something').html(data);
}
})*/
}
function addactiveclass(){
/*$('#list-'+id).addClass("active"); */
$('#something div').addClass("active" + cnum++)
}
});
</script>
</body>
</html>
I cannot reproduce your ajax response, so I have just added some code to insert a DIV into #something every time the interval expires (reduced to 1000ms for the test).
Then the function addactiveclass() changes the class of the Div that has been added. I change the class name on a counter each loop so you can see that the class is updated every time around.
You will obviously have to adapt my code to handle what ever content your AKAX adds, but the approach should achieve what I think you want.

Resetting a PHP $_SESSION array with jquery function

I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions

Refresh a div with php data every 10 seconds using jQuery

Am trying to refresh data stored in a div every 10 seconds using jQuery.
My HTML code is:
<!DOCTYPE html>
<head>
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#latestData").load("getLatestData.php #latestData");
}, 10000);
});
</script>
</head>
<body>
<div id = "latestData">
</div>
</body>
</html>
And the PHP code I am using (temporarily as I know this won't change due to the same "data"):
<?php
echo "test";
?>
However, it isn't even showing "test" on the html page.. could anyone suggest where I have gone wrong?
Many thanks
jQuery load method works in a different way. Try reading its documentation.
You don't have to specify destination element ID twice, remove the second one, like this:
$("#latestData").load("getLatestData.php");
Here's a way that will solve what you want to achieve, using the $.get method in jQuery:
$(document).ready(function () {
setInterval(function() {
$.get("getLatestData.php", function (result) {
$('#latestData').html(result);
});
}, 10000);
});
If you want to refresh message count just use this code:
$(document).ready(function () {
setInterval(function () {
$("#ID").load();
}, 1000);
});

jquery form submit does not work after using a load function

I have an index.html page which, using jquery, calls somepage.php residing within the same site to load the contents of this index.html page.
So this is the intended page load sequence:
index.html -> somepage.php -> submit.php (if submit button is clicked)
The index.html has only the "main-div" and no contents as such. When the somepage.php is called, the "main-div" contents are loaded by running the php script. The main-div contains a sub div with a small form with a submit button. Using jQuery,I see if the submit button is clicked, and when clicked, the submit.php script is called.
This is the barebone code:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$('document').ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get(
'http://www.someurl.com/submit.php',
{ item: jsURL },
function(data){
if(data=="success")
{
$('#submit-status').html(data);
}
else
{
$('#submit-status').html(data);
}
}
);
}
});
</script>
</head>
<body>
<div id="main-div"> </div>
</body>
</html>
Now the issue:
The index.html page loads with everything displayed correctly (the small form with the submit button, all other main-div contents, everything is displayed). However, the submit button does not call the submit.php script, meaning I believe that the jQuery code corresponding to the click event is not being registered.
I am fairly new to jQuery. Does this have something to do with how I have "ordered" the code in the jQuery .ready()? Something to do with the DOM not being ready before the function is called, or maybe an issue with the .load() in jQuery?
Try this :
<script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php",function(){
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').attr('value');
submit(jsURL);
});
});
});
function submit(jsURL){
$.ajax({
url:'http://www.someurl.com/submit.php',
type :'GET',
success: function(data){
$('#submit-status').html(data);
}
});
}
</script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get('http://www.someurl.com/submit.php', {item: jsURL}, function(data){
$('#submit-status').html(data);
});
}
});
Do not quote the document
load() is a shortcut for $.ajax, and it's async, so #item-submit does'nt exist when you attach the event handler, you need a delegated event handler for that.
If it's really a submit button inside a form, make you sure you prevent the default action so the form does'nt get submitted.
The load function works asynchronously. With your code #item-submit is not yet there when you try to bind the event handler.
Bind the event handler on succes:
$("#main-div").load("http://www.someurl.com/somepage.php", function () {
$('#item-submit').click(function () {
jsURL = $('#input').val();
submit(jsURL);
});
});
load loads the data asynchronously, which means time by the time you are assigning a click handler on submit button the button itself might not be yet on the page. To overcome this you have two options:
Specify a success handler for load.
$("#main-div").load("http://www.someurl.com/somepage.php", function(){
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
});
Use on to indicate that the click handler should be assigned to elements that are or will be on the page.
$('#item-submit').on('click', function(){
jsURL = $('#input').val();
submit(jsURL);
});
As all pointed out, the load function works asynchronously so, your click handler is not working for the 'future' div.
You can bind handler to a future element like this:
$(document).on('click', '#item-submit', function(event){
jsURL = $('#input').val();
submit(jsURL);
});
This way you can bind your handler in the jQuery document ready function.

pass query string variables without refresh page

My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.

Categories