AJAX - JSON Error - javascript

When I am trying to receive data from the server side, error I am getting:
06-30 11:23:57.119: I/chromium(7486): [INFO:CONSOLE(50)] "{"readyState":4,"responseText":"","status":404,"statusText":"Not Found"}", source: file:///android_asset/www/js/index.js (50)
JS file:
$j.ajax({
type: 'POST',
url: 'http://www.myrandomurl.com/SupportData/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
//alert(JSON.stringify(response));
//console.log(JSON.stringify(response));
if (response.success) {
myApp.alert("you're logged in");
//window.localStorage["email"] = e;
//window.localStorage["password"] = p;
console.log(window.localStorage["email"]);
//localStorage.removeItem('email');
mainView.router.loadPage('main.html');
} else {
myApp.alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
//myApp.alert('Could not connect to the database' + error);
console.log(JSON.stringify(error));
//window.location = "index.html";
}
});
PHP side:
$sql = "SELECT login_id, email_id, password FROM login WHERE email_id='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$row = mysql_fetch_array($result);
if($num_rows == 1) {
$response['success'] = true;
}else {
$response['success'] = false;
}
echo json_encode($response);

Related

If and else condition inside success in ajax

As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement" and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you
<script>
function renderAttendees(id)
{
///$("#attendeesContent").empty();
var dataString = { "id": id };
$.ajax({
type: 'POST',
url: server+'webservice/crm/viewAttendeesDetails',
data: dataString,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: true,
success: function(data)
{
if($.trim(data) === 'error')
{
alert('yes');
}
else
{
alert('no');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);
}
</script>
//My Controller Code
public function viewAttendeesDetails()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$data = array();
$id = $_POST['id'];
$AttendeesDetails = $this->model->GetAttendeesDetail($id);
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
}
echo json_encode($data);
exit;
}
?>
//My Model Code
db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");
$stmt->bindParam(":AttendId", $id);
$stmt->execute();
return $stmt;
}
catch (Exception $e)
{
return $e->getMessage();
return $stmt;
}
return;
}
?>
//Here is the result of console.log(data);
Object
email:"kyle#localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"
I would return from your controller something like
{status: 'success', data: myArrayWithFoundData}
so when you receive the ajax response you could do a json_decode, and check the status.
So in you controller you would have
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
$rsp_data = {status: 'success', data: $data};
}else{
$rsp_data = {status: 'error', data: null};
}
echo json_encode($resp_data);
Something like that, so in the ajax response you would do a
var a = JSON.parse(data);
and check the a.status for error

jQuery ajax call not triggering success function on Safari 9.1

In a project I have a particular ajax call that works fine on PC Chrome/Firefox, but on Safari 9.1 it fails to trigger the success function.
The ajax call:
$('#new_file_form').submit(function(e) {
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
url: '/includes/ajax/file-manager.php',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
success: function(result) {
JSON.parse(result);
alert(result);
if (result == true) {
$('#new_file_form').reset;
$('#new_file_modal').modal('hide');
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-info-sign blue"></i>File successfully saved.',
callback: function() {
location.reload();
}
});
} else if (result == false) {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>File not saved.',
callback: function() {
location.reload();
}
});
} else {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>Whoa! That escalated quickly..',
callback: function() {
location.reload();
}
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
This doesn't throw any errors. The file is uploaded and the data inserted into the database, it's just the success function that sits there and seems to be laughing at me.
Based on the returned error in Safari it seems useful to post the file-manager.php code:
if(!empty($_POST['file_name']) && !empty($_POST['file_type']) && !empty($_POST['file_user'])) { // && !empty($_FILES['file'])
$ownerid = $mysqli->real_escape_string($_POST['file_user']);
$ownertype = 1;
$name = $mysqli->real_escape_string($_POST['file_name']);
$visible = $mysqli->real_escape_string($_POST['visible']);
$filetype = $mysqli->real_escape_string($_POST['file_type']);
$ownerid = filter_var($ownerid, FILTER_SANITIZE_NUMBER_INT);
$visible = filter_var($visible, FILTER_SANITIZE_NUMBER_INT);
$filetype = filter_var($filetype, FILTER_SANITIZE_NUMBER_INT);
$cdate = date('Y-m-d H:i:s');
$edate = $cdate;
$u_file_name = $_FILES['file']['name'];
$u_tmp_file = $_FILES['file']['tmp_name'];
$u_file_type = $_FILES['file']['type'];
$u_file_error = $_FILES['file']['error'];
$u_file_content = file_get_contents($_FILES['file']['tmp_name']);
$upload_result = '';
if($u_file_error == 'UPLOAD_ERROR_OK') {
if($u_file_name == '') {
$upload_result = false;
} else {
$sql = "SELECT path FROM filetypes WHERE id = '$filetype'";
$result = $mysqli->query($sql);
$record = $result->fetch_object();
$file_type_path = $record->path;
$extension = end(explode(".", $u_file_name));
if($ownertype == 1) {
$s_file_name = preg_replace("![^a-z0-9]+!i", "-", $name).'-'.date('Y-m-d_H-i').'.'.$extension;
$s_file_dest = LOCAL_BASE_PATH.'/uploads/'.$ownerid.'/'.$file_type_path;
$s_file_location = $s_file_dest.'/'.$s_file_name;
$s_file_path = '/uploads/'.$ownerid.'/'.$file_type_path.$s_file_name;
}
if(!file_exists($s_file_dest)) {
mkdir($s_file_dest, 0755, true);
}
move_uploaded_file($u_tmp_file, $s_file_location);
$sql = "INSERT INTO files (ownertype, owner, type, visible, extension, name, path, cdate, edate) VALUES ('$ownertype', '$ownerid', '$filetype', '$visible', '$extension', '$s_file_name', '$s_file_path', '$cdate', '$edate')";
$result = $mysqli->query($sql);
$upload_result = true;
}
}
echo json_encode($upload_result);
exit();
}
When I alert the ajax result before parsing it, I get a PHP error:
Strict Standards: Only variables should be passed by reference...

ajax jquery always running Error;

Ajax jquery always running error function, althought success function run and i can get session value,i can't run window.location="profile.php";
$(document).ready(function(){
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
type: "POST",
url: "model/user.php",
data: {
user_log : username,
password : password
},
dataType: 'json',
error: function (xhr,textStatus,errorThrown) {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
},
success: function(json){
window.location="profile.php";
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
user.php
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
require_once(dirname(__FILE__).'/../model/connect.php');
?>
<?php
global $pdo;
if(isset($_POST['user_log'])) {
// username and password sent from Form
$username=$_POST['user_log'];
$password=$_POST['password'];
$qr= "SELECT * FROM user where username='$username' AND password='$password'" ;
$stmt= $pdo->query($qr);
$row= $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$_SESSION['id']=$row['id'];
$_SESSION['name_mem']=$row['username'];
$_SESSION['level_mem']=$row['level'];
}
header("location:../../../../index.php");
}
?>
Remove this line :
header("location:../../../../index.php");
If above doesn't work, omit this from ajax properties :
dataType: 'json',
you can use ajax like this,
<script>
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value : you can load progress bar in here
}, false);
return xhr;
},
type: "POST",
url: "model/user.php",
data: {'username' : username, 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.location="profile.php";
}else{
$("#error").html("<span style='color:#cc0000'>Error:</span> "+msg.massage);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error: this statement will execute when fail ajax
}
});
});
</script>
server side code like this(inside user.php),
$username=$_POST['username'];
$password=$_POST['password'];
...........
//$status="fail" or "done"
//success must be always success
//$massage= "password or username not match"
$respond=array("success"=>"success","status"=>$status,"massage"=>$massage);
echo json_encode($respond);
exit;
I hope you useful this.

Add value to database with ajax and php

I want to add value 'Nova parcela' to database in table zemljiste so I write first ajax code:
<script>
var nova_parcela = 'Nova parcela';
$("#dodaj").click(function() {
$.ajax({
url: "insert.php",
type: "POST",
async: true,
data: { name:nova_parcela}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
</script>
after that I write php code: INSERT.php is:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (!$_POST['name']!='Nova parcela') {
echo "<p>Popunite sva polja</p>";
exit;
} else {
try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO zemljiste (naziv) VALUES (:name)");
$STH->bindParam(':name', $_POST['name']);
$STH->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>".$_POST['ajdi'];
}
}
$DBH = null;
but nothing happend , what can be a problem here?
try change that
if (!$_POST['name']!='Nova parcela') {
to
if (!isset($_POST['name'])) {
EDIT:
if (isset($_POST['name'])) {
try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO zemljiste (naziv) VALUES (:name)");
$STH->bindParam(':name', $_POST['name']);
$STH->execute();
$datas['msg']= "success" ;
} catch (PDOException $e) {
echo $e->getMessage();
}
$DBH = null;
echo json_encode($datas);
}
and your script:
<script>
var nova_parcela = 'Nova parcela';
$("#dodaj").click(function() {
$.ajax({
url: "insert.php",
type: "POST",
async: true,
data: { name:nova_parcela}, //your form data to post goes here as a json object
dataType: "json",
success: function(data) {
if (data.msg == 'success'){
$('#output').html("<p>Data submitted successfully</p>"+nova_parcela);
drawVisualization();
}
else{
$('#output').html("<p>Popunite sva polja</p>");
}
}
});
});
</script>

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources