4

To make this understandable I made an sample code because my actual code is much bigger.

Basically what I want to accomplish is to run my PHP script that edits an XML file using ajax. This is because I need to do this inside a javascript in my real project.

This is what I have so far:

the .php file containing the ajax function:

<!DOCTYPE html>
<html>
<head>
<script>
function editXMLDoc()
{
  $.ajax({
  url: "sensors.php",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});
}
</script>
</head>
<body>

<button type="button" onclick="editXMLDoc()">Endre XML</button>

</body>
</html>

And here is the php script writing to xml:

<?php
include 'sensor.php';
$b=new sensor();

$arr=$b->load('sensor.xml');         

for($i=0,$ms=count($arr);$i<$ms;$i++)
{
  if($arr[$i]['fields']['status']=='1')
  {
     $arr[$i]['fields']['status']='0';
  }else{
    $arr[$i]['fields']['status']='1';
  }
}
echo "Completed<br/>";
//3. save array to xml
$b->save('sensor.xml',$arr);
?>

I know the script is working so I am pretty sure the prob is the connection between the ajax function and the php script.

Can anyone help me out?

The Dude
  • 1,088
  • 7
  • 16
  • 30
  • In the Ajax you use the function sensors.php but the php file is called sensor.php. Or the file with the script is called sensors.php? – JuaRoAl Mar 27 '15 at 10:12
  • No its not. The php file includes another php file called sensor.php. I can see how that might be confusing. – The Dude Mar 27 '15 at 10:14
  • @user2927356: Did this answer your previous question http://stackoverflow.com/q/29278936/367456 as well? – hakre Mar 27 '15 at 20:30

5 Answers5

7

Try this code... actually you did not attached jQuery library.

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
            jQuery(document).ready(function($){
                var resp = $("#response");
                $.ajax({
                    type: "POST", // Method type GET/POST           
                    url: "sensors.php", //Ajax Action url
                    data: {},

                    // Before call ajax you can do activity like please wait message
                    beforeSend: function(xhr){
                        resp.html("Please wait...");
                    },

                    //Will call if method not exists or any error inside php file
                    error: function(qXHR, textStatus, errorThrow){
                        resp.html("There are an error");
                    },

                    success: function(data, textStatus, jqXHR){
                        resp.html(data);
                    }
                });
            });
        </script>
    </head>
    <body>
        <div id="response"></div>
    </body>
</html>
Sateesh
  • 1,327
  • 9
  • 12
1

Use AJAX like this:

<script type="text/javascript">
  jQuery(document).ready(function($){

    $('.rt11').click(function(){

        $.ajax({
            type: "POST", // Method type GET/POST           
            url: "sensors.php", //Ajax Action url
            data: {yourKey: "yourValue", yourKey1: "another value"},

            // Before call ajax you can do activity like please wait message
            beforeSend: function(xhr){
                console.log("Please wait...");
            },

            //Will call if method not exists or any error inside php file
            error: function(qXHR, textStatus, errorThrow){
                console.log("There are an error");
            },

            success: function(data, textStatus, jqXHR){
                console.log(data);
            }
        });

    });

});
</script>
Sateesh
  • 1,327
  • 9
  • 12
  • Ok, but how do I call this function with a button? – The Dude Mar 27 '15 at 10:41
  • In your ajax call you don't need "data", "beforeSend", and "type" atributes to make it simpler. And if it returns a xml file, add dataType: "xml". – JuaRoAl Mar 27 '15 at 11:06
  • Pass your element selector CLASS or ID inside **$('.rt11').click(function(){** – Sateesh Mar 27 '15 at 11:24
  • @Sateesh Sorry to be completely noobish, but when you say pass it inside, how do I do that. thought it would be something like this: – The Dude Mar 27 '15 at 11:38
  • I mean that you are using **class="rt11"** and this class already **$(".rt11")** used inside braces so on button click ajax request will call. if you are using Firefox then install AddOn called Firebug then check in console you will see ajax request. – Sateesh Mar 27 '15 at 11:41
  • @Sateesh Hm. how would the function look if I were to drop the button and let the ajax function run everytime the page is loaded? – The Dude Mar 27 '15 at 11:56
  • then you can remove on click function **$('.rt11').click(function(){** after that Ajax will call automatically on page load. – Sateesh Mar 27 '15 at 12:03
  • @Sateesh Ok! As I suspected this did not work, which is probably why I couldnt get the button to work either. So where am I going wrong. Do I have to say something in my php script to allow ajax to run it? – The Dude Mar 27 '15 at 12:12
  • No, AJAX is client script so PHP cant disable it. I think you have any other issue.. can you share your link? after that i can tell if there any error.. – Sateesh Mar 27 '15 at 12:16
  • I am working on localhost, but I can share a dropbox link if thats ok? – The Dude Mar 27 '15 at 12:23
  • yeah sure.. just share your link – Sateesh Mar 27 '15 at 12:30
  • Thanks ALOT https://www.dropbox.com/sh/o07ng25hzc97xvk/AAB5k6UQvCxAdthRJoyf_U4Ya?dl=0 – The Dude Mar 27 '15 at 12:42
0

I think there is no problem in code but sometime in large code the min.js file did not include properly. please try the below code. there is no need to change sensors.php file.

<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
    $('.rt11').click(function(){
  $.ajax({
  url: "sensors.php",
  context: document.body
}).done(function(html) {
  $( this ).addClass( "done" );
});
});
});
</script>
</head>
<body>

<button type="button" class="rt11">Endre XML</button>

</body>
</html>
sandeep soni
  • 303
  • 1
  • 12
0

HTML:

<button type="button" id="idButton">Endre XML</button>

JS:

  $("#idButton").click(function(){
        $.ajax({
                url: 'sensors.php',
                dataType: "xml", //if it returns a xml file
                success: function (data) {
                    // everything is ok
                    alert(data)

                },
                error: function (xhr, status, error) {
                    // Something went wrong
                    if (xhr.status > 0) alert('Error: ' + status);
                }
            });

        })    
JuaRoAl
  • 201
  • 2
  • 7
0

Try this i think you missed to include the jQuery library file.Get post data to your php file after ajax call.

    <!DOCTYPE html>
    <html>
    <head>
    //include the jQuery library file
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    function editXMLDoc()
    {
      var myvalue='123';  
      $.ajax({
              url: "sensors.php",
              context: document.body,
              data: {myvalue:myvalue},   
             }).done(function() {
                 $( this ).addClass( "done" );
             });
     }
    </script>
    </head>
    <body>

    <button type="button" onclick="editXMLDoc()">Endre XML</button>

    </body>
    </html>
Vijay
  • 421
  • 3
  • 12