Foster
Foster

Reputation: 385

File being called by Ajax contains error

I have 2 pages, process page and form page.

So basically the form page consists of a lot of input text and once the user click the submit button, it runs the ajax call and call the process page. the process page requires user's credentials like id and password.

My ajax call basically success run, but the process page is not running. When there is no user logged in, the process page will output the undefined index message. In this case is the id or password, because basically there is no data passed(ID and Password) to the process page.

This is my ajax call function

function postTweet(){
$.ajax({
    url : 'blablabla',
    type : 'POST',
    data : blablabla,
    success: function() {
        div1.append("Success!");
 }})
 .fail(function(data){
    console.log(data);
  });
}

So basically after the non-loggedin user click the submit button, the Success message will still be displayed out, eventhough basically there is no process running in the process page.

What I want is, if the process basically is not running, I should prompt out a proper message.
Can someone help me please?

Any help given is highly appreciated. Thanks

Upvotes: 0

Views: 34

Answers (2)

Vince
Vince

Reputation: 1851

Your success function can handle arguments (look at ajax success here)

For example:

PHP File

<?php
echo json_encode(array('test' => "hello world")); // echo any array data
exit(); // Stop php from processing more, you only want the json encoded data to be echoed
?>

Javascript File

...
dataType: 'json', // This is needed to convert the echoed php data to a json object
success: function (response) { // "response" will be the converted json object
    console.log(response);
},
...

The console.log(response); would look something like Object {test: "hello world"}

EDIT

In your case, you could do something like this:

<?php
if ( ! isset($username) ) {
    echo json_encode(array('success' => FALSE, 'message' => "Username is incorrect."));
}
...
exit();
?>

To alert the above error message in javascript:

...
success: function (response) {
    if (response.success) {
        alert('success!');
    } else {
        alert(response.message);
    }
},
...

Upvotes: 1

Manish Shukla
Manish Shukla

Reputation: 1365

There are 2 ways to handle this issue.

  1. if form page contain login credential input then you can validate login credentials are filled or not in java script and then call ajax process.
  2. you can validate login credentials in ajax file using isset() method and if login credentials are not validated then you can send a simple message to ajax calls about login failed.

Upvotes: 0

Related Questions