0

I am using AJAX to run a php file and send data with it. Currently I use

complete: function() {
              location.reload();
          }

To reload the page after the php file is done. What I want is that when there is an error in the external php file, an alert is displayed (Bootstrap). Displaying an alert is not the problem, I have a function for that that accepts the string and type of alert but that is in PHP. That leads me to two questions;

How do I get data back from the AJAX call?

How do I use that data to display an alert with a PHP function (after a reload possibly)?

Thanks!

EDIT: In my external php file I have:

header('Content-Type: application/json');
$error = 1;
echo json_encode($error);
B_s
  • 3,026
  • 5
  • 32
  • 51

1 Answers1

1

The first parameter of the complete will get the HTML in the response of the php =)

complete: function(response) {
    if(response==''){
        location.reload();
    }else{
        //another code here
    }
}

PS: Complete answer in the comments

Ernesto
  • 301
  • 1
  • 6
  • Thanks! How should I specify the contents of the response? – B_s Nov 09 '14 at 18:06
  • you coul print like ` echo "1" ?>` to set a good answer and if there is an error ` echo "2" ?>` Or ` if($error==true){echo "error";}else{echo "success";}` then with the response in javascript `if(response =='error'){ //code to call the dialog}` – Ernesto Nov 09 '14 at 18:08
  • thank you but if I check if response="1" and echo "1" the page does not reload. Don't I need to do something with JSON? Edit: I get back an [object Object], so probably something with JSON I guess? – B_s Nov 09 '14 at 18:14
  • in your php whatever you prints outs its what you get in the var response of the complete function , you could send a json string too and use `var obj=$.parseJSON(response);` and use the obj like a javascript object, that answer your questions? – Ernesto Nov 09 '14 at 18:18
  • http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script see this post to send an JSON objets by default – Ernesto Nov 09 '14 at 18:19
  • I get an object Object back as response. I do not know how I should properly return from my other php file? – B_s Nov 09 '14 at 18:21
  • use a `console.log(response)` it will tell you the properties of the object, you can put the php function to know what you retrieve to the ajax? – Ernesto Nov 09 '14 at 18:23
  • The console gives back a responseText: "1" in the object. I updated my question with my php. – B_s Nov 09 '14 at 18:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/64587/discussion-between-ernesto-and-bastiaan). – Ernesto Nov 09 '14 at 18:29