How to achieve the same behaviour in Ajax

$usrname = $this->session->userdata('username');
$password = $this->session->userdata('password');

$data = array('userName'=>urlencode($usrname),'password'=>urlencode($password));
$data_string = json_encode($data);
$datanew = "loginemployee=". $data_string;

$method = 'post';
$format = 'application/json';
$this->rest->format($format);
$login_url = $this->login_url;
//print_r($login_url);
//exit;
$result = $this->rest->{$method}($login_url, $datanew);

Can anybody please assist me with this. This is actually a PHP script to login into a website, I need to achieve the same on my Cordova app which uses only HTML and JQuery, so please provide me info on how to do this.

$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').attr('value'); // get username
var password = $('#password').attr('value'); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew  = "loginemployee=". $jsonString;
if(jsonString)
{
  alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
  $.ajax({
    type: "POST",
    url: "http:// i know URL", // URL 
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    // send username and password as parameters 
    data: datanew,    // script call was *not* successful
    error: function (XMLHttpRequest, textStatus, errorThrown) {
    $('div#loginResult').text("responseText: " +    XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
    $('div#loginResult').addClass("error");
  }, // error 
  // script call was successful 
  // data contains the JSON values returned by the Perl script 
  success: function (data) {
    alert("success");

    if (data.error) { // script returned error
        $('div#loginResult').text("data.error: " + data.error);
        $('div#loginResult').addClass("error");
    } // if
    else { // login was successful
      alert(data);
      console.log(data);
        $('form#loginForm').hide();
       $("#loginResult").append('all good');
      } //else
    } // success
  }); // ajax/ if
} // if
else {
  $('div#loginResult').text("enter username and password");
  $('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});

You have done some mistakes in code and I listed those thing below.

  • Don't use $('#username').attr('value') . Instead of use $('#username').val() . Because $('#username').attr('value') return the value of the element while the html created. But $('#username').val() will return the current value. Same as change $('#password').attr('value') to $('#password').val() . For more information check this post.
  • Concatenation operator in javascript is + not . . And also u added a variable like $jsonString .
  • In your Server php code, if your using $_POST['loginemployee'] to retrieve the post values means don't use contentType: "application/json; charset=utf-8", . Because it will use the entire content including key as invalid json like loginemployee={"userName":"cloud","password":"cloudnine"} . If you need like that means u need to use file_get_contents('php://input') to retrieve the post content. But better don't use contentType in ajax. So you can able to easily get the post content using $_POST['loginemployee'] .
  • And also if the reply is json means use dataType in ajax, else dont use that. For more information about contentType and dataType check this post.
  • So, I updated the code. Check and reply back if there is any issues. Hope it will work as your wish.

    $(document).ready(function(){
        $('form#loginForm').submit(function() { // loginForm is submitted
            var username = $('#username').val(); // get username
            var password = $('#password').val(); // get password
            alert(username);
            var UserData= {"userName":username , "password":password};
            var jsonString=JSON.stringify(UserData);
            var datanew  = "loginemployee="+ jsonString;
            if(jsonString)
            {
                alert("encoded"+jsonString);
            }
            if (username && password) { // values are not empty
                console.log(datanew);
                $.ajax({
                    type: "POST",
                    url: "http://url_to_post", // URL 
                    // contentType: "application/json; charset=utf-8",
                    // If reply is json means uncomment the below line.
                    // dataType: "json",
                    // send username and password as parameters 
                    crossDomain : true,
                    data: datanew,    // script call was *not* successful
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $('div#loginResult').text("responseText: " +    XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
                        $('div#loginResult').addClass("error");
                    }, // error 
                    // script call was successful 
                    // data contains the JSON values returned by the Perl script 
                    success: function (data) {
                        alert("success");
                        if (data.error) { // script returned error
                            $('div#loginResult').text("data.error: " + data.error);
                            $('div#loginResult').addClass("error");
                        } // if
                        else { // login was successful
                            console.log(data);
                            $('form#loginForm').hide();
                            $("#loginResult").append('all good');
                        } //else
                    } // success
                }); // ajax/ if
            } // if
            else {
                $('div#loginResult').text("enter username and password");
                $('div#loginResult').addClass("error");
            } // else
            $('div#loginResult').fadeIn();
            return false;
        });
    });
    
    链接地址: http://www.djcxy.com/p/46156.html

    上一篇: 将JSON数据发送到WebMethod

    下一篇: 如何在Ajax中实现相同的行为