JQuery AJAX is unable to execute success function - javascript

What I'm using: JQuery, mysql_crud.php class
I have a class for donor, inside the class I created a function to add a donor into the database. Any result made by the function will return an array.
donor-class.php
public function addDonor($foo, $bar, $soap, ){
.
.
$message = array('message' => 'Message for user here');
return $message;
}
The class is then executed by another php file which will return JSON data
add-donor-function.php
$res = $donor->addDonor($foo, $bar, $soap);
header('Content-Type: application/json');
echo json_encode($res);
This PHP file will return JSON data
{
"message" : "Message for user here"
}
I also have a javascript file to run an ajax function
js_add_donor.js
function addDonor() {
var name = $('#name').val();
var ic_no = $('#ic_no').val();
var gender = $('#gender').find(":selected").val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var b_type = $('#b_type').find(":selected").val();
var dob = $('#don').val();
var address = $('#address').val();
var district = $('#district').find(":selected").val();
$.ajax({
url: "/firstblood/php/function/donor-management/add-donor-function.php",
type: "POST",
data: {name:name, ic_no:ic_no, gender:gender, email:email, mobile:mobile, b_type:b_type, dob:dob, address:address, district:district},
dataType: 'json',
success: function(result, status){
// Below codes won't run
alert('heloo');
alert(status);
$('#response').text(success.message);
}, error: function(xhr, status, error) {
// Below codes run
alert(xhr.status);
alert(status);
alert(error);
}
});
return false;
}
addDonor() is used for a button when clicked.
When the code is executed, the window alerts "200", "parseerror", and "SyntaxError: Unexpected token < in JSON at position 0"
Where am i wrong here ?

Related

if use ajax call for contact form submitting, header(location:/path) not working

The issue is if try to ajax call for submitting my contact form. then header("location: /path); starts not working.
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
// header("location: /contact/thankyou.html");
}
} else {
echo "Invalid captcha! Please enter again. ";
}
And yes, because header redirect is not working. I comment it out. And tried to redirect page inside ajax call like below.
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function(){
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data){
response.html(data).fadeIn();
window.location.href ="/contact/thankyou.html";
},
error: function(e){
console.log(e)
}
});
});
});
But this time, it's only redirecting inside the .status div! like in the image Normally I am displaying a error message in that div...
Hey This is wrong practice if you are using ajax req then php not able to redirect to your destination all you need to redirect in ajax success response simple us
$data = array();
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
$data['status'] = 1; // for true
$data['message'] = "your success message"; // for true
}
}
else {
$data['status'] = 0; // for false
$data['message'] = "your error message"; // for false
}
//define content type json if you never echo like echo 'ss' then no need to this
header('Content-Type: application/json');
echo json_encode($data);exit;
and get response in ajax request dataType Json to access json array obj
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'json',
data: form.serialize(),
beforeSend: function() {
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data) {
if (data.status == 1) {
response.html(data.message).fadeIn();
window.location.href = "/contact/thankyou.html";
}
else{
// for error
response.html(data.message).fadeIn();
}
},
error: function(e) {
console.log(e)
}
});
});
});
You have to send header as Base64 string then decode it in the service / Backend.

post in my js wont work

JS : Fixed by godot!
/* Data Delete Starts Here */
$(".delete-file").click(function()
{
var name = $(this).attr("name");
var file_id = $(this).attr("id");
var active_user = document.getElementById("username").value;
if(confirm('Sure to Delete ' +name+ '?'))
{
$.ajax({
url: 'suf-delete.php',
type: 'post',
async: false,
data: {'file_id':file_id ,'active_user':active_user},
success: function(response){
$("#file_table"+file_id).fadeOut('slow');
},
error: function(error){
console.log(error.responseText);
//you could debug your php code if some error raises
}
});
}
return false;
});
/* Data Delete Ends Here */
PHP: Working Fine (suf-delete.php)
elseif($_POST['file_id'] && $_POST['active_user'])
{
$file_id = $_POST['file_id'];
$active_user = $_POST['active_user'];
$crud->filesDelete($file_id,$active_user);
}
Im now having a problem with my class crud.
I think Its just my query. Im trying to make activity log, delete, select and unlink Item using my code provided below.
Please check this:
Class Crud
public function filesDelete($file_id,$active_user)
{
$stmtFiles = $this->conn->prepare('SELECT * FROM tbl_files WHERE file_id=:file_id');
$stmtFiles->execute(array(":file_id"=>$file_id));
$unFile=$stmtFiles->fetch(PDO::FETCH_ASSOC);
$userStmt = $this->conn->prepare('SELECT * FROM tbl_login WHERE username=:username');
$userStmt->execute(array(":username"=>$active_user));
$fetch = $userStmt->fetch(PDO::FETCH_ASSOC);
$activity = "Deleted the file ".$unFile['file_name'];
if($fetch['access_type']=="Design2K18ADMIN") {
$type = "Administrator";
}
elseif ($fetch['access_type']=="Design2K18MANAGER") {
$type = "Manager";
}
elseif ($fetch['access_type']=="Design2K18MODERATOR") {
$type = "Moderator";
}
elseif ($fetch['access_type']=="Design2K18SIMPLE") {
$type = "Simple";
}
$actLog = $this->conn->prepare("INSERT INTO activity_log(username, activity, type) VALUES(:username, :activity, :type)");
$actLog->execute(array(":username"=>$active_user, ":activity"=>$activity, ":type"=>$type));
$stmtSelFol = $this->conn->prepare('SELECT * FROM tbl_section WHERE sec_id=:sec_id');
$stmtSelFol->execute(array(":sec_id"=>$unFile['sec_id']));
$unFol=$stmtSelFol->fetch(PDO::FETCH_ASSOC);
unlink("../Files/".$unFol['sec_folder']."/".$unFile['file_name']);
$stmtDelFile = $this->conn->prepare('DELETE FROM tbl_files WHERE file_id=:file_id');
$stmtDelFile->execute(array(":file_id"=>$file_id));
return true;
}
I have confirm that My js and php works fine by saving the logs in error.php
I save the value of file_id and active_user in my error.txt file.
9Daren appears which is the value(id) of Item and the current session user is Daren.
Please help me check my public function why It does not do anything.
I would use ajax:
/* Data Delete Starts Here */
$(".delete-file").click(function()
{
var name = $(this).attr("name");
var file_id = $(this).attr("id");
var active_user = document.getElementById("username").value;
if(confirm('Sure to Delete ' +name+ '?'))
{
$.ajax({
url: 'suf-delete.php',
type: 'post',
async: false,
data: {'file_id':file_id ,'active_user':active_user},
success: function(response){
$("#file_table"+file_id).fadeOut('slow');
},
error: function(error){
console.log(error.responseText);
//you could debug your php code if some error raises
}
});
}
return false;
});
/* Data Delete Ends Here */

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

JqueryAjax and php logic

Hey guys im with a problem getting a value from php. I know we have a lot of problems with this kind of issues, but i need help.
This is my javascript
$( document ).ready(function() {
$(".loading_bg").hide();
});
$( document ).ajaxStart(function() {
$(".loading_bg").fadeIn("slow");
});
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
and this is my php
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_POST['function'])) {
$user = $_POST['username'];
$password = $_POST['password'];
echo login::validate_user($user, $password);
}
class login {
static function validate_user($username, $password) {
//Call a new default connection
$db = db::connect();
//Prepare our sql
$stmt = $db->prepare("SELECT * FROM Accounts WHERE username = :username AND password = :password");
//Bind our values to the SQL statement
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->bindValue(':password', $password, PDO::PARAM_STR);
$stmt->execute();
//Get number of affected rows
$results = $stmt->rowCount();
//If to check if we can find any row with username and password
if($results === 1) {
//return json_encode("valid account");
} else {
return json_encode($username);
}
}
}
?>
When i do the request im getting a undifned error from my var, i dont know how to fix it, can someone help me, if possible.
I think its something with my $_POST.. because if run the php with login::validate_user("teste","teste); i can get the json result..
Everything else is fine, you are not passing data correctly to ajax call. You are making query string but you have to pass JSON object if you want to capture it in $_POST in php and can append to url if you want to capture in $_GET array. I have corrected your function in both ways below:
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = { 'function': 'validate_user', 'username': username, 'password': password }
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
When you want to capture data in $_GET at server side
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php?' + datastring,
data: {},
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
Here is PHP Code
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_GET['function'])) {
$user = $_GET['username'];
$password = $_GET['password'];
echo login::validate_user($user, $password);
}
.... // Remaining Class will come here
Im sorry to bother all of you, the real problem its my form input feilds.. i forgot to set a class... Thank you all, and once again, im sorry to make you lose time with such a silly problem.

How to show alert when error comes from the PHP as response to ajax request in following case?

The jQuery AJAX function is as follows :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
The PHP code is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg;
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data = $objUserLogin->GetResponse();
echo json_encode($data);
die;
}
break;
Now I'm able to print the success when the response comes without any error but what about showing the alert message when some error happens. How to achieve it? What change needs to make to the above code? Please help me.
Use below condition in success:
success: function(result, success) {
if($.inArray( "error_message", result)) {
alert("Error message");
} else {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
}
on php file if u found data acc to ur parameter
than it ok if there is no data acc to ur parameter than this time u can call its an error so in thsi case echo "error";
and on ajax page check for result if its value is error then do what else u want
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}

Categories

Resources