2

So I am trying to open af php file that updates something in my database. I want to do this using AJAX since I dont want my entire page to update. After the php file has been ran I want to change an image on the page that triggered the php file.

How exactly is this done?

5 Answers5

3

Hope you are having jquery library

do an ajax call like this:

$('#upvote').click(function(){
    $.ajax({
        url : 'scripts/upvote.php', // give complete url here
        type : 'post',
        success : function(data){
            alert('success');
        }
    });
});

Hope this will help you

Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
1

This is one way to do an AJAX call. You don't really need to set it to POST:

$.ajax({
    url: 'anyphpfile.php',
    dataType: 'type', //the type of data you're expecting
    success: function(result){
        //do what you want to update here
    }
});
Minoru
  • 1,680
  • 3
  • 20
  • 44
1

The structure of when this is done depends on how you make your AJAX call. In the tags you've included jQuery, so I'm going to assume you're using the .ajax() function. For now I'll assume the use of the .then() callback (show your code if it's different). In that case you'd "change the image" here:

$.ajax({
  url: 'someurl.php'
}).then(function() {
  // change the image here
});

According to the documentation, .then() will always be called after the AJAX call completes. There are other, more specific functions such as .done() or .fail() which you can use as well. The comment in the code above indicates where you'd perform your action responding to the AJAX call. What action you perform isn't entirely clear. Are you just changing the src of an img? Something like this, then:

$('#theImage').prop('src', someUrlValue);

Where you get someUrlValue is up to you.

David
  • 208,112
  • 36
  • 198
  • 279
  • Nothing seems to happen when i press my image. This is my javascript code: http://pastebin.com/206b6sZn – Thobias Nordgaard Oct 25 '13 at 13:34
  • @ThobiasNordgaard: In what way does it fail? Check the JavaScript console for errors. For example, in your code you're using `someUrlValue` but you never defined it anywhere. You'll need to give it an actual value. Using browser debugging tools (such as FireBug or Chrome developer tools) you can check if the AJAX call is actually being made, what the response from the server is, even step through the JavaScript code in a debugger. You'll need to determine the specific problem happening here. – David Oct 25 '13 at 13:45
0

As shown in the JQuery docs:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function(result) {
    // Change image here
  },
  dataType: dataType
});
Pastor Bones
  • 7,183
  • 3
  • 36
  • 56
-1

Using jquery, simply as

$.ajax({url: "yourpage.php"});

Check reference for more options http://api.jquery.com/jQuery.ajax/

mguimard
  • 1,881
  • 13
  • 14