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.
Related
When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.
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.
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/
Upon suggestion of using Ajax for an html page, I decided to attempt to learn how it works. In my example, I'm just trying to get the response from a php file (which just echoes a simple string as a test) but it doesn't work, in that nothing actually happens.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Incident Center </title>
<!--<link rel="stylesheet" href="http://web.njit.edu/~swp5/assignment/style/style.css">-->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function onsubmit()
{
var sender;
if (window.XMLHttpRequest)
{
sender=new XMLHttpRequest();
}
else
{
sender=new ActiveXObject("Microsoft.XMLHTTP");
}
sender.onreadystatechange=function()
{
if (sender.readyState==4 && sender.status==200)
{
document.getElementById("myDiv").innerHTML=sender.responseText;
}
}
sender.open("GET","proz.php",true);
sender.send();
}
</script>
</head>
<body>
<div class="header">
Incident Center
</div>
<p>
<button onclick="onsubmit()">Test</button>
</p>
<div id="myDiv"></div>
</body>
</html>
As I already mentioned in my comment, you should check the response code of your request to see if something went wrong. Add the following line to the start of your onreadystatechanged function:
alert(sender.readyState + ', ' + sender.status + ', ' + sender.responseText);
Based on this output you can probably determine your error.
Using Opera 11.51 here, it doesn't actually like the fact that you use onsubmit() as a function name. Presumably because onsubmit() is actually already an eventhandler hook of a <button> element itself. I presume other browsers won't like this function name either.
So, first off, rename the function. Let's assume dosubmit() here.
Furthermore, you should wrap a button in a <form> element. And because a default button, acts as a submit button, the form is being submitted, causing the page to reload.
To prevent this, you should let the function return false; and call the function like so onclick="return dosubmit()", if you are going to call it inline like this, or make the button a button of type button, like so: <button type="button" onclick="dosubmit()">
Why don't you use jQuery ? http://www.jquery.com/
Send doesn't actually display anything. Send calls the page and populates two different variables. What send does is populates the "responseXML" and "responseText" properties of the sender. Try after your send:
alert(sender.responseText);
See http://en.wikipedia.org/wiki/XMLHttpRequest
It's much easier to use jQuery to do this as it has a built in AJAX function. Your code would look like this:
jQuery.ajax({
type: 'get',
url: 'proz.php',
error: function(r) {
alert("Something went wrong - "+r);
}
success: function(response) {
alert(response);
}
});
Hope that helps