ajax passing parameter to javascript/php - php

I experience a weird problem in this code, actually it works for 1 second and then not anymore.. maybe some variable/function is not correctly declared and is causing this strange thing..
I have in my index.php this piece of code. If I put hardcode inside the function myfunc par1 and par2 set to zero then everything behaves correctly, means loadfunc.php is correcly called with those parameters, while if try the code I posted I see that loadfunc.php is called once correctly and so I can see the correct output for only 1 second..
<script type="text/javascript">
function myfunc(par1, par2)
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis2').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 1000);
}
};
$http.open('GET', 'loadfunc.php' + '?par1=' + par1 + '&par2=' + par2);
$http.send(null);
}
}
</script>
<script type="text/javascript">
setTimeout(function() {myfunc("0","0");}, 1000);
</script>

setTimeout(function(){$self();}, 1000);
Resets the timeout, but doesn't set up the parameters, which is why they show up as undefined.

Related

PHP & MySql and Ajax auto-suggest issue

I'm using bootstrap for website. I include Ajax, css and PHP to show Auto Suggestions for mp3 search. Everything is working fine but an issue happened. I tried with different way but the issue is still there.
The Issue
When type keyword it show suggestion. (OK)
When you click on keyword from suggestion it works. (OK)
But when we erase keyword and click on anywhere at page then page content reload and shown as u can see in picture.
Url of website is http://www.4songs.pk
Code in header
<script src="http://www.4songs.pk/js/jquery-1.10.2.js"></script>
<script>
$(function(){
$(document).on( 'scroll', function(){
if ($(window).scrollTop() > 100) {
$('.scroll-top-wrapper').addClass('show');
} else {
$('.scroll-top-wrapper').removeClass('show');
}
});
$('.scroll-top-wrapper').on('click', scrollToTop);
});
function scrollToTop() {
verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $('body');
offset = element.offset();
offsetTop = offset.top;
$('html, body').animate({scrollTop: offsetTop}, 500, 'linear');
}
</script>
<script type="text/javascript">
var myAjax = ajax();
function ajax() {
var ajax = null;
if (window.XMLHttpRequest) {
try {
ajax = new XMLHttpRequest();
}
catch(e) {}
}
else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e){
try{
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return ajax;
}
function request(str) {
//Don't forget to modify the path according to your theme
myAjax.open("POST", "/suggestions", true);
myAjax.onreadystatechange = result;
myAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myAjax.setRequestHeader("Content-length", str .length);
myAjax.setRequestHeader("Connection", "close");
myAjax.send("search="+str);
}
function result() {
if (myAjax.readyState == 4) {
var liste = myAjax.responseText;
var cible = document.getElementById('tag_update').innerHTML = liste;
document.getElementById('tag_update').style.display = "block";
}
}
function selected(choice){
var cible = document.getElementById('s');
cible.value = choice;
document.getElementById('tag_update').style.display = "none";
}
</script>
The 2nd issue
When auto suggestions load it also include some empty tags as you can see in picture
I take this picture as doing Inspect Elements
PHP Code are clean
<?php
include('config.php');
if(isset($_POST['search']))
{
$q = $_POST['search'];
$sql_res=mysql_query("SELECT * FROM dump_songs WHERE (song_name LIKE '%$q%') OR (CONCAT(song_name) LIKE '%$q%') LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{?>
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>
<?php
}
}?>
In the function request(str) put an if statement to check if str length is greater than zero.
function request(str) {
if(str.length > 0)
{
// Your existing code
}
else
{
document.getElementById('tag_update').innerHTML = '';
}
}
In short words the problem you are describing is happping because the str parameter in the data that you send to /suggestions is empty. The server returns 304 error which causes a redirect to the root page. Your js script places the returned html into the suggestion container. And thats why you are seeing this strange view.
-UPDATE 1-
Added the following code after user request in comments
else
{
document.getElementById('tag_update').innerHTML = '';
}
-UPDATE 2- (16/07/2014)
In order to handle the second issue (after the user updated his question)
Υou forgot to close the a tag in this line of code
<li><a href="javascript:void(0);" onclick="selected(this.innerHTML);"><?=$row['song_name'];?></li>

php variable to javascript via ajax

Ok im tring to get PHP variable to javascript variable via ajax.
i have some piece of php code to make this variable it look like this: (i wont put entire code because its working so only relevant code for this topic. i have new_m variable which is ARRAY and i want to pass it)
shuffle($new_m);
echo json_encode($new_m);
then i have js file which should catch that echo and it look like this:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
var myvar = new Array();
var myvar=JSON.parse(xmlHttp.responseText);
return myvar;
}
}
xmlHttp.open("GET", "showimage.php", true);
xmlHttp.send(null);
}
When this code is not on separate page like here and when is myvar is used inside function it works (because i have used this code on another page successfully). So i think my problem is not returning correct variable or not returning it on correct way.
and final piece of code is part where this myvar should be used it looks like:
<script type="text/javascript" src="js/shuffle.js"></script>
<title>undf</title>
</head>
<body onload="MakeRequest()">
<script type="text/javascript">
alert(myvar);
var pos = 0;
var imgs = myvar;
</script>
and nothing happens. im still new at this ajax and javascript. thanks for you help in advance.
Your problem is that when alert( myvar); is executed, the request to the server hasn't happened yet, and the variable is undefined (not to mention that I believe the variable is out of scope, so you can't access it).
You should set up the JS so that when the window loads, you execute the request to retrieve the data and then read it:
<script type="text/javascript">
window.onload = function() {
var myvar = MakeRequest();
alert( myvar);
}
</script>
You can then get rid of the onload within the <body> tag.
Note that I'm not entirely sure that you're returning the value from the MakeRequest() function correctly, since the return is within the xmlhttp callback and not in the function. You should investigate this and verify.

Refreshing my php page with AJAX every 5 seconds

I'm creating a link-sharing website and on my index.php page (the page I want to refresh every 5 seconds) there are posts/links that must appear automatically (AJAX refreshing) without the user to refresh by him/herself or pressing F5 the whole time.
How would this work, precisely?
You should use the setInterval javascript function to deal with this issue.
setInterval(callServer, REFRESH_PERIOD_MILLIS);
See:
some info on ajax Periodic Refresh
javascript setInterval documentation
[edit] some good refresh examples, especially without js framework (depending wether you want to use jquery, mototools, another or no framework...)
you have to user the setInterval method to call your ajax function to inject new content into your div:
<HTML>
<HEAD>
<TITLE>Hello World Page</TITLE>
<script language="JavaScript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq.overrideMimeType) {
xmlHttpReq.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) { // IE
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttpReq) {
alert('ERROR AJAX:( Cannot create an XMLHTTP instance');
return false;
}
xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttpReq.onreadystatechange = function() {
callBackFunction(xmlHttpReq);
};
xmlHttpReq.send("");
}
function callBackFunction(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var responceString = http_request.responseText;
//TODO implement your function e.g.
document.getElementById("myDiv").InnerHTML+ = (responceString);
} else {
alert('ERROR: AJAX request status = ' + http_request.status);
}
}
}
setInterval("xmlhttpPost('test.php')", 5000);
</script>
</HEAD>
<BODY>
Hello World
<div id="myDiv"></div>
</BODY>
</HTML>
Is there a need to use AJAX?
Unless I'm missing something; you could use the meta refresh tag:
<meta http-equiv="refresh" content="5">
I would recommend increasing the time between refreshes as this will put a heavier load on the server and may cause to freeze, or slow down the site.
Use setInterval(myAjaxCallbackfunction,[time in ms]).
Callback uses property of js that function are first class members(can be assigned to variables), and can be passed as argument to function for later use.

Jquery Ajaxing in Processmaker

I am using a web app called ProcessMaker.
They do not have support for jquery. So I had to figure out how to integrate it myself. There were lots of people on their forums trying to get it done, so thankfully it now has been documented. If anyone would like to do so here is the link where I have detailed the process: jQuery with ProcessMaker
My question is now using the jquery ajax request.
In order to use jquery with processmaker I had to overcome 2 problems. The first the Smarty filtering since processmaker uses templating langauge. And the second the Maborak lib doesn't allow certain things.
So now I believe it to be a maborak issue, but I do not know for certain. All I know when I try to run my code, the error console (firefox 4.x) gives me the following error: jqXHR[i] is not a function.
This is happening at line 7323 of my jquery lib that I included (version 1.6.2).
I have Googled, and all I have come up with so far is that people are saying it can possibly be a befreSend issue and that disabling it fixes it.
Maybe I don't know how to disable it properly, but it isnt working still.
If anyone can help me with this, it would be very greatly appreciated.
Thanks,
Zedd
In Processmaker exist a library "makorak" this library generate problems with other libraries.. hence you Should use jquery as follows...
var $JQ = jQuery.noConflict();
$JQ("#myField").value = 'cochalo';
hope I've helped
Try this:
$.noConflict();
jQuery(document).ready(function($)){
$("button").click.function(){
$("p").text("jquery is still working");
}
}
before:
you need declare this:
var $j = jQuery.noConflict();
and... you must don't use $() any more
instead:
use $j()
example:
// Use jQuery via $j(...)
$j(document).ready(function() {
$j("div").hide();
});
that's all
read new documentation about ajax in dynaform in this
or
Write this function
function ajax(url, callback, error, method, cache, async) {
async = async || true;
//alert(cache);
if (typeof(cache) == 'undefined') {
cache = false;
}
if (typeof(method) == 'undefined') {
method = 'GET';
}
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp = new XMLHttpRequest();
} else // code for IE5, IE6
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
if (typeof(callback) == 'function') {
callback(xmlhttp.responseText);
}
} else {
if (typeof(error) == 'function') {
error(xmlhttp.status);
} else {
alert('خطا : لطفا مجددا تلاش کنید.');
}
}
}
}
var d = new Date();
var n = d.getTime();
var getExplode = url.split("?");
scriptName = url;
param = '';
if (getExplode.length > 1) {
scriptName = getExplode[0];
param = getExplode[1];
if (cache == false) {
param = param + "&n=" + n;
}
} else {
if (cache == false) {
param = param + "n=" + n;
}
}
if (method.toLowerCase() == 'post') {
xmlhttp.open("POST", scriptName, async);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
} else {
xmlhttp.open("GET", scriptName + '?' + param, async);
xmlhttp.send();
}
}
and use it like this
var url = ajaxUrl + "OperationRenovation.php?Command=GetDetail&IdDarkhast=" + ID + "&Code=" + Code + "&Mabna=" + Mabna;
ajax(url, function(Response) {
alert(response);
}, function() {
alert('مشکل در برقراری ارتباط با سرور');
}, 'post');

changing values of array elements in javascript functions

These are my three functions that I am using in javascript :
function postRequest()
{
var xmlHttp;
if(window.XMLHttpRequest)
{ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', 'effort.php', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
get_string(xmlHttp.responseText);
dij();
}
}
xmlHttp.send(null);
}
function get_string(str)
{
get_integer = str.split(" ");
for(var i=0;i<214;i++)
{
vertex_i[j] = get_integer[i]*1;
j++;
}
j=0;
for(var i=214;i<427;i++)
{
vertex_f[j] = get_integer[i]*1;
j++;
}
j=0;;
for(var i=427;i<517;i++)
{
x[j] = get_integer[i]*1;
j++;
}
j=0;
for(var i=517;i<607;i++)
{
y[j] = get_integer[i]*1;
j++;
}
for(var m=0;m<90;m++)
{
for(var n=0;n<90;n++)
{
L[m][n] = -1;
}
}
for(var m=0;m<212;m++)
{
x1 = x[vertex_i[m]];
x2 = x[vertex_f[m]];
y1 = y[vertex_i[m]];
y2 = y[vertex_f[m]];
L[vertex_i[m]][vertex_f[m]] = parseInt(find_dist(x1,x2,y1,y2));
}
}
function point_it(event)
{
postRequest();
}
namely :
point_it(event),then postRequest(); and finally dij();
In these functions I use the data in three globally defined arrays,the elements of whose are derived from the data sent by the server(get_string function).
if I call dij() function from within the postRequest() function(after the get_string function I am able to access the correct data within the arrays.
However if I call it immediately after the postRequest() function the value of elements in the array become equal to null.
I am unable to understand the proper reason for this and have tried several ways to get through but with no progress.
CAn sm1 please help me out !
postRequest fires an asynchronous request to the server. Calling a function directly after it doesnt mean that the request has finished and youve doen anything with the response data. It works inside postRequest because that where you actually handle processing the request and response.
if you want to do this all from within point it i would recommend doing the following:
function postRequest(callback)
{
var callbackFunc = callback||null;
var xmlHttp;
if(window.XMLHttpRequest)
{ // For Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // For Internet Explorer
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('GET', 'effort.php', true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
get_string(xmlHttp.responseText);
if(callbackFunc){
callbackFunc();
}
}
}
xmlHttp.send(null);
}
function point_it(event)
{
postRequest(dij);
}
this allows you to vary the callback that uses the array thats been populated by the post request and in a away that it always fires after that request cycle is complete.
XMLHttpRequest is asynchronous.
That means, it will return as soon as the request was send. If you now call dij() the request will still be pending and get_string wasn't called yet.
As soon as the requests completes, the callback will be called, and then execute get_string.
You need to leave dij() inside the callback too.
Visually:
postRequest is made, sets the callback, but does not execute it, postRequest then returns
the code after the call to postRequest executes
some time passes...
the XMLHttpRequest finally completes and the callback executes, which now calls get_string
Global variables are not a good practice. It is better to combine your get_string and dij functions into one with your arrays as local variables inside the single function.

Categories