I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
$.ajax({
url: 'loaddata.php',
success: function(data){
var arr = data.split('|');
for(var i=0; i<arr.length; i++){
var miniArr = arr[i].split(',');
db.push(miniArr);
}
printTest(); //work here
}
});
printTest(); //not working and collapse here
});
function printTest(){
document.getElementById('test').innerHTML += db;
}
</script>
</head>
<body>
<div id="test" />
</body>
</html> `
My php file should be fine,
<?php
$database = file('database');
foreach($database as $item){
if ($item===end($database))
echo $item;
else
echo $item.'|';
}
?>
Thanks in advance.
Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.
If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.
You can't call your second printTest() here.
And for the record, try to use JSON to retrieve your datas, it's way much easier.
Related
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.
Ok, so ajax seems to be misbehaving. In other words i'm doing something wrong. I have a simple angular js app. The html looks like this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="../scripts/form_controllers.js"></script>
</head>
<body ng-app="EditDocApp">
<div ng-controller="EventDetector">
<input ng-model="event">
<button ng-click = "SelectEvent()">Click</button>
</div>
</body>
</html>
form_controllers.js contains a call to the Jquery post method in the EventHandle angular service. This is invoked in the calling of EventHandle.ajaxRequest() in the $scope.SelectEvent method in the EventDetector controller. This is form_controllers.js:
var editDocApp = angular.module("EditDocApp", []);
editDocApp.controller("EventDetector", eventDetector)
.factory("HandleEvents", handleEvents);
function handleEvents() {
var pass_back = {
ajaxLastReturn: "one",
ajaxRequest: function() {
$.post("http://localhost/TrailGuide/Website/Interface/webDataModelBuild/Documentation/scripts/test1.php", {}, function(response) { alert(response); })
.fail(function() { alert("nah"); });
}
}
return pass_back;
}
function eventDetector($scope, HandleEvents) {
$scope.event = "";
$scope.SelectEvent = function() {
$scope.event = "select";
HandleEvents.ajaxRequest();
};
}
The $.post method is failing every time i execute it by calling $scope.SelectEvent() from the button in the view (an alert box with "nah" pops up). I've tested the address passed to $.post by copying and pasting to the browser address box and it runs fine. I've tried the $.post method with and without data, no dice. I've tried jquery.ajax, still no dice. The php file, test1.php, is as follows:
<?php
echo "I am here!";
?>
Can somebody please point out what i am missing here? Is there some setting in php.ini that could be effecting this? Btw, this is my very first post on stack overflow so go easy on me! I'll get the hang of it. Thanks a bunch!
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
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/
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.