Micael Dias
Micael Dias

Reputation: 341

Using ajax with unique ids

Hey guys I need to have ajax on my website but I have no clue of javascript. I'm building my very first website and all I know is a bit of PHP and HTML/CSS. Anyway, what I need is to send to a different.php an ID using the GET method and I've done that page to display json with the response.

"success":"true";
"success":"duplicate";
"success":"false",
"reason":"theReason";
"premium":"error";

Those are the responses I can get. What I want is 3 different behaviours depending on the message. I will write in PHP to try to make it more clear.

if(success == true OR duplicate){    
    // change div bg color: green;    
    // hideDiv after 0.2seconds;    (want to give time for users to see the green);    
}else if(success == false){    
    // change div bg color: red;
    // alert: "theReason";
}else{    
    // "premium":"error";    header('Location: page.php');
}

Since all the relevant Divs are loaded from a database the ID to send to different.php can be easily found. I can do

<div id="123">

if it makes it easier or

<a href="different.php?id=123">Submit</a>

I know this is not very good question but I was reading about AJAX and I didn't understand it.

Upvotes: 0

Views: 229

Answers (1)

Dennis Trukhin
Dennis Trukhin

Reputation: 59

You can use jQuery for that. 1. Download jQuery: http://jquery.com/download/ 2. Include the script you downloaded into your webpage:

<script src='/path/to/downloaded/jquery'></script>
  1. Then it all depends on when you want your ajax to be executed. Let's assume you have a link that should load your data. Then you can do it like that:

HTML code

<a id='#mylink' data-id='123>My link</a>

Javascript code

<script>
$('#mylink').on('click', function() {
    $.get('different.php', {'id': $(this).attr('data-id')}, function(resonse) {
        // response variable contains your JSON from different.php script, so write here you JavaScript code that uses it
    });
});
</script>

Hope it helps.

Upvotes: 1

Related Questions