How to invoke PHP file in AJAX/JavaScript? - php

I have this code that GET the php file using an AJAX method. The goal is to inform the user if the movie table is empty or not. If the table is empty, it will display a confirm box that will ask if the user wants to add movies or not?
Here's my index.php file:
Movies
Here's my moviestbl.php:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
?>
<script language="JavaScript">
var option = confirm("No Movies found. Add Movies now?");
if(option ==true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
}
else{
//do nothing. return to current window.
}
</script>
<?php
}
?>
And finally, here's my AJAX file.
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
</script>
When I click the link, it is not doing or displaying anything. need help. thanks.

You will need to get the data from server using an ajax request , the response could be in JSON format.
Suggestions .
use jQuery and $.ajax - for pulling data from server
on getting the response - do the confirm and switch window
You can structure the logic to handle specific logics at client & server
PHP : logic on server could beCreate and interface for responding with JSON result for status of entries on movie table. your current query should work fine.
Javascript: Make use of the interface defined on php to to query data and make use of the 'confirm' javascript to do the switching.
Right now if you change
Movies
to
Movies
You should see it working with page reloads and redirects.

This will probably work better:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
echo "empty";
}
?>
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
if(XMLHttpRequestObject.responseText === "empty"){
var option = confirm("No Movies found. Add Movies now?");
if(option == true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
} else{
//do nothing. return to current window.
}
}
}
}
XMLHttpRequestObject.send(null);
}
</script>

I was able to make the code run now. Thanks to Firebug and coffee. The anchor tag is the problem. I don't know why, but when I used the img instead, it worked.
<img alt="movies" style="cursor:hand;cursor:pointer;" onclick="checkMovieTbl('/movies/ajaxphp/moviestbl.php')"/>
The PHP Script file:
<?php
//fetch the data from the table movies
include '../phpfunc/connect.php';
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
$json = json_encode($countRows);
if($json == 0){
echo $json;
}
?>
And lastly, the AJAX file.
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTbl(url){
//if not false
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("GET", url, false); //not sync
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var response = XMLHttpRequestObject.responseText;
//alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
if(response==0){
//execute something here
}
}
else{
alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
}
}
XMLHttpRequestObject.send();
}
}
Thanks to everyone who answered my questions and helped me. Chiao!

Related

Separate url in autocomplete menu

I have an autocomplete jQuery menu, that output the name of all the users I have, from a MySQL database. I'm trying to link each selection to the proper profile. For that, the URL is something like: /profile.php?id=341, 341 that stands for the ID of the user selected.
The only problem, is that when I try to put the ID of a given user, ALL the ID of ALL the user are shown in the URL... and I want only the ID of the selected user!
I have tried with PHP, but I don't know what to add to the following line to make it work.
$req = mysql_query("select id, Username, EmailAddress from ***");
Should it be something like WHERE Username='username'....? Finally, I know that I should maybe try something else, without PHP, but I just want to test it that way! Thanks!
<input type="text" name="course" id="course" />
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#course").autocomplete("/test/test2.php", {
selectFirst: false,
formatItem: function(data, i, n, value) {
//make the suggestion look nice
return "<font color='#3399CC'>" + value.split("::")[0] + "</font>";
},
formatResult: function(data,value) {
//only show the suggestions and not the URLs in the list
return value.split("::")[0];
}
}).result(function(event, data, formatted) {
//redirect to the URL in the string
var pieces = formatted.split("::");
window.location.href = '/profile.php?id='+
<?php
mysql_connect ("***", "***","***") or die (mysql_error());
mysql_select_db ("***");
$req = mysql_query("select id, Username, EmailAddress from ***");
while($dnn = mysql_fetch_array($req))
{
echo $dnn['id'];
}
?>
;
console.log(data);
console.log(formatted);
});
});
</script>
Your MySQL query is true to every user in the database, so it returns all the users. If you want to go to "foo"'s profile, you need to tell the database to fetch "foo"'s id only. A unique row that the user has maybe there email and must be their username.
I assume you have an array in javascript which contains selected users:
var users = new Array("Daniel","Amy","Sandy");
then you need to use ajax to communicate to php:
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}//This can become an external file to link
</script>
so then you can post data to php:
<script>
var returnedStr = "";
function searchuser(){ //use searchuser function on a button to call
var usersStr = users.toString(); //the string that contain the users separated by ","
var ajax = ajaxObj("POST", "thisurl.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "fail"){ //i didn't include this in php, but you can add it yourself if you can't fetch from mysql
echo "Failed";
} else {
returnedStr = ajax.responseText;// when php echos
}
}
}
ajax.send("u="+usersStr);
}
</script>
then your php will need to handle the string:
<?php
if(isset($_POST["u"])){
$returnArr = array();
$returnStr = "";
$processedArr = explode(',', $_POST['u']); //Here the posted data will turn into an array
$lengthArr = count($processedArr);
for ($i=0; $i<=$lengthArr; $i++)
{
$req = mysql_query("SELECT id FROM xxx WHERE Username='$processedArr[$i]' LIMIT 1");
while($dnn = mysql_fetch_array($req))
{
array_push($returnArr, $dnn['id']);
}
}
$returnStr = implode(",",$returnArr);
echo ($returnStr);
}
?>
Now in Javascript returnedStr will hopefully be 1,2,3 or something like that.
Please comment if this doesn't work!

Update several elements via Ajax from PHP array result

I am trying to generate some invoices based on user's input (date selection). That is something like this:
The invoice.php file would let the user select a date from a form, and based on that selection the contents of the invoice (like amount, customer, etc.) on that same page would be updated through Ajax.
The ajaxInvoice.php would generate a MySQL query and in the end create an array with the corresponding table row based on date selection and merchant (unique row).
invoice.php
...
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var date = document.getElementById('date').value;
var merchant = document.getElementById('merchant').value;
var queryString = "?date=" + date + "&merchant=" + merchant;
ajaxRequest.open("GET", "ajaxInvoice.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
...
<form name="invoiceDate">
<input type="hidden" id="merchant" value="<?php echo $merchant; ?>" />
Date: <select id="date">
<option>2013-07-23</option>
<option>2013-07-25</option>
</select>
<input type="button" onclick="ajaxFunction()" value="Select Date" />
</form>
...
<div id="field_1">FIELD 1</div>
...
<div id="field_2">FIELD 2</div>
...
<div id="field_3">FIELD 3</div>
...
ajaxInvoice.php
include_once('includes/db.php');
$merchant = $_GET['merchant'];
$date = $_GET['date'];
$merchant = mysql_real_escape_string($merchant);
$date = mysql_real_escape_string($date);
$query = "SELECT * FROM settlements WHERE datePayment = '$date' AND merchant = '$merchant'";
$result = mysql_query($query) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
I was wondering if I could have access to that array this way:
echo $array[0]['fieldName'];
and update selected elements on the page based on different row fields. Not sure if getElementById or getElementByName should be used.
My question would be how to actually access the php array within the script part and also within the rest of the page, so that I can update the various div elements with the corresponding data obtained from the DB query after the user selects the date from the form.
In fact, if only one div has to be updated, the code works just fine, but I don't know how to extend the logic to update more than one div.
Any help or hints on the syntax or code logic would be greatly appreciated.
Thank you very much in advance!
I usually use JSON:
PHP at the server: echo json_encode($array)
JavaScript on the client: var response = JSON.parse(ajaxRequest.responseText)
Implemented:
invoice.php
...
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var response = JSON.parse(ajaxRequest.responseText);
// Now you can use:
response[0]['fieldName'];
// Like this
var ajaxDisplay = document.getElementById('field_1');
ajaxDisplay.innerHTML = response[0]['field_1'];
}
}
...
ajaxInvoice.php
...
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
// Encode to JSON
echo json_encode($array);

Changing include direction with javascript

I'm trying to change an include path with JavaScript. It need's to go from this
<?php include 'sections/welcome.php'; ?>
to this
<?php include 'sections/new_visitor.php'; ?>
to this
<?php include 'sections/nda.php'; ?>
and so on... do anybody know how to code this in JavaScript?
you can't change how PHP is coded via javascript. You can send variables to php via javascript and then PHP responds to those variables... it looks like you have a registration of sorts. If you're using standard HTTP requests, you could use javascript to append a $_GET variable to the action link. For Instance:
$('#form').attr('action', $('#form').attr('action') + '?page=welcome');
Then, upon clicking the link, PHP will have access to $_GET['page'], so in php you could:
switch($_GET['page'])) {
case 'welcome':
include 'section/welcome.html';
break;
case 'nda':
include 'section/nda.html';
break;
}
Look at the if(message ===1) statement below:) sorry for being such a noob :P
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("cat create that object hos");
}
function newuser(){
if(xmlHttp.readyState ===0 || xmlHttp.readyState ===4){
name = encodeURIComponent(document.getElementById('name').value);
company = encodeURIComponent(document.getElementById('company').value);
nationalities = encodeURIComponent(document.getElementById('nationality').value);
phonenumber = encodeURIComponent(document.getElementById('phonenumber').value);
queryString = "?name=" + name + "&?company=" + company + "&?nationalities=" + nationalities + "&?phonenumber=" + phonenumber + "&?URL= newuser";
xmlHttp.open("GET", "/php/database.php?" + queryString, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('newuser()', 1000);
}
}
function handleServwerResponse(){
if(xmlHttp.readyState ===4){
if(xmlHttp.status === 200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
if(message === 1){
//I want to call a function here, so i can change the include path
}else{
document.getElementBy("underInput").innerHTML = 'User already exist klick to sign in here <p style="color:blue" onclick=""></p>';
}
}
}
}
}

Voting redirect

I downloaded the PHP voting script from this website:
I have installed this and it works perfectly on my website, however I am looking at customising it slightly so that once a user has voted it then redirects them to a new page, or ideally opens up a lightbox.
I have narrowed it down to a javascript problem, and the javascript file is within the voting.js file.
Below is the following code found in that file:
// Ajax Voting Script - http://www.coursesweb.net
var ivotings = Array(); // store the items with voting
var ar_elm = Array(); // store the items that will be send to votAjax()
var i_elm = 0; // Index for elements aded in ar_elm
var itemvotin = ''; // store the voting of voted item
var votingfiles = 'votingfiles/'; // directory with files for script
var advote = 0; // variable checked in addVote(), if is 0 cann vote, else, not
// gets all DIVs, store in $ivotings, and in $ar_elm DIVs with class: "vot_plus", "vot_updown", and ID="vt_..", sends to votAjax()
var getVotsElm = function () {
var obj_div = document.getElementsByTagName('div');
var nrobj_div = obj_div.length;
for(var i=0; i<nrobj_div; i++) {
// if contains class and id
if(obj_div[i].className && obj_div[i].id) {
var elm_id = obj_div[i].id;
// if class "vot_plus", "vot_updown1", "vot_updown2", or "vot_poll" and id begins with "vt_"
if((obj_div[i].className=='vot_plus' || obj_div[i].className=='vot_updown1' || obj_div[i].className=='vot_updown2') && elm_id.indexOf("vt_")==0) {
ivotings[elm_id] = obj_div[i]; // store object item in $ivotings
ar_elm[i_elm] = elm_id; // add item_ID in $ar_elm array, to be send in json string tp php
i_elm++; // index order in $ar_elm
}
}
}
// if there are elements in "ar_elm", send them to votAjax()
if(ar_elm.length>0) votAjax(ar_elm, ''); // if items in $ar_elm pass them to votAjax()
};
// add the ratting data to element in page
function addVotData(elm_id, vote, nvotes, renot) {
// exists elm_id stored in ivotings
if(ivotings[elm_id]) {
// sets to add "onclick" for vote up (plus), if renot is 0
var clik_up = (renot == 0) ? ' onclick="addVote(this, 1)"' : ' onclick="alert(\'You already voted\')"';
// if vot_plus, add code with <img> 'votplus', else, if vot_updown1/2, add code with <img> 'votup', 'votdown'
if(ivotings[elm_id].className == 'vot_plus') { // simple vote
ivotings[elm_id].innerHTML = '<h4>'+ vote+ '</h4><span><img src="'+votingfiles+'votplus.gif" alt="1" title="Vote"'+ clik_up+ '/></span>';
}
else if(ivotings[elm_id].className=='vot_updown1') { // up/down with total Votes
// sets to add "onclick" for vote down (minus), if renot is 0
var clik_down = (renot == 0) ? ' onclick="addVote(this, -1)"' : ' onclick="alert(\'You already voted\')"';
ivotings[elm_id].innerHTML = '<div id="nvotes">Votes: <b>'+ nvotes+ '</b></div><h4>'+ vote+ '</h4><span><img src="'+votingfiles+'votup.png" alt="Vote Up" title="Vote Up"'+ clik_up+ '/> <img src="'+votingfiles+'votdown.png" alt="Vote Down" title="Vote Down"'+ clik_down+ '/></span>';
}
else if(ivotings[elm_id].className=='vot_updown2') { // up/down with number of votes up and down
var nvup = (nvotes*1 + vote*1) /2; // number of votes up
var nvdown = nvotes - nvup; // number of votes down
// sets to add "onclick" for vote down (minus), if renot is 0
var clik_down = (renot == 0) ? ' onclick="addVote(this, -1)"' : ' onclick="alert(\'You already voted\')"';
ivotings[elm_id].innerHTML = '<h4>'+ vote+ '</h4><span><img src="'+votingfiles+'votup.png" alt="Vote Up" title="Vote Up"'+ clik_up+ '/> <img src="'+votingfiles+'votdown.png" alt="Vote Down" title="Vote Down"'+ clik_down+ '/></span><div id="nupdown"><b id="nvup">'+ nvup+ '</b> <b id="nvdown">'+ nvdown+ '</b></div>';
}
}
}
// Sends data to votAjax(), that will be send to PHP to register the vote
function addVote(ivot, vote) {
// if $advote is 0, can vote, else, alert message
if(advote == 0) {
var elm = Array();
elm[0] = ivot.parentNode.parentNode.id; // gets the item-name that will be voted
ivot.parentNode.innerHTML = '<i><b>Thanks</b></i>';
votAjax(elm, vote);
}
else alert('You already voted');
}
/*** Ajax ***/
// create the XMLHttpRequest object, according to browser
function get_XmlHttp() {
var xmlHttp = null; // will stere and return the XMLHttpRequest
if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); // Forefox, Opera, Safari, ...
else if(window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE
return xmlHttp;
}
// sends data to PHP and receives the response
function votAjax(elm, vote) {
var cerere_http = get_XmlHttp(); // get XMLHttpRequest object
// define data to be send via POST to PHP (Array with name=value pairs)
var datasend = Array();
for(var i=0; i<elm.length; i++) datasend[i] = 'elm[]='+elm[i];
// joins the array items into a string, separated by '&'
datasend = datasend.join('&')+'&vote='+vote;
cerere_http.open("POST", votingfiles+'voting.php', true); // crate the request
cerere_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // header for POST
cerere_http.send(datasend); // make the ajax request, poassing the data
// checks and receives the response
cerere_http.onreadystatechange = function() {
if (cerere_http.readyState == 4) {
// receives a JSON with one or more item:[vote, nvotes, renot]
eval("var jsonitems = "+ cerere_http.responseText);
// if jsonitems is defined variable
if (jsonitems) {
// parse the jsonitems object
for(var votitem in jsonitems) {
var renot = jsonitems[votitem][2]; // determine if the user can vote or not
// if renot=3 displays alert that already voted, else, continue with the voting reactualization
if(renot == 3) {
alert("You already voted \n You can vote again tomorrow");
window.location.reload(true); // Reload the page
}
else addVotData(votitem, jsonitems[votitem][0], jsonitems[votitem][1], renot); // calls function that shows voting
}
}
// if renot is undefined or 2 (set to 1 NRVOT in voting.php), after vote, set $advote to 1
if(vote != '' && (renot == undefined || renot == 2)) advote = 1;
}
}
}
// this function is used to access the function we need after loading page
function addLoadVote(func) {
var oldonload = window.onload;
// if the parameter is a function, calls it with "onload"
// otherwise, adds the parameter into a function, and then call it
if (typeof window.onload != 'function') window.onload = func;
else {
window.onload = function() {
if (oldonload) { oldonload(); }
func();
}
}
}
addLoadVote(getVotsElm); // calls getVotsElm() after page loads
I did have a go at doing this myself and it did work in certain browsers, but not others. All I did was add change the code on line 66 from:
ivot.parentNode.innerHTML = 'Thanks';
to:
ivot.parentNode = window.location = "register2.php";
But as I said, this only works on certain browsers as on other browsers it doesn't add the information to the database, anyone know how I can resolve this?
The ajax request and the database operations are executed in the votAjax(elm, vote). So you have to add the code for redirecting after the execution of that request.
Most likely between lines 100-115
Did you mean :
window.top.location = 'register2.php';

sending php array to javascript function onclick

Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)

Categories