I've been pulling my hair out to get this to work but no luck.
I have the below AJAX call;
$("#orderverify-form").submit(function(e) {
$('#loader').show();
e.preventDefault();
initiateCall();
});
function initiateCall() {
// Client side validation
if ($("#phone_number").val() == "") {
$('#loader').hide();
detError();
} else {
$.post("php/corder-verify.php", {
phone_number : $("#phone_number").val()
}, function(data) {
if (data.verification_code == 0) {
console.log(data.verification_code);
numberError();
} else {
console.log(data.verification_code);
showCodeForm(data.verification_code);
checkStatus();
}
}, "json");
}
}
My responses received from PHP are below;
Query successfull
// return verification code as JSON
$json = array();
$json["verification_code"] = $code;
header('Content-type: application/json');
echo(json_encode($json));
exit;
Query not successful
else {
// return verification code as JSON
$json = array();
$json["verification_code"] = 0;
header('Content-type: application/json');
echo(json_encode($json));
exit;
}
Code is just a rand number I'm generating. For failure I just set it to 0.
I never seem to be able to catch the error.
Only the else part of my AJAX if..else statement work :(
Help please.
Related
I have created a .post() request
function validateLogin()
{
var username = $("#username").val();
var password= $("#password").val();
var details = {"name": username, "password": password};
console.log(details);
console.log(JSON.stringify(details));
$.post("getthedb.php", JSON.stringify(details), function(response)
{
if(response.code==0)
{
alert("Response: " + response.message);
$("#myDiv").innerHTML = response.message;
}
else
{
$("#myDiv").innerHTML = response.message;
}
}, "application/json");
}
getthedb.php
<?php
header('Content-type: application/json');
$jsonobj = file_get_contents("php://input");
$detail= json_decode($jsonobj);
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
{
$response1['code']=0;
$response1['message']="Success";
}
else
{
$response1['code']=1;
$response1['message']="No Success";
}
$response = json_encode($response1);
echo $response;
?>
This is not giving back any result,'console.log(details)' and
'console.log(JSON.stringify(details))' produces the JSON object. how to debug this???
where am i lagging here.??
If you code doesn't provide some error i assume that your if down there isn't called and $response1 is empty. So no response to read.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
{
$response1['code']=0;
$response1['message']="Success";
}
else ???
$response = json_encode($response1); // Response1 is empty
echo $response;
missing ) in if loop.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
should be
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
$response1 array not declared.
You haven't written else case
I cannot get this script work. I try to warn if login that user entered is available. But I cannot manage this script to work:
$( "#myRegForm" ).submit(function( event ) {
var errors = false;
var userAvi = true;
var loginInput = $('#login').val();
if( loginInput == ""){
$("#errorArea").text('LOGIN CANNOT BE EMPTY!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if(loginInput.length < 5 ){
$("#errorArea").text('LOGIN MUST BE AT LEAST 5 CHARACTERS!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if (loginInput.length >=5) {
$.post('checkLogin.php', {login2: loginInput}, function(result) {
if(result == "0") {
alert("this");
}
else {
alert("that");
}
});
}
if (errors==true) {
return false;
}
});
Everything works fine until loginInput.length >=5 else block. So I assume there is a problem with getting answer from PHP file, but I cannot handle it, though I tried many different ways. Here is checkLogin.php's file (note that jQuery script and PHP file are in the same folder):
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}
else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo "0"; // for you to use if(if(result == "0") you should send a string
} else {
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
?>
You're literally sending the string 'loginInput'.
change
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) {
to
$.post('checkLogin.php', {login2: loginInput}, function(result) {
Edit
I would just comment out everything except the following for now and see if that at least works
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) { // put loginInput back in quotes
alert('#'+result+'#'); // # to check for whitespace
});
I have a e-commerce system. And i'm adding products to my cart like on screenshot
When i click to add to cart button. I'm showing a shopping cart notification which is bootstrap popover. The main problem is when i decide to another product i recived same notification.
I'm writing "Product A is added." When i do that in every different product adding it writes Product A is added. Adding i correct but notification is wrong.
Here is my jQuery Code...
$('.quick-add-cart').click(function(){ //Sepete Ekleme İşlemi yapıyoruz.
$('#cart-popover').attr('data-content','');
productID = $(this).parents('.productbit').attr('id');
$.ajax({
type: "POST",
url: "ajax/add_to_cart.php",
dataType: 'json',
data: {
productID : productID
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Bağlantı sağlanamadı.\n Lütfen internet bağlantınızı kontrol ediniz.');
} else if (jqXHR.status == 404) {
alert('Sayfa bulunamadı. [404]');
} else if (jqXHR.status == 500) {
alert('Sunucu Hatası [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.'+ jqXHR.responseText);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax istemi durduruldu.');
} else {
alert('Beklenmeyen Hata.\n' + jqXHR.responseText);
}
},
success: function (data) {
if (data.insert_count > 0) {
cart_old_count = $('#cart_count').text();
cart_new_count = parseInt(cart_old_count,10) + data.insert_count;
$('#cart_count').text(cart_new_count);
}
$('#cart-popover').attr('data-content',data.queryresult).popover('show');
setTimeout(function() {
$('#cart-popover').popover('hide');
}, 5000);
}
});
});
And here is my add_to_cart.php
require_once '../includes/class/class.cart.php';
include_once '../locale.php';
session_start();
$C = new Cart();
//Sepete Ürün Ekliyoruz
if (isset($_POST['productID'])){
if (!isset($_SESSION['userid'])) {
$jsonData['queryresult'] = "Sepete Ekleme Yapabilmek için Bayi Girişi Yapmalısınız !";
} else {
$productid = $_POST['productID'];
$product = $C->get_product_fields('product', $productid);
$jsonData['update_count'] = 0;
$jsonData['insert_count'] = 0;
$cart_error = FALSE;
if ($C->is_in_cart($productid)) {
if ($C->update_cart($productid))
$jsonData['update_count'] += 1;
else {
$jsonData['queryresult'] = $C->cart_errors($productid);
$cart_error = TRUE;
}
} else {
if ($C->add_to_cart($productid))
$jsonData['insert_count'] += 1;
else {
$jsonData['queryresult'] = $C->cart_errors($productid);
$cart_error = TRUE;
}
}
if ($cart_error === FALSE) {
if ($jsonData['insert_count'] == 1){
$jsonData['queryresult'] = "Bir paket ".$product." eklendi.";
}
if ($jsonData['update_count'] == 1){
$jsonData['queryresult'] = "Bir paket daha ".$product." eklendi.";
}
if ($jsonData['insert_count'] == 0 && $jsonData['update_count'] == 0){
$jsonData['queryresult'] = "Ürünü sepete ekleme sırasında hata oldu.";
}
}
}
header('Content-type: application/json');
echo json_encode($jsonData);
}
related issue: Twitter bootstrap js popover content doesn't update when data-content attribute is updated
Two changes are required to solve your problem:
Instead of .attr('data-content', data.queryresult), you should use .data('content', data.queryresult)
You need to use .popover('destroy') before updating the content, this prevents popover from getting lost with async processing.
Here is a sample code, I have used setTimeout to simulate the Ajax call:
function displayPopover(msg) {
$('#cart-popover').popover('destroy');
$('#cart-popover').data('content',msg).popover('show');
setTimeout(function() {
$('#cart-popover').popover('hide');
}, 5000);
}
// add first product to cart
setTimeout(function() { displayPopover('product 1') }, 2000);
// add second product to cart
setTimeout(function() { displayPopover('product 2') }, 4000);
You can see it in action here: http://jsbin.com/UXAxEBE/1/
tip: when you have such type of error where you don't know whether the problem is at php or javascript side, you should try to console.log(data.queryresult) in your javascript to validate that php returns the correct content and that your problem is at client side.
I am trying to send some data using php and jquery ajax using json datatype method.
Here is my code:
$("#username").on("keyup change keypress", function () {
var username = $("#username").val();
$.ajax
({
type: "POST", // method send from ajax to server
url: window.location.protocol + '//' + window.location.host + '/' + "admin/admins/user_exists",
data: {
username: username
},// Specifies data to be sent to the server
cache: false, // A Boolean value indicating whether the browser should cache the requested pages. Default is true
contentType: "application/json",
dataType: 'json', // The data type expected of the server response.
success: function (response_data_from_server) {
for (var key in response_data_from_server)
var result = response_data_from_server[key] + ""; // JSON parser
if (result == 'true') {
console.log("---------------- in true");
$("#username_alert").text("ERROR");
$('#username_alert').removeClass("alert-success");
$("#username_alert").css("visibility", "visible");
}
else {
if (result == 'false') {
console.log("---------------- in false");
$("#username_alert").text("NO ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').addClass("alert-success");
}
else {
if (result == 'empty') {
console.log("---------------- in empty");
$("#username_alert").text("ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').removeClass("alert-success");
}
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and it always goes to an error function. The error that I receive is the following:
parsererror SyntaxError: Unexpected token {}
My url location is correct and is indeed returning the correct json format. Here is my php code:
public function user_exists()
{
$username = $this->input->post("username");
$is_exists = "false";
$this->load->database();
if ($username != "")
{
$rows = $this->db->query("
SELECT * FROM `admins` WHERE `username` = '" . $username . "'
")->num_rows();
if ($rows > 0)
{
$is_exists = "true";
}
else
{
$is_exists = "false";
}
}
else
{
$is_exists = "empty";
}
$arr = array ('result' => $is_exists );
$response = json_encode($arr);
echo $response;
}
I've debugged it million times, the firebug sees the response as correct and expected json, however the client side seems to refuse to get it as a json respone, for what I believe.
Will appreciate any help!
...
header('Content-type: application/json');
echo $response;
Maybe you could use "header('Content-type: application/json');" before "echo"
I am getting a NaN error in my ajax callback function and can only think it has to do with an array in PHP. I have been trying to find ways to correct it but have come up against a brick wall.
What is supposed to happen is that PHP queries the database and if there are no results send a response to ajax and issue the error message. However, all I am getting is NaN. The error stems from the success code below.
I would be grateful if someone could point out my error.
PHP code:
$duplicates = array();
foreach ($boxnumber as $val) {
if ($val != "") {
mysql_select_db($database_logistor, $logistor);
$sql = "SELECT custref FROM boxes WHERE custref='$val' and status = 'In'";
$qry = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($qry) < 1) {
$duplicates[] = '[ ' . $val . ' ]';
$flag = 1;
} else {
$duplicates[] = $val;
}
}
}
//response array with status code and message
$response_array = array();
if (!empty($duplicates)) {
if ($flag == 1) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'ERROR: ' . implode(',', $duplicates) . ' needs to be in the database to be retrived.';
}
//if no errors
} else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'All items retrieved successfully';
$response_array['info'] = ' You retrieved a total of: ' . $boxcount . ' boxes';
}
//send the response back
echo json_encode($response_array);
Relevant ajax:
$("#brtv-result").html(msg.message+msg.info);
jQuery code:
$(function() {
$("#BRV_brtrv").submit(function() {
var send = $(this).serialize();
$.ajax({
type: "POST",
url: "boxrtrv.php",
cache: false,
data: send,
dataType: "json",
success: function(msg) {
if( msg.status === 'error') {
$("#brtv-result").fadeIn(1000).delay(1000).fadeOut(1000);
$("#brtv-result").removeClass('error');
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message);
}
else {
$("#brtv-result").fadeIn(2000).delay(2000).fadeOut(2000);
$("#brtv-result").removeClass('error');
$("#brtv-result").addClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message+msg.info);
//location.reload(true);
//$('#brtv-result').addClass("result_msg").html("You have successfully retrieved: "+data.boxnumber).show(1000).delay(4000).fadeOut(4000);
$("#BRV-brtrv-slider").val(0).slider("refresh");
$("input[type='radio']").attr("checked",false).checkboxradio("refresh");
var myselect = $("select#BRV-brtrv-department");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
var myselect = $("select#BRV-brtrv-address");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
}
},
error:function(){
$("#brtv-result").show();
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass('error');
$("#brtv-result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
NaN (pronounced nan, rhymes with man) only happens when you try to do an operation which requires a number operand. For example, when you try to Number('man') you'll get this error.
What you return from your PHP file, is simply an array which contains simply data. So, the problem is in your JavaScript. You have to send more parts of your JavaScript, so that we can see it thoroughly.
However, I recommend that you use Firebug and set a breakpint at the correct place (the callback function start), and check the stack trace of the calls to diagnose the problem.