Jump to content

Returning something


Shadowing

Recommended Posts

Hey guys i just started trying out ajax and my knowledge of java script is still really low.

 

Im trying to test to make sure im even grabing the php file. So i want to return something so i know its working.

so i put this div tag with some words on the file "include_evaluate.php"

 

<div id="myDiv">
Ajax is working
</div>

 

So when i click the button with the id evaluate i want it to display "Ajax is working".

so i dont know what i need to add to this to make it return whats in the div.

 

 

    <script>
    
     $(document).ready(function(){
   $("#evaluate").click(function(event){
      
     xmlhttp.open("GET","\System_Lords\ajax\include_evaluate.php",true);
     xmlhttp.send();

     document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

   });

    });
   
   </script>

Link to comment
Share on other sites

A simple example.

 

foo.php

echo json_encode(array('msg' => 'Hello from foo.php'));

 

index.html

<!DOCTYPE html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.js"></script>
    <script>
      $(document).ready(function() {
        $("#linky").click(function() {
          $.ajax({
            url: 'foo.php',
            type: 'POST',
            dataType: json,
            success(response) {
              $('#foo').html(response.msg);
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <a href="#" id="linky">Click</a>
    <div id="foo"></div>
  </body>
</html>

 

I generally return JSON form ajax as it allows you to easily pass back more than one value.

 

Plenty more examples in the docs. http://api.jquery.com/jQuery.ajax/

Link to comment
Share on other sites

I should show an example of sending data to php too I guess.

 

index.php

<!DOCTYPE html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.js"></script>
    <script>
      $(document).ready(function() {
        $("#linky").click(function() {
          $.ajax({
            url: 'foo.php',
            type: 'POST',
            dataType: json,
            data: {
              msg_from_js: 'Hello from jQuery'
            },
            success(response) {
              $('#foo').html(response.msg);
            }
          });
        });
      });
    </script>
  </head>
  <body>
    <a href="#" id="linky">Click</a>
    <div id="foo"></div>
  </body>
</html>

 

foo.php

// send the message back to js.
echo json_encode(array('msg' => $_POST['msg_from_js']));

Link to comment
Share on other sites

I'm getting hit with a script error on just displaying the index page before even clicking on the link. is there something im doing wrong?

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

<script type="text/javascript" src="/system_lords/jquery/jquery-1.7.1.min.js"></script>

<script>      

$(document).ready(function() {        

$("#linky").click(function() {          

	$.ajax({            

		url: 'foo.php',            

		type: 'POST',            

		dataType: json,            

		data: {              

			msg_from_js: 'Hello from jQuery'            

			},            

			success(response) {              

				$('#foo').html(response.msg);            

				}        

				});        

				});      

				});    
</script>  
</head>  

<body>    

<a href="#" id="linky">Click</a>    

<div id="foo"></div>  


</body>
</html>

Link to comment
Share on other sites

says its expecting a bracket } line 27 which is line success(response) {

 

 

maybe i should use FF and download this thing called fire bug i hear so much about to see java script errors better

 

I dont understand the syntax at all when "success" starts. cause for how im reading it its following parameters. So is that suppose to be part of the data parameter or a new one

Link to comment
Share on other sites

alright i have firebug now :)

 

I cant see where it shows errors on it though.

 

I added the quotes around json and still have the error.

 

IE is saying expecting : on line 27

 

I should of noticed the quotes not being around json my text editor was saying something was wrong and I didnt realize it. I notice the comma before success. so success is acting as the 5th parameter? how can that be shouldnt each parameter be a word followed by a colon? trying to understand the syntax on how its changing towards last

Link to comment
Share on other sites

lol that was confusing the heck out of me haha. , cause i barley know java script as it is lol.  alright its all working now.

Im going to bed. will take off from here when i wake up.

 

one question though. this whole json thing is new to me lol.

 

You are putting the POST in an array. so how do I echo each value seperatly when Im returning more then one thing in the array, do I use list() like i would a php function?

Link to comment
Share on other sites

Sorry Thorpe, im really trying to understand this, read about json for the first time. But i dont see any json code going on in this script?

I attempted to add a 2nd return to your code

 

so if I understand this right

msg1_from_js is the name of the _POST im grabing from

responce is responce .key

 

now I want to put these into a variable i guess so i can like print var msg1 = $('#foo').html(response.msg1);           

document write it i think it is for java script" as I wish in my DIV.

so i dont really want to mention the #foo id. also i noticed if i just do this

 

$('#foo').html(response.msg1);           

$('#foo').html(response.msg2);

 

The second one just over writes the first one lol.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="/system_lords/jquery/jquery-1.7.1.min.js"></script>

<script>      

$(document).ready(function() {        

$("#linky").click(function() {          

	$.ajax({            

		url: 'foo.php',            

		type: 'POST',            

		dataType: 'json',            

		data: {              

			msg1_from_js: 'Hello from jQuery',            
			msg2_from_js: 'Hello again from jQuery'
			},            

			success: function(response) {              

				var msg1 = $('#foo').html(response.msg1);            
				var msg1 = $('#foo').html(response.msg2);
				}        

				});        

				});      

				});    
</script>  
</head>  
<body>    

<a href="#" id="linky">Click</a>    

<div id="foo"></div>  

</body>
</html>

 

 

<?php
echo json_encode(array('msg1' => $_POST['msg1_from_js'] , 'msg2' => $_POST['msg2_from_js']));
?>

Link to comment
Share on other sites

Ahh i just got rid of the foo.php file and it still works. so ajax isnt even reading from the file its just posting whats in data:

 

thats makes sense why the keys wasnt working cause it wasnt even reading from an array or anything.

Link to comment
Share on other sites

I got rid of the data field and then added something into the array and it works. so now i know im grabing from the file.

 

I dont understand how its was able to echo it when i got rid of the php array in the php file.

 

cause its response.msg so i would think it could only grab the key in the php file.

Link to comment
Share on other sites

lol i dont know what was going on. probably cause i have to many windows open. but everything i said was going on wasnt. when i delete the php code it doesnt work at all like it should.  I had the example up in another window so i think i edited it which wasnt the real foo.php file.

Link to comment
Share on other sites

Hey Thorpe thanks alot, i got everything figured out now.

figured out how to grab form data and pass variables to the php file. Man my mind is going a million miles an hour thinking of all the kewl stuff i can build now knowing how to use ajax.

in a few months im going to make a much more advance game map. in the mean time i want to make a chat system.

I really like using Json.

Link to comment
Share on other sites

Hey thorpe

 

is it possible to tell ajax to call a php function from a php file or am I stuck with having to use a new php file for every php script I want to run? I sure hope there is a way cause that is going to be messy creating so many files.

Link to comment
Share on other sites

Iv'e siad this before but it's just anormal request. Just like you requesting a page with your browser.

 

In order to have a function executed you could use a simple series of if statement, or build a very simple front controller:

 

<?php

if (isset($_GET['action')) {
  if (function_exists('action' . ucfirst($_GET['action'])) {
    $func = 'action' . ucfirst($_GET['action']);
    $func();
  }
}

function actionFoo() {
  return json_encode(array('msg' => 'Hello from foo()'));
}

// more functions.

 

Then just use a url such as /somepath/somescript?action=foo in your Ajax call.

Link to comment
Share on other sites

holy crap thats an amazing idea

 

thanks man. I would of never of doing that. I googled that for a hour and no one mentioned doing this lol.

 

I just realize i could use a php switch for this for the first time if i have alot of functions on a page.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.