JavaScript to Pass variable and retrieve output from PHP page - php

Trying to pass a variable to a PHP file then get the output of that file.
Page1.html:
<h2 id="test"></h2>
<script>
var data2;
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
data2 = data;});
document.getElementById("test").innerHTML = data2;
</script>
textandemail.php:
$variable = $_POST["txt"];
$variable2 = $_POST["email"];
echo $variable;
echo $variable2;
Hopefully this describes the desired idea. I will be doing much more in the PHP file but in the end echoing out a response that I want the JavaScript to read and implement into the html page.

The $.post() function is asynchronous. It finishes some time LATER. You need to put the assignment of the results from that function into the success handler, not after the function itself because as you have it now, the line document.getElementById("test").innerHTML = data2; is occurring BEFORE the ajax function has finished and thus it won't work.
This is how you can do it:
<h2 id="test"></h2>
<script>
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
// any code that uses the ajax results in data must be here
// in this function or called from within this function
document.getElementById("test").innerHTML = data;
}
);
</script>
Or, since you have jQuery, you can do it like this:
<h2 id="test"></h2>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$.post('textandemail.php',{ txt: "John", email: "test#gmail.com" },
function(data) {
// any code that uses the ajax results in data must be here
// in this function or called from within this function
$("#test").html(data);
}
);
</script>

Your post call is asynchronous, you have access to the data2 variable only once the process is done, so you should do your ....innerHTML ... in the callback function, when the data is available, not before.
There are plenty of good examples of this on any js sites. On the jQuery doc you have a good example.
Since you are useing jQuery, you could replace your innerHTML call too.

you should use ajax function to make communication between php and javascript
function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){
var xmlhttp
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}
catch(e){
try{xmlhttp=new XMLHttpRequest()}
catch(e){
alert("Your Browser Does Not Support AJAX")}}}
err=""
if (GP==undefined) err="GP "
if (URL==undefined) err +="URL "
if (PARAMETERS==undefined) err+="PARAMETERS"
if (err!=""){alert("Missing Identifier(s)\n\n"+err);return false;}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4){
if (RESPONSEFUNCTION=="") return false;
eval(RESPONSEFUNCTION(xmlhttp.responseText))
}
}
if (GP=="GET"){
URL+="?"+PARAMETERS
xmlhttp.open("GET",URL,true)
xmlhttp.send(null)
}
if (GP="POST"){
PARAMETERS=encodeURI(PARAMETERS)
xmlhttp.open("POST",URL,true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.setRequestHeader("Content-length",PARAMETERS.length)
xmlhttp.setRequestHeader("Connection", "close")
xmlhttp.send(PARAMETERS)
the call functions put it inside the javascript page
Ajax_Send("POST","users.php",data,e)
where data is the data you send to the php page and e is the function you pass the output of php page to it

Related

Unable to run jsvascript until page refresh

I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.
<script>
$( document ).ready(function(){
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
function requestContent() {
var date = new Date();
$.ajax({
type:'POST',
url:'php/app/adminTimeline.php',
data:{
date: date.yyyymmdd()
},
success: function(data) {
if (data == '') {
alert("No data found!");
} else {
// $("#loading_spinner").css({"display":"none"});
$('#timeline-content').prepend(data);
}
},
error: function(data) {
// $("#loading_spinner").css({"display":"none"});
alert("Something went Wrong!");
}
});
}
window.onload = requestContent();
});
</script>
The document.onready method and window.onload the method seems not to be working too.
Ps: I have the Jquery library linked in the header too.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
https://learn.jquery.com/using-jquery-core/document-ready/
Also you're calling requestContent()
window.onload must be function, not returning value.
$(document).ready(function(){
// here you ajax
}
https://jsfiddle.net/cqfq5on5/1/
The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.
However where you create the date object, uses this, which executes after the document is fully loaded
$(document).ready(function(){
//Code
});
This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (#sagid) pointed out, window.onload cannot be a returning value but must be a function.
i.e.
window.onload=function(){
//Code
};
This means, your solution is to change window.onload=requestContent(); to
$(document).ready(function(){
requestContent();
});
Good luck!

Do php query with ajax

I'd like to do a sql query with ajax so I don't need to reload the page / load a new page.
So basicly I need to call a php page with ajax. And it would be great if there could be a way to reload a count of amount of rows in a table too.
Edit: to make it more clear, it should be able to do something along the lines of when you click the Like button on Facebook.
Thanks
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("your_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">here are your contents</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
You don't want to query using ajax, you want to get new data using ajax, which is a fundamental difference.
You should just, using ajax, request a php page with perhaps some parameters, which in turn executes the query and returns the data in a format you can handle (most likely: json).
If you allow queries to be executed using ajax, how are you going to prevent a malicious user from sending drop table users, instead of select * from news where id = 123?
You won't do a sql query with ajax, what you need to do is call an external php page (one where your query is) in the background using ajax. Here is a link that explains how to do it with jquery: http://api.jquery.com/jQuery.ajax/
"Facebook Like" button in Agile Toolkit (PHP UI Library):
$likes = get_like_count();
$view = $this->add('View');
$button = $view->add('Button')->setLabel('Like');
$view->add('Text')->set($likes);
if($button->isClicked()){
increate_like_count();
$view->js()->reload()->execute();
}
p.s. no additional JS or HTML code needed.
function onClick(){
$.post(
"path/to/file", //Ajax file ajax_file.php
{ value : value ,insiId : insiId }, // parameters if you want send
//function that is called when server returns a value.
function(data){
if(data){
$("#row_"+data.id).show(); //display div rows
}
},"json"
);
}
<div id="myDiv">here are your contents</div>
<button type="button" onclick="onClick()">Change Content</button>
Here the ajax code that you can call to the server side php file and get the out put and do what you want
You are wrong, who says that he is submitting the whole query who is telling that he is not filtering? U can do all this easy with the jquery load function, you load a php file like that $('#BOX').load('urfile.php?param=...');.
Have fun,
i hope that was a little helpful for you, sry bcs of my bad english.
Possible solution: Ajax calls PHP scripts which make the query and return the new number
$.ajax({
async:true,
type:GET,
url:'<PHP_FILE>',
cache:false,
data:'<GET_PARAMETERS_SENT_TO_PHP_FILE>',
dataType:'json',
success: function(data){
$('<#HTML_TARGET>').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('<#HTML_TARGET>').html('<div class="ajax_error">'+errorThrown+'</div>');
}
});
Where
<PHP_FILE> is your php script which output must be encoded according to dataType. The available types (and the result passed as the first argument to your success callback) are: "xml", "html", "script", "json", "jsonp", "text".
<GET_PARAMETER_SENT_TO_PHP> is a comma separate list of value sent via GET (es. 'mode=ajax&mykey=myval')
<#HTML_TARGET> is the jquery selector
See jquery.ajax for more details.
For example:
<p>Votes:<span id="count_votes"></span></p>
<script type="text/javascript">
$.ajax({
async:true,
type:GET,
url:'votes.php',
cache:false,
dataType:'text',
data:'id=4'
success: function(data){
$('#count_votes').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('#count_votes').html(errorThrown);
}
});
</script>
If your looking for something like the facebook like btn. Then your PHP code should look something like this -
<?php
$topic_no = $_POST['topic'];
$topic_likes = update_Like_count($topic_no);
echo $topic_likes;
function update_Like_count($topic)
{
//update database by incrementing the likes by one and get new value
return $count;
}
?>
and the javascript/jquery ajax should be something like so -
<script>
$('#like-btn').click( function () {
$.post(
"like.php",
{ topic : value },
function(data)
{
if(data)
{
$("#like-btn span").append(data); //or append it to wherever you'd like to show it
}
else
{
echo "error";
}
},
"json"
);
});
</script>
Here is an example which uses a favorite jQuery plugin of mine, jQuery.tmpl(), and also the jQuery .text() function.
HTML and Javascript Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
<script id="UserTemplate" type="text/x-jquery-tmpl">
<li><b>Username: ${name}</b> Group ID: (${group_id})</li>
</script>
<button id="facebookBtn">Facebook Button</button>
<div id="UserCount"></div>
<ul id="userList"></ul>
<script>
function getData(group_id) {
$.ajax({
dataType: "json",
url: "test.php?group_id=" + group_id,
success: function( data ) {
var users = data.users;
/* Remove current set of movie template items */
$( "#userList" ).empty();
/* Render the template with the movies data and insert
the rendered HTML under the "movieList" element */
$( "#UserTemplate" ).tmpl( users )
.appendTo( "#userList" );
$( "#UserCount" ).text('Number of users: '+ data.count);
}
});
}
$( "#facebookBtn" ).click( function() {
getData("1");
});
</script>
</body>
</html>
PHP Code
<?php
//Perform a query using the data passed via ajax
$group_id = $_GET['group_id'];
$user_array = array(
array('name'=>'John','group_id'=>'1',),
array('name'=>'Bob','group_id'=>'1',),
array('name'=>'Dan','group_id'=>'1',),
);
$user_count = count($user_array);
echo json_encode(array('count'=>$user_count,'users'=>$user_array));
HTML:
//result div will display result
<div id="result"></div>
<input type="button" onclick="getcount();" value="Get Count"/>
JS:
//will make an ajax call to ustom_ajax.php
function getcount()
{
$.ajax({
type:"get",
url : "custom_ajax.php",
beforeSend: function() {
// add the spinner
$('<div></div>')
.attr('class', 'spinner')
.hide()
.appendTo("#result")
.fadeTo('slow', 0.6);
},
success : function (data) {
$("#result").html(data);
},
complete: function() {
// remove the spinner
$('.spinner').fadeOut('slow', function() {
$(this).remove();
});
}
});
}
custom_ajax.php:
//will perform server side function
//make a connection and then query
$query_txt = "SELECT count(*) FROM table ";
$result= mysql_query($query_txt) or die(mysql_error());
$total=mysql_num_rows($result) ;
$html= "Total result is $total";
echo $html; exit();

Javascript + Load AJAX function on page load + Pass Javascript vars to PHP

I have again a little problem with a javascript (i am a real noob regardin that). This time I would like to load an AJAX function on page load in order to save some javascript variables to php sessions. I figured out thats the best way to pass javascript vars to php. If there is a better way (besides cookies), dont hesitate to let me know :)
For now I would like to:
-pass javascript variables to an external php page on page load
-save variables in php
-use the php variables without pagereload
Here is my script so far:
$(document).ready(function () {
function save_visitor_details() {
$(function() {
var visitor_country = geoip_country_name();
var visitor_region = geoip_region_name();
var visitor_lat = geoip_latitude();
var visitor_lon = geoip_longitude();
var visitor_city = geoip_city();
var visitor_zip = geoip_postal_code();
var dataString = 'visitor_country='+ visitor_country +'&visitor_region='+ visitor_region +'&visitor_lat='+ visitor_lat +'&visitor_lon='+ visitor_lon +'&visitor_city='+ visitor_city +'&visitor_zip='+ visitor_zip;
$.ajax({
type: "POST",
url: "inc/visitor_details.php",
data: dataString,
success: function(res) {
alert ("saved");
//$('#result').html(res);<-- should contain variables from inc/visitor_details.php
});
}
});
return false;
}
});
Thanks in advance!
Edit: I changed it a little and got it to work by adding the javascript variables into a hidden form, submit the form with the ajax script above and save variables into php session array at the backend php file.Thanks any1 for your time!!!
I don't really understand what is the question here. But here are a few advices.
rather than serializing the data yourself, you should rather let jQuery do that for you:
$.post('inc/visitor_details.php', {country: geoip_country_name() /* stuff */}, function(data) {
alert('ok!'); alert(data);
});
be aware that, by passing data to your server using Javascript, users can send whatever data they want, including fake data. So handle it with care.
Then entire process may looks like this:
/* javascript */
$(document).ready(function() {
function save_visitor_details() {
$.post('inc/visitor_details.php', {
country: geoip_country_name(),
region: geoip_region_name(),
lat: geoip_latitude(),
lon: geoip_longitude(),
city: geoip_city(),
zip: geoip_postal_code()
}, function(data) {
/* do whatever you want here */
alert(data);
}, 'json');
}
save_visitor_details();
});
/* PHP */
<?php
$keys = array('country', 'region', 'lat', 'lon', 'city', 'zip');
$output = array();
foreach($keys as $key) {
do_some_stuff($_POST[$key]);
$output[$key] = $_POST[$key];
}
header('Content-type: text/plain; charset=utf-8');
echo json_encode($output);
?>
JavaScript:
var http = createRequestObject() ;
function createRequestObject(){
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
obj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(str){
http.open('get', str);
http.onreadystatechange = handleResponse;
http.send(null);
}
sendReq("someurl?var=yourvar");
Php:
$var = $_GET['var']; // use some security here.

How to call multiple AJAX functions (to PHP) without repeating code

I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.

jquery - send string to php to safe it in mysql

i got this script, which i found in the web:
<script type="text/javascript">
$(document).ready(
function () {
$('a.closeEl').bind('click', toggleContent);
$('div.groupWrapper').Sortable(
{
accept: 'groupItem',
helperclass: 'sortHelper',
activeclass : 'sortableactive',
hoverclass : 'sortablehover',
handle: 'div.itemHeader',
tolerance: 'pointer',
onChange : function(ser)
{
},
onStart : function()
{
$.iAutoscroller.start(this, document.getElementsByTagName('body'));
},
onStop : function()
{
$.iAutoscroller.stop();
}
}
);
}
);
var toggleContent = function(e)
{
var targetContent = $('div.itemContent', this.parentNode.parentNode);
if (targetContent.css('display') == 'none') {
targetContent.slideDown(300);
$(this).html('[-]');
} else {
targetContent.slideUp(300);
$(this).html('[+]');
}
return false;
};
function serialize(s)
{
serial = $.SortSerialize(s);
alert(serial.hash);
};
</script>
<div class="serializer">
<a href="#" onClick="serialize(); return false;" >serialize all lists</a>
</div>
<script language="JavaScript" type="text/javascript">var client_id = 1;</script>
at the bottom of the script is the "function serialize", which is called by clicking on the link below. Can someone tell me, how can i send the variable "serial.hash" to a php-file to save it in mysql-database?
many thanks, maschek
Yes as Yacoby says $.post() or jQuery.post
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Use Ajax to send request to a PHP script which submits the data to a database. The JQuery documents contain a lot of examples. If you use a HTTP GET request, be warned there is a limit on the amount of data you can pass. This is browser dependant. I would recommend using jQuery.post as the method of sending data.
All the PHP script has to do is read the variables either from $_GET or $_POST (whichever method you use), sanitize them and submit them to the database.
Actually, it seems very simple now:
$.post("test.php",{'func':'serial'},function(data){
alert(data);
});

Categories