I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.
$(document).ready(function () {
$("#comments_form").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'process_in.php',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
var x = jQuery.parseJSON(result);
alert(x.f);
},
});
});
})
<?php
include ('connection.php');
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
}
function xssafe($d)
{
$x = filter_var($d, FILTER_SANITIZE_STRING);
return $x;
}
A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception.
Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.
$.ajax({
type: 'POST',
url: 'process_in.php',
dataType: 'JSON',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
console.log(result.f);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
You can learn how to debug the code and check your error logs
Now lets get to your code, there are many possible cases that you are not getting the value.
It could be your php code or it could be your jquery.
In php to check whether its returning a valid json hit the url in browser like this
http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo
As in your php code you haven't return any value so add an else part for the
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
} else {
echo json_encode(['error'=>'Invalid request']);
}
Related
My Codeigniter: (Do you think there is an error?)
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
My jQuery Code: (Do you think there is an error?)
$(".submit").on("click", function(){
var kuladi = $("#kullaniciadi").val();
var email = $("#email").val();
var sifre = $("#sifre").val();
var confirm = $("#sifreonay").val();
var hata = $("#hata").val();
var checkbox = $("#checkbox").is(":checked");
var link = "http://tantunisiparis:8080/main/anasayfa/KayitOl";
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
if (!kuladi || !email || !sifre) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Boş bırakılan alanlar var!");
}
else if (!pattern.test(email)) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Lütfen geçerli bir e-mail giriniz!");
}
else if (!checkbox) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Kullanıcı Sözleşmesini Kabul Etmediniz.");
}
else if (sifre != confirm) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Şifreler eşleşmiyor!");
}
else{
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
console.log(data.status);
alert("Success döndü");
},
error: function (data){
console.log(data.status);
alert("Error döndü");
}
});
}
});
Why I am having a problem like this?
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
You need to set HTTP status code. So in case of error call this code in the controller $this->output->set_status_header(500);.
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
$this->output->set_status_header(500); // or any other code
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
You can read more about output class in the docs http://www.codeigniter.com/userguide3/libraries/output.html
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
if(data.status == 'success'){
console.log(data.status);
alert("Success döndü");
}
if(data.status == 'error'){
console.log(data.status);
alert("Error döndü");
}
}
});
I thing, This code will work for you...
I want to write (register section) code that can check if email have been used in past or the login is empty.
The code is working fine, but my ajax code dont run at all.
I checked everything, path to php file is good, variables are good etc. Don't how to solve it.
Code:
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var self = $(this);
var $name = self.find('[type=name]');
var $email = self.find('[type=email]');
var $pass = self.find('[type=password]');
var emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailRegex.test($email.val())) {
createErrTult("Błąd! Email ma zły format!", $email)
error++;
}
//MY AJAX CODE
var email = $email.val();
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
}
});
if ($name.val().length > 1 && $name.val() != $name.attr('placeholder')) {
$name.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong name!', $name)
error++;
}
if ($pass.val().length > 1 && $pass.val() != $pass.attr('placeholder')) {
$pass.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong password!', $pass)
error++;
}
if (error != 0) return;
self.find('[type=submit]').attr('disabled', 'disabled');
self.children().fadeOut(300, function() {
$(this).remove()
})
$('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
.hide().delay(300).fadeIn();
// var formInput = self.serialize();
// $.post(self.attr('action'),formInput, function(data){}); // end post
});
php:
<?php
include ("config.php");
if($action == "emailcheck"){
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo json_encode($dodano);
}
?>
First, you should try adding error callback:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
This may alert you about some occured error.
Second, you can try to use json instead of plain text:
Client-side:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
dataType: 'json', // THIS ROW
type: 'POST',
success: function(odp) {
if (odp['result'] == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error)
{
alert(error);
}
});
Server-side:
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck") {
if(isset($_GET['email'])) {
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo (json_encode(array("result" => $dodano))); // THIS ROW
}
}
}
}
?>
before everything check you config.php file path .. In your case config.php should be in the same path with rejestracja.php and try this.. lets start with ajax
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
email: email
},
type: 'GET',
success: function(odp) {
if (odp == 1) {
alert('Email exists');
}else{
alert('Email dosen\'t exists');
}
}
});
then in php
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck"){
if(isset($_GET['email'])){
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo ($dodano);
}
}
}
?>
you should get alert with ('Email exists')
how to return URL built in php as json object to ajax to open it in the new tab?
so far all my attempts to do so were unsuccessful. Please help
here is my JS file
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
cache: false,
success: function (html) {
myWindow = window.open(encodeURIComponent(true),
"_blank");
myWindow.focus();
if (html == "true") {
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
and here is my PHP file
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/includes/sitewide-variables.php");
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// Check if all required fields are filled in
if (empty($_POST['name']) && empty($_POST['id'])) {
echo "Error: You must fill in all required fields.";
// If not, exit!
exit();
}
// If valid, store values in variables
$id = stripslashes($_POST['id']);
$name = stripslashes($_POST['name']);
if($name){
$query = 'SELECT * FROM files_paid WHERE parentpageID = :promoproductID';
$res = $db->prepare($query);
$res->execute(array(':promoproductID' => $id));
foreach ($res as $info);
if($info['promoCode'] == $_POST['name']){
$redirect_link = 'http://'.$info['promobuylinkID'].'.myid.pay.clickbank.net';
$todayis = date("l, F j, Y, g:i a") ;
$to = "My Email Address";
$subject = "Promotional Purchase";
$message = "$todayis [EST] \n
Promo Code: $name \n
";
// Send email
$sent = mail($to, $subject, $message);
if($sent) {
echo json_encode($redirect_link);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
}
}
?>
I am only getting true in the new window.
Thanks in advance
I have have found the problem.
First, I was missing dataType: "json", in ajax.
and after that I only had to return html to get to the point where I needed to get.
So the JS file now looks like this
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
dataType: "json",
cache: false,
success: function (html) {
if (html) {
window.open(decodeURIComponent(html),"_blank").focus();
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function () {
alert("Your Coupon Code is not valid");
}
});
return false;
});
});
All works just fine.
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"