Link to home
Start Free TrialLog in
Avatar of hidrau
hidrauFlag for Brazil

asked on

Using Ajax help

Hello Guys

I have a php page where I have many function for database.

In this php page I have a function where I ask for a randon word, the function access my database and returns me a word from my table.

Today, so that it works, I need to reload the page but I'd like to start it when I click on the button and without relead the page I could get the

word from my function.

How could I do that in Ajax?

Thanks
Avatar of Mlanda T
Mlanda T
Flag of South Africa image

I'll put together a demo.  Stay tuned.
Here is a basic example.

HTML:

<input id="myTxt" type="text" placeholder="enter your word">
<input id="myBtn" type="button" value="Make It So!">

Open in new window


JQuery:

function doAjaxCall(word) {
  $.ajax({
    type: "POST",
    url: "/echo/json/",  //this should be the path of the page that does your db lookup
    data: { text: word }
  }).success(function(response) {
    console.log(response); //this is the response from your lookup
  });
}

$('#myBtn').click(function() {
  var word = $('#myTxt').val();
  if (word != "") {
    doAjaxCall(word);
  }
});

Open in new window


How it works:  There is an event listener waiting for the button to be clicked.  When clicked, we get the text from the input and call a function if the text is not blank.  The function sends the text via POST using an AJAX call.

You'll want to replace the value of the url property in the AJAX call with the path of the file that handles your database lookup.  On that database lookup page, you can find the word in $_POST['text'], and you'll want to echo the result of the lookup, which is what will be returned in the AJAX response.

Here is a JS Fiddle Demo.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hidrau

ASKER

Hello zephyr_hex,

I undestood what you gave me as example, but there is something that I didn't understand.

In my page where is the command in php that I access the database I have many functions, each functions run a determine query that results something diferent.

I need to indicate the function in that php page and the parameters.
How could I do that?
Did you get it?
If I'm understanding you correctly, you're saying that you also need to send a parameter that tells you what function should be run.  In that case, you can add that to the data parameter of the AJAX call.

data: { text: word, function: "myFunction" }

Open in new window


$_POST['function'] will contain the string "myFunction" in the example above
FYI - .success() is deprecated - switch to using done() instead :)
Avatar of hidrau

ASKER

Chris Stanyon

In your way, how could I inform the function that the ajax will must use?
Avatar of hidrau

ASKER

Hello zephyr_hex,

I am trying but it is not working.

You an access the page and try it.

http://www.teachmenow.com.br/tarot/palchv.php

to play with it, you have to choose one card for the text, after click on the button and then close the panel inf and after close the inf panel, this function will be called:

$("#alerta2 .close").click(function(){
				$(".well").show();
				doAjaxCall();
				//location.reload();
			});			

Open in new window


I couldn't able to insert again another value in my button center, the value is a new one word that correspond one of those cards.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hidrau

ASKER

Chris Stanyon,

Years ago I used ajax in a project. After 5 years without working with internet programming, I am a lot of rusty LOL,

I know that it is possible to access the function directly by ajax, but I don't remember it :(

The old project I had a db.php with many functions, I was able to use the function and pass the parameter without any problem, I don't remember how to do that anymore :( That is the problem.
Avatar of hidrau

ASKER

Althoug I am testing, maybe the solution is here

https://teamtreehouse.com/community/jquery-ajax-calling-php-function
If you have a PHP file with a lot of functions you need some way of knowing which function to call. The code posted will do that - you pass in the name of the function you want to call, and then code your script to read that parameter and call the approriate function.

There is no way to call a PHP function directly from AJAX. I don't know what you did years ago, but you wouldn't have just called a function from a PHP file - it's just not possible.
Avatar of hidrau

ASKER

Let me correct something.

The project years ago was made in asp and not php.
The code in the link is doing exactly what we're talking about - it's passing a parameter to the PHP file so that it knows which function to call - it doesn't (and can't) call the function directly.

In their code, the parameter is called 'action'. In my code it's called 'f' and in zephyr's code it's called 'function' - the principles though remain the same
Avatar of hidrau

ASKER

Chris Stanyon,

I am trying what you told me. But I am not getting the result :(
Avatar of hidrau

ASKER

Chris Stanyon,

I did a test with you gave me, I created a new project only with the test but nothing. :(

you can see it here:

http://www.teachmenow.com.br/tarot/test2.php

this is my php code :

<?php

			   
$servername = "xxxxxxxxxxxxxxxxxxxxxx";
$username   = "xxxxxxxxxxx";
$password   = "xxxxxxxxxxx";
$dbnome     = "xxxxxxxxxx";

if (isset($_GET['f'])):
    switch ($_GET['f']) {
        case 'ncd':
            pegaIdcartaRandon();
            break;
    }
endif; 


function pegaIdcartaRandon(){
    global $servername, $username, $password, $dbnome;
	
	$conn = new mysqli($servername, $username, $password, $dbnome);
	$conn->set_charset("utf8");
	//$conn = mysql_connect($servername, $username, $password, false) or print (mysql_error());

	
	if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
	
	$sql    = "select CARTAPALCHV_ID, palchv from CARTAPALCHV where SITUACAO='N' order by rand() limit 1";
	$result = $conn->query($sql);
	
    if ($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {
		$id =  $row["palchv"];}
    }
	else {
		$id = "-1";
	}
	
	$conn->close();	

	return $id;
}

?>

Open in new window


What is wrong?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hidrau

ASKER

I got the problem : )
Avatar of hidrau

ASKER

thanks a lot for your help.
Avatar of hidrau

ASKER

Only one thing.
If I need to pass parameter for me function, how should I do?
You can pass as much data as you need in your AJAX request, and then just strip them out of the query string. Here's a wuick idea but you'd probably want to do some sanity checking:

yourscript.php?f=ncd&someVar=123

if (isset($_GET['f'])):
    switch ($_GET['f']) {
        case 'ncd':
            $myVar = $_GET['f'];
            pegaIdcartaRandon($myVar);
            break;
    }
endif; 

Open in new window