8 Replies - 1099 Views - Last Post: 23 July 2014 - 08:47 AM Rate Topic: -----

#1 soapstar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 14

Passing Ajax result to PHP SQL Query

Posted 18 July 2014 - 07:47 AM

Hi folks,

I've been pulling my hair out all day over this so I decided its time to get some expert help before I waste any more time!

Basically I want to be able to pass an Ajax result into a PHP SQL Query. Prefferably i want this to happen on the same PHP page. Here is what I have now:

review_course.php

 for (var i=0;i<=totalPages;i++) {
		   
		   		
		   		 if(pair[0]== 'page'+i){
	
					
			
					
					$.ajax({
                    type: "POST",
                    url: "func.inc.php",
                    data: {voteid: 'page'+i},
					dataType: 'text',
                    success: function(results){
				
						var res = results;
						console.log(res);
						alert(res);//alerting 'res' brings up correct result
						$('#commentid').val('<?php query2($_SESSION['pageNo'],$_SESSION['courseID'], $_SESSION['userID']) ?>');//NOT WORKING - TRYING TO INSERT SESSION VARIABLE 'pageNo' WHICH IS CREATED IN 'func.inc.php'  
//<?php query2(res,$_SESSION['courseID'], $_SESSION['userID']) ?>');//Inserting 'res' directly into PHP Query obviously wont work!
						

       				}
					});
					
						
					
				}
							
					 	
		   	}





func.inc.php

session_start();

$test = isset($_POST['voteid'])? $_POST['voteid'] : '';  
	
	
	
	$_SESSION['pageNo'] = $test; //setting a session variable
	
	echo $_SESSION['pageNo'];//echo session variable (works)




What this code is meant to do is post a variable to another PHP page (would preferably like it to be same page), GET this variable, sets a session variable then read this into the PHP Query. Can anyone give me any insight to why this doesn't work?

Thanks so much for any help!

Note:I haven't included all of my code, hopefully i have included enough to understand my problem.

Is This A Good Question/Topic? 0
  • +

Replies To: Passing Ajax result to PHP SQL Query

#2 andrewsw  Icon User is offline

  • blow up my boots
  • member icon

Reputation: 6541
  • View blog
  • Posts: 26,484
  • Joined: 12-December 12

Re: Passing Ajax result to PHP SQL Query

Posted 18 July 2014 - 08:58 AM

You need to clearly understand the difference between server and client-side processing. The php session-value (if there is any) has already been inserted into the page way before the Ajax request is ever made. Load the page and examine the source (View Source) of the page to see this.

Client and Server, briefly

You should ignore this specific issue and concentrate on understanding the difference between server and client-side processing. Once you understand this, you will be in a position to tackle the problem.
Was This Post Helpful? 1
  • +
  • -

#3 soapstar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 14

Re: Passing Ajax result to PHP SQL Query

Posted 21 July 2014 - 01:58 AM

Hey,

Thanks for your reply. I totally understand why this isn't working now, its impossible isn't it!

How can I actually take output from JS which is generated on the page then use this in a PHP query on the same page? Or is this just not possible.

thanks very much for your help

This post has been edited by andrewsw: 21 July 2014 - 02:39 AM
Reason for edit:: Removed previous quote, just press REPLY

Was This Post Helpful? 0
  • +
  • -

#4 andrewsw  Icon User is offline

  • blow up my boots
  • member icon

Reputation: 6541
  • View blog
  • Posts: 26,484
  • Joined: 12-December 12

Re: Passing Ajax result to PHP SQL Query

Posted 21 July 2014 - 02:34 AM

Your goal isn't entirely clear to me, but you can (generally) do several things:

When the page is first created you can embed a value from PHP in it, that you can refer to in the Javascript later. This value can either be hidden in the HTML somewhere (a hidden element) or created within a <script> as a JS variable:
echo "var jsVariable = $phpVariable;";

A value, or values, can be returned (echoed) by PHP from the Ajax request. One of these values could be retrieved from a session-variable.

So your end result should be achievable, you'll just need to work out how to approach it.

This post has been edited by andrewsw: 21 July 2014 - 02:38 AM

Was This Post Helpful? 0
  • +
  • -

#5 soapstar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 14

Re: Passing Ajax result to PHP SQL Query

Posted 23 July 2014 - 01:44 AM

Hi,

Thanks for explaining to me. I have worked out another way I can do this using Ajax however I still cant use the updated result in my PHP query via a session variable. My code is as follows:


review_course.php
<?php

//DB CONNECTION STUFF UP HERE

//PHP CODE 
//- CHECKS IF FORM HAS BEEN SUBMITED
//- DETERMINES WHAT PAGE THE IFRAME IS CURRENTLY ON (DETERMINED BY getPageNo() BELOW)
//- THEN UPDATE (OR INSERT IF USER/COURSE DOESN'T EXIST) DATABASE ACCORDINGLY USING THE CURRENT PAGE NUMBER, USER ETC
//- DONE

if(isset($_POST['commentname'])){

$comment = $_POST['commentname'];
	
			$query1 = "SELECT * FROM comments WHERE user_id='{$_SESSION['userID']}' and course_id='{$_SESSION['courseID']}'";
			$result1 = mysql_query($query1);
			$count1 = mysql_num_rows($result1);

for($i = 1; $i < 100; $i++){

if($_SESSION['test'] == 'page'.$i){//SESSION VARIABLE NEEDS TO BE UPDATED EVERY TIME  getPageNo() IS RUN FOR THIS TO WORK
		
					debug_to_console($i);
					if($count1==1){
		
						mysql_query("UPDATE comments SET page{$i}='$comment' WHERE user_id='{$_SESSION['userID']}' AND course_id='{$_SESSION['courseID']}'");
		
		
					}else{
	
						mysql_query("INSERT INTO comments (user_id,course_id,page{$i}) VALUES ('{$_SESSION['userID']}','{$_SESSION['courseID']}','$comment')");
		
					}
				}
			}

?>

<html>
<head>

//IFRAME
//IFRAME LOADS AN EXTERNAL PAGE (ON SAME DOMAIN)- The src will be updated from the DB in the future
//ON LOADING THE FUNCTION getPageNo() is started

<iframe style="margin: 0 auto; text-align: center;" src="http://localhost/how/Page 1.html?CourseTitle=the course title&TotalPages=22&page1=1"  onload=getPageNo() width="976" height="564" frameBorder="none" id="theFrame" >
</iframe>

<form action="review_course.php?" method="POST" name="commentform" id="commentform">

<script type="text/javascript" src="js/jquery-2.0.3.min.js" language="javascript"></script>
<script type="text/javascript">

//-getPageNo() FUNCTION
//-GETS THE CURRENT URL OF IFRAME
//-RETURNS THE VALUE OF THE LAST URL PARAMETER IN THE URL ('page1=1' in this case, shows that its currently on page 1)
//-SUBMITS RESULT TO session_write.php TO UPDATE SESSION VARIABLE WITH CURRENT PAGE NO

function getPageNo(){

var query = document.getElementById('theFrame').contentdocument.location.search.substring(1);
var vars = query.split("&");
var pair = vars[vars.length-1].split("=");
var totalPages = 0;
var pageNo = "0";
var newURL ="";;
var results;


for (var i=0;i<vars.length;i++) {
			   
   var pair2 = vars[i].split("=");
				
				
   if(pair2[0] == 'TotalPages'){
					  
      totalPages = pair2[1];
					
   }
}

for (var i=0;i<=totalPages;i++) {

   if(pair[0]== 'page'+i){

      pageNo = 'page'+i;

      //-AJAX
      //-POSTS THE CURRENT PAGE NUMBER 'page1' TO session_write.php TO CREATE A SESSION VARIBALE CONTAINING CURRENT PAGE NUMBER
      $.ajax({
      type: "POST",
      url: "session_write.php",
      data: { name: "page"+i},
      success: function(results){
	
	 console.log(results);//RETURNS THE CORRECT PAGE NUMBER ('page1' for example)

      }
      });
   }												 	
}
								   
   return(false);
		   		 		   
}

</script>

</form>

//TEXT AREA WHICH UPDATES DATABASE WITH TEXT

<textarea rows="10" cols="119" maxlength="1000" id="commentid" name="commentname" form="commentform"></textarea>

</body>
</html>




session_write.php

<?php
session_start();

//-CREATE A SESSION VARIABLE TO USE IN review_course.php TO DETERMINE CURRENT PAGE NUMBER OF IFRAME

$_SESSION["test"] = $_POST["name"];
echo $_SESSION['test'];//echos page1,page2,page3 etc everytime a new page is opened in iframe *WORKS*


?>





Now on running this the current page number is successfully output from the ajax success result in realtime when i change pages on the iframe. HOWEVER the session variable which is being created is not being read by the PHP on review_course.php in realtime, ONLY when i reload the page does it pick up the updated session variable. I assume this is because the PHP is run once on course_review.php and never again until page reload?

How can I get the PHP to read in the session variable without having to reload the page entirely?

Thanks to anyone who can help me. Much appreciated!

This post has been edited by andrewsw: 23 July 2014 - 10:07 AM
Reason for edit:: Removed previous quote, just press REPLY

Was This Post Helpful? 0
  • +
  • -

#6 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3778
  • View blog
  • Posts: 13,691
  • Joined: 08-August 08

Re: Passing Ajax result to PHP SQL Query

Posted 23 July 2014 - 03:35 AM

DO NOT USE DEPRECATED MySQL functions!!! Use prepared statements in PDO or MySQLi.
Was This Post Helpful? 0
  • +
  • -

#7 soapstar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 18-July 14

Re: Passing Ajax result to PHP SQL Query

Posted 23 July 2014 - 03:44 AM

View PostCTphpnwb, on 23 July 2014 - 03:35 AM, said:

DO NOT USE DEPRECATED MySQL functions!!! Use prepared statements in PDO or MySQLi.


Hi,

Im sorry but I don't understand what you mean. Can you please give me a little more insight relating my code please?


Thanks
Was This Post Helpful? 0
  • +
  • -

#8 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3778
  • View blog
  • Posts: 13,691
  • Joined: 08-August 08

Re: Passing Ajax result to PHP SQL Query

Posted 23 July 2014 - 03:48 AM

Your code is highly vulnerable to SQL injection attack. Do a web search on it.

There's a great PDO tutorial here. Read it, then read it again, then study it. Finally, use it. Do not pass Go, do not collect $200, do not do any other PHP coding until you know it.
Was This Post Helpful? 0
  • +
  • -

#9 chris98  Icon User is offline

  • D.I.C Lover

Reputation: 40
  • View blog
  • Posts: 1,104
  • Joined: 06-July 13

Re: Passing Ajax result to PHP SQL Query

Posted 23 July 2014 - 08:47 AM

And since the best way to understand something is by doing it, here's a link to an SQL Injection tutorial. Do this on your scripts and you'll see exactly how vulnerable they are:

http://voice0fblackh...torial-for.html

This post has been edited by chris98: 23 July 2014 - 08:48 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1