Ajax request in cordova not working - php

I am using ajax request to a php script in order to registrate a new user, it works and saves it in the database, but returns as error and not as success.
This is my ajax request:
$.ajax({
type: "POST",
url: "http://localhost/webAPI/register.php",
data: dataString,
crossDomain: true,
cache: false,
success: function (data) {
if (data == 1)
alert("success");
else(data == 0 )
alert("error");
},
error: function (){
alert("An Error Ocurred");
}
});
and this is my php script:
if($_POST)
{
$user_name = $_POST['username'];
$user_password = $_POST['password'];
$joining_date = date('Y-m-d H:i:s');
//password_hash see : http://www.php.net/manual/en/function.password-hash.php
$password = password_hash( $user_password, PASSWORD_BCRYPT, array('cost' => 11));
//if($count==0){
$stmt = $db_con->prepare("INSERT INTO users(username,password,joiningdate) VALUES(:uname,:pass,:jdate)");
$stmt->bindParam(":uname",$user_name);
$stmt->bindParam(":pass",$user_password);
$stmt->bindParam(":jdate",$joining_date);
if($stmt->execute())
{
echo 1;
}
else
{
echo 0;
}
}

replace else(data == 0 ) with else
$.ajax({
type: "POST",
url: "http://localhost/webAPI/register.php",
data: dataString,
crossDomain: true,
cache: false,
success: function (data) {
if (data == 1)
alert("success");
else
alert("error");
},
error: function (){
alert("An Error Ocurred");
}
});
and in PHP code
if($stmt->execute())
{
exit(1);
}
else
{
exit(0);
}

You could parse the PHP response in JSON in order to check the result from JS.
The PHP response :
if ($stmt->execute()) {
die(json_encode(['return' => true]));
} else {
die(json_encode(['return' => false]));
}
And from JS, just check the return flag :
$.ajax({
type: "POST",
url: "http://localhost/webAPI/register.php",
data: dataString,
dataType: 'JSON', // tell JS that the PHP response is json formated
crossDomain: true,
cache: false,
success: function (data) {
if (data.return) { // check if return is true
alert("success");
} else { // if return is false
alert("error");
}
},
error: function (jqXHR, textStatus, errorThrown){
console.log(textStatus, errorThrown); // this will tell you more in case of unsuccessful request
}
});
Hope it helps.
EDIT :
Look at the Ajax error attribute function. It must tell you more about the error.
RE-EDIT :
The dataString you send to PHP must be a JSON object. So from your comment, it must look like :
var dataString = {
username: $("#username").val(),
password: $("#password").val()
};

The only problem was the missing datatype property in the ajax request.

Related

Ajax request dont send $_POST propertly

Im trying to develop an android app using php, jquery, mysql and phonegap.
Phonegap environment don't let me use php, but I can locate it in to my server and I request data from database with ajax.
I can do simple queries, but when I use a var taken from $_POST, it doesn't works, exactly way isset($_POST['any_var']) returns false, but if I do isset($_POST) returns true, so I think I have an incorrect dataString.
I'm new in this kind of develop any clue in helpful.
<script>
$(document).ready(function()
{
$("#login").click(function(){
var nombre=$("#nombre").val();
var pass=$("#pass").val();
var dataString= "nombre="+nombre+"&pass="+pass+"&login=true";
if($.trim(nombre).length>0 & $.trim(pass).length>0){
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").val('Conectando...');
},
success: function(data){
return data;
},
error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown);}
});
var url="https://crm.inter-web.es/app/json.php";
$.getJSON(url, function(track){
console.log(track);
$(".list").append("<li>Nombre "+track['nombre']+"</li>");
$(".list").append("<li>Pass "+track['pass']+"</li>");
});
}return false;
});
});
</script>
PHP code:
<?php
//server code
include "db.php";
if (isset($_POST['login'])) {
$q=mysqli_query($con,"select nombre, pass from usuarios where nombre='".$_POST['nombre']."'");
$datos=mysqli_fetch_all($q, MYSQLI_ASSOC);
$num=mysqli_num_rows($q);
$json=json_encode($datos);
echo $json;
}else{
$q=mysqli_query($con,"select * from clientes where id_cliente='62' ");
$datos=mysqli_fetch_array($q, MYSQLI_ASSOC);
$num=mysqli_num_rows($q);
// var_dump($datos);
// for ($i=0; $i < $num ; $i++) {
// echo $datos[$i][0]."<br>";
// }
$json=json_encode($datos);
// mkdir("./json/");
// $fp=fopen("json/json.json", "w+");
// fwrite($fp,$json);
echo $json;
}
?>
Instead trying to format a "dataString"... I suggest you to use an object:
dataObject = {
nombre: $("#nombre").val(),
pass: $("#pass").val(),
login: true,
}
And in the ajax:
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataObject,
// ...
success: function(data){
// return data; // That line does nothing.
console.log(data);
},
Finally, I did this with GET in stead of POST, my first code was redundant, I did 2 request to the server:
$.ajax({
type: "POST",
url:"https://crm.inter-web.es/app/json.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").val('Conectando...');
},
success: function(data){
return data;
},
error: function(jqXHR, textStatus, errorThrown){ alert(errorThrown);}
});
AND:
$.getJSON(url, function(track){
console.log(track);
$(".list").append("<li>Nombre "+track['nombre']+"</li>");
$(".list").append("<li>Pass "+track['pass']+"</li>");
});
I modify the url with the GET parameters in the second way ("https://url?name=name&pass=pass") and it Works fine.

Jquery Ajax - post huge string value in Ajax

I have tried this below link but not working in my server.
Jquery Ajax - post huge string value
Try this one
$.ajax({
type: "POST",
url: "your_url",
data: {string:3MB_string},
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});

How handle errors in php script fired by Jquery.ajax?

I have php-script, firing with jquery ajax function. Somthing like this:
$("a.test").click (function () {
var new_id = $(this).attr("new_id");
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(){
alert('error');
}
});
return false;
});
Now, a have some errors in test.php, but I can't see them. Sript just runs and I have no feedback, only error alert (alert ('error')).
How can I get back errors, that I have in test.php to handle them?
If you echo the errors in test.php, you can simply do:
$.ajax({
url: 'test.php',
type: "POST",
cache: false,
async: true,
data: ({
new_id : new_id
}),
success: function (data) {
alert (data);
},
error: function(data){
alert('error:'+data);
}
});
return false;
});
Edit:
I usually do something like this. In test.php if you get an error, create an array with your error info and echo it json encoded:
$message=array('error' => 1,'message' => '<div class="alert alert-danger" role="alert">' . $login['message'] . '</div>' );
echo json_encode($message);
Now in your jquery you can retrive the error by:
success: function (data) {
alert (data);
},
error: function(data){
var obj = JSON.parse(data);
alert(obj.message);
}
When you have it in array like this you dont even need error: function(data) anymore, since you can simply:
success: function (data) {
var obj = JSON.parse(data);
if (obj.error) {
// do something
alert (obj.message);
}else{
// do something else
}
},
On test.php you could show errors using the code explained here: https://stackoverflow.com/a/21429652/6525724
And then on this page instead of alert('error') you could use alert(data).
Try this
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}

how to login from a rest api using angularJS and ionic

so i have this mobile app that uses ionic framework, and for the authentification, i want to get the emails stored in the database using a rest api, my problem is i dont know how to code the function that will verify the informations entered by the user, i'm pretty sure ive done a chaotic login function down here... so here's how services.js look like
.factory('UserService', function($q) {
var users={};
var url="http://localhost/test/index2.php";
if(url.indexOf("localhost") >= 0)
{
jQuery.ajax({
contentType: "application/jsonp; charset=utf-8",
type: "GET",
dataType: "jsonp",
crossDomain: true,
url: url,
success: function(data, status, jqXHR){
users=(data);
},
error: function (jqXHR, status) {
// gestion d'erreur
alert(status);
alert(jqXHR.status);
}
});
}else
{
jQuery.ajax({
contentType: "application/json; charset=utf-8",
type: "GET",
dataType: "json",
crossDomain: true,
url: url,
success: function(data, status, jqXHR){
users=(data);
},
error: function (jqXHR, status) {
// gestion d'erreur
alert(status);
alert(jqXHR.status);
}
});
}
return {
login: function (email,pwd) {
var deferred = $q.defer(),
results = users.filter(function (element) {
return (email === element.email and pwd === element.pwd);
});
deferred.resolve(results);
return deferred.promise;
}
}
});
and here's my api
<?php
$mysqli = new mysqli("localhost", "root", "imane", "annuaire");
$r = $mysqli->query("SELECT * FROM employee");
if(mysqli_num_rows($r) > 0){
$result = array();
while($row = mysqli_fetch_assoc($r))
{
$result[] = $row;
}
if($_GET['callback']) {
$json = json_encode($result);
header("Content-type: application/javascript");
print $_GET['callback'] . '('.$json.')';
}
else
{
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
}
}
?>
thank you!

jQuery ajax call to php giving a 404 not found: what am I missing?

I have a jQuery Ajax call to php giving a 404 not found. What am I missing?
Requesting the page (non Ajax) from a browser gives me the json data back.
The jQuery calling the php by Ajax:
$.post({
url:'/jqgrid/nwproducts.php',
success:function(data){
$('#auto').autocomplete({source:data.ProductName});
}
});
The php code:
<?php
header("Content-Type: application/json");
header("HTTP/1.1 200 OK");
$arrayProduct = array();
$mysqli = new mysqli('localhost','login','passwd','northwind');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$resultAll = $mysqli->query('select ProductName from products');
if (!$resultAll)
{
echo "error\n";
} else {
while ($obj = $resultAll->fetch_object()) {
array_push($arrayProduct,$obj);
}
echo json_encode($arrayProduct);
}
?>
I am getting the following error in firebug:
http://localhost/jqgrid/%5Bobject%20Object%5D 404 Not Found
Put out url and success param off the object.
$.post('/jqgrid/nwproducts.php', function(data) {
$('#auto').autocomplete({source:data.ProductName});
});
http://api.jquery.com/jQuery.post/
Hi Pranay I used your code modified a little bit but it worked
(function IsExists(pagePath) {
$.ajax({
type: "POST",
url: pagePath,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success:function(result) {
$('#auto').autocomplete({source:result});
}
});
})('/jqgrid/nwproductsonly.php');
If possible, check whether the page is accessible and whether you provided the correct page URL.
One more solution: if possible make use of an Ajax function that gives you more flexibility.
function IsExists(pagePath, dataString) {
//alert(pagePath);
$.ajax({
type: "POST",
url: pagePath,
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success:
function(result) {
var flg = true;
if (result != null) {
flg = result.d;
if (flg == "True") {
alert('Success-true'); }
else {
alert('Success - false'); }
}
}
});
}

Categories