Why does such a file path work when an Ajax request is made

<script type="text/javascript"> $(function() { $("#send").click(function(){ var login = $("#login").val(); var password = $("#password").val(); $.ajax({ type: "POST", url: "sendMessage.php", data: {"login": login, "password": password}, cache: false, success: function(response){ var messageResp = new Array('Выполнено','Ошибка'); var resultStat = messageResp[Number(response)]; if(response == 0){ $("#login").val(""); $("#password").val(""); location.href='google.ru'; } $("#resp").text(resultStat).show().delay(1500).fadeOut(800); } }); return false; }); }); </script> 

And there is no such

 <script type="text/javascript"> $(function() { $("#send").click(function(){ var login = $("#login").val(); var password = $("#password").val(); $.ajax({ type: "POST", url: "http://удаленный сервер/sendMessage.php", data: {"login": login, "password": password}, cache: false, success: function(response){ var messageResp = new Array('Выполнено','Ошибка'); var resultStat = messageResp[Number(response)]; if(response == 0){ $("#login").val(""); $("#password").val(""); location.href='google.ru'; } $("#resp").text(resultStat).show().delay(1500).fadeOut(800); } }); return false; }); }); </script> 

The index.html file contains the form

 <form method="post" > <p>Логин:<br><input name="login" type="text" id="login"></p> <p>Пароль:<br><input name="password" rows="5" cols="50" id="password"></p> <input name="js" type="hidden" value="no" id="js"> <p><input name="button" type="submit" value="Отправить" id="send"></p> <p><span id="resp"></span></p> </form> 

The sendMessage.php file contains the request

 <?php $db = mysql_connect("localhost","demo","demo"); mysql_select_db("demo",$db); mysql_query("SET NAMES cp1251"); header("Content-type: text/html; charset=windows-1251"); if(empty($_POST['js'])){ $q=mysql_query("SELECT * FROM users WHERE username='".$_REQUEST['login']."'"); $result = mysql_fetch_array($q); if(($_REQUEST['login']==$result['username']) && (md5(md5($_REQUEST['password']))==$result['password'])) { echo 0; //Выполнено } else{ echo 1; //Ошибка } } ?> 

Why does the first Ajax request work, and the second request, with the path to the file (sendMessage.php) on the remote server does not work, what could be the problem, and how to fix it ???

  • Apparently you have a file in which the script has a relative path, is not in the root directory, where sendMessage.php is located - lampa
  • one
    Yes, it is not in the root directory, but I need it. It is necessary that the mobile application interacts with the database - webkostya

1 answer 1

In short, in my case, the problem was solved by this line

 header('Access-Control-Allow-Origin: *'); 

I pasted it into the file to which I addressed sendMessage.php

 // можно ограничить домен, для которого доступен ответ // header('Access-Control-Allow-Origin: http://javascript.ru ');