I have added an ajax call on the blur of input and click on submit button to verify the email exist or not.
Code is simple to just check the existing data and return true false in response.
On local it is working totally fine but on client's server the ajax is not responding as expected. The response status is 200 but nothing in the preview of response on the console of the browser. For more clarity adding the picture.
Ajax code:
jQuery.ajax({
url : "{{ path('sales_account_email_exist') }}",
type : "POST",
cache : false,
data : {email:email_val,user_id:$("#user-id").val()},
success : function(data){
$(".loader").hide();
var obj = $.parseJSON(data);
if(obj===false)
{
$("#duplicate_email_exist").css("display","inline-block");
errorMessage = '<i class="warning sign icon"></i>' + email_val + ' : Email already exists in the system.';
$("#duplicate_email_exist").html(errorMessage);
email_exist_valid = false;
}
else
{
$("#duplicate_email_exist").css("display","none");
$("#duplicate_email_exist").html("");
email_exist_valid = true;
}
}
})
Ajax backend code:
/**
* #Route("/exist-email", name="sales_account_email_exist",methods={"GET","POST"})
*/
public function emailExist(Request $request): Response
{
$email = $request->get('email');
$user_id = $request->get('user_id');
if (isset($email) && !empty($email)) {
if (isset($user_id) && !empty($user_id)) {
$query = $this->em->createQueryBuilder()
->select('u.id', 'u.email')
->from('App\Entity\User', 'u')
->andWhere('u.email =\'' . str_replace("'", '', $email) . '\'')
->andWhere('u.id !=' . $user_id)
->getQuery();
} else {
$query = $this->em->createQueryBuilder()
->select('u.id', 'u.email')
->from('App\Entity\User', 'u')
->where('u.email = :email')
->setParameter('email', $email)
->getQuery();
}
$email_exist = $query->getArrayResult();
if (!empty($email_exist)) {
return new response('false');
} else {
return new response('true');
}
}
return new response('true');
}
jQuery.ajax({
url : "{{ path('sales_account_email_exist') }}",
type : "POST",
cache : false,
data : {email:email_val,user_id:$("#user-id").val()},
success : function(data){
$(".loader").hide();
var obj = $.parseJSON(data);
if(obj===false)
{
$("#duplicate_email_exist").css("display","inline-block");
errorMessage = '<i class="warning sign icon"></i>' + email_val + ' : Email already exists in the system.';
$("#duplicate_email_exist").html(errorMessage);
email_exist_valid = false;
}
else
{
$("#duplicate_email_exist").css("display","none");
$("#duplicate_email_exist").html("");
email_exist_valid = true;
}
},
// add this
error: function (request, status, error) {
alert(request.responseText); // <-- your code will be here
}
})
Check logs
Add error: statement after success:, probably this will help to find problem.
Related
I'm working on a project where I have some jQuery code that is supposed to check if a certain row in the database exists. If the row does exist, The code within the success stage gets executed. But the problem I have with this script is when the 'checkdb' function gets executed the code within success happens even though the row doesn't exist in the database. What is causing this?
jQuery code
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
The jQuery above gets executed every minute, To check if the row is present.
The PHP code below is supposed to check if the row in the database exists. If it does, it should return a response which then ends up in the succeeding stage in jQUery. If it does not already exist, Do something else
PHP code
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing');
}
}
Why is it executing the succeeding stage even though the row does not already exist? Thanks in advance
response('content', 200, $headers) and `json()` helper also takes three param `json($data, status, $headers)`
methods take three parameters replace the content of the else
like
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing',404);
}
}
In jQuery, success block gets executed when response status code is 200. If you send status code as 404 which is in else block when DB is not exist, then error block will get executed instead of success. Laravel by default will send 200 as status code for AJAX requests in response.
Add dataType:"JSON"
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
datatype:'JSON',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
I have a script running and working, however the insert into members part don't work:
function register_member($username,$name,$email,$password) {
$time = time();
$ip = get_ip();
db()->query("INSERT INTO members (full_name,username,email,password,ip_address,last_active,date_created,banned,active)VALUES(?,?,?,?,?,?,?,?,?)",
$name,$username,$email,$password, $ip, $time, $time,0,1);
//login user
login_user($username, $pass, false);
if (config('auto-follow', '')) {
$users = explode(',', config('auto-follow'));
foreach($users as $user){
$user = get_user($user);
if ($user) {
follow($user['id']);
}
}
}
return true;
}
It seems for me that it can't read the db()->query ("INSERT INTO part. When I remove that query, the signup script can complete reading the function, but if I leave it in, it returns a 500 internal error. Any ideas?
Finally got the php.ini to change, and it is in the js script the error is happening. On this line here: var json = jQuery.parseJSON(result);
$(document).on("submit", "#signup-form", function() {
$(".loader-container").fadeIn();
$(this).ajaxSubmit({
url : baseUrl + 'signup',
success : function(result) {
var json = jQuery.parseJSON(result);
if (json.status == 1) {
//we can redirect to the next destination
window.location.href = json.url;
notify(json.message, 'success');
} else {
notify(json.message, 'error');
$(".loader-container").fadeOut();
}
}
})
return false;
});
I am making a cart system using PHP and AJAX. Everything works pretty fine, except for the updating part. When the user clicks outside of the number form, the subtotal will update automatically. I used AJAX for this, but doesn't work. I tested this with the search, everything was fine.
AJAX function:
function initXML() { //Adaptation for old browsers
var _xmlhttp;
if (window.XMLHttpRequest) {
_xmlhttp = new XMLHttpRequest();
} else {
_xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return _xmlhttp;
}
function ajaxFormValidate(_config) {
/*Structure
type: 'GET' or 'POST',
url: 'request URL' Default: location.href,
method: true or false (optional). False for non-async, true for async,
sendItem: file or data to be sent,
success: a callback function when the request is complete
error: a fallback function when the request is failed
*/
if (!_config.type) {
_config.type = 'POST'; //Automatically set type to POST if no type property is declared
}
if (!_config.url) {
_config.url = location.href; //Automatically set url to self if no url property is declared
}
if (!_config.method) {
_config.method = true; //Automatically set method to true if no method property is declared
}
var _xmlHttp = initXML(); //Declare request variable
_xmlHttp.onreadystatechange = function(){
if (_xmlHttp.readyState === 4 && _xmlHttp.status === 200) {
if (_config.success) {
_config.success(_xmlHttp.responseText);
}
}
else {
if (_config.error) {
_config.error(_xmlHttp.responseText);
}
}
}; //Check readyState and status to handle the request properly
//Handle the items sent
var _Itemstring = [], _sendItem = _config.sendItem;
if (typeof _sendItem === "string") {
var _arrTmp = String.prototype.split.call(_sendItem, '&');
for (var i = 0; i < _arrTmp.length; i ++) {
var _tmpData = _arrTmp[i].split('=');
_Itemstring.push(encodeURIComponent(_tmpData[0]) + "=" + encodeURIComponent(_tmpData[1]));
}
}
else if (typeof _sendItem === "object" && !(_sendItem instanceof String || (FormData && _sendItem instanceof FormData))) {
for (var k in _sendItem) {
var _tmpData = _sendItem[k];
if (Object.prototype.toString.call(_tmpData) === "[object Array]") {
for (var j = 0; j < _tmpData.length; j ++) {
_Itemstring.push(encodeURIComponent(k) + '[]=' + encodeURIComponent(_tmpData[j]));
}
}
else {
_Itemstring.push(encodeURIComponent(k) + '=' + encodeURIComponent(_tmpData));
}
}
}
_Itemstring = _Itemstring.join('&');
if (_config.type === 'GET') {
_xmlHttp.open('GET', _config.url + "?" + _Itemstring, _config.method);
_xmlHttp.send();
}
else if (_config.type === 'POST') {
_xmlHttp.open('POST', _config.url, _config.method);
_xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
_xmlHttp.send(_Itemstring);
}
}
AJAX called inside a JS file handling the changes in the inputs
// JavaScript Document
window.addEventListener('load', function(){
var _ranum = document.getElementsByClassName('ranum');
for (var i = 0; i < _ranum.length; i ++) {
_ranum[i].addEventListener('blur', function(){ //Check click outside
var _this = this;
ajaxFormValidate({
type:'POST',
sendItem: {
u: _this.value, //Send the value after the change
id: _this.id, //Send the product id
},
success: function(response){
console.log('SUCCESS');
}
});
}, false);
}
}, false);
Handling the changes in PHP file
var_dump($_POST['u']);
if (isset($_POST['id'], $_POST['u'])) {
if (!empty($_POST['id']) && !empty($_POST['u'])) {
$id = mysqli_real_escape_string($conn, $_POST['id']);
$u = mysqli_real_escape_string($conn, $_POST['u']);
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id] = $u;
}
}
}
I see the it logged out 'SUCCESS' in the console, however, when I use var_dump($_POST['u']) it doesn't work. Also, it updates the subtotal only if I reload the page.
What did I do wrong? I pretty sure my AJAX function is correct, and JS logged out 'SUCCESS', so what's the problem? Thanks very much
I'm doing an application web for a school and I'm stuck when trying to edit a student. I want the user to click in the row of and specific student and then open a form with his data.
I have to do an ajax request, so I can call my php function (the one which makes the query on my db) and load the data in the form. This is my jQuery code for the ajax request:
//When you click in the table students, in some element whose class is edit ...
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: '../ajax/',
data: {'table': 'alumnos', 'action': 'carga', 'ids': rowID},
dataType: 'json',
success: function(result) {
console.log(result.nombre);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
The ajax request calls the method to get the data from my db:
function cargaAlumno($ids) {
require 'db.php';
$sql = "SELECT * FROM Alumnos WHERE ID=$ids";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
$row = $result -> fetch_assoc();
$nombre = $row['Nombre'];
$apellidos = $row['Apellidos'];
$telefono = $row['Telefono'];
$usuario = $row['Usuario'];
$contrasena = $row['Contrasena'];
$result = array();
$result["nombre"] = $nombre;
$result["apellidos"] = $apellidos;
$result["telefono"] = $telefono;
$result["usuario"] = $usuario;
$result["contrasena"] = $contrasena;
ChromePhp::warn($result);
ChromePhp::warn(json_encode($result));
echo json_encode($result);
}
}
This method has to return a JSON to the ajax request, but the success method is never reached because of the error: parsererror.
I've tried with dataType: 'json' (this is when I have the error) and without it (it thinks its html). I also have tried with and without contentType and in my php: header('Content-type: application/json; charset=utf-8').
My json encoded looks like this:
{"nombre":"Susana","telefono":"56765336","usuario":"susa"}
I don't know if I need some more methods because I'm doing it in Wordpress or I have something wrong in my code.
Any help would be appreciated. Thank you in advance :)
If you are doing it in Wordpress, I'd use the built in wpdb to handle the db connection and results. Like so:
function cargaAlumno() {
global $wpdb;
$ids = $_POST['ids'];
$sql = $wpdb->get_results(
$wpdb->prepare("
SELECT *
FROM Alumnos
WHERE id = '$ids'
")
);
echo json_encode($sql);
exit();
}
Also remember this goes into your themes functions.php file.
Remember to hook it into the wp_ajax hook:
add_action( 'wp_ajax_nopriv_cargaAlumno', 'cargaAlumno' );
add_action( 'wp_ajax_cargaAlumno', 'cargaAlumno' );
Then in your ajax:
$("#tblAlumnos").on("click", ".editar", function(event) {
var rowID = $(this).parents('tr').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl, //this is a wordpress ajaxurl hook
data: {'table': 'alumnos', 'action': 'cargaAlumno', 'ids': rowID}, // You didn't use the correct action name, it's your function name i.e. cargaAlumno
//dataType: 'json', dont need this
success: function(result) {
//Parse the data
var obj = jQuery.parseJSON(result);
console.log(obj[0].nombre); // I'm guessing nombre is your db column name
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
alert(jqXHR.status);
alert(jqXHR);
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This js file needs to be added into your theme to work in conjunction with the above reworked function()
Let me know if you need anymore help or have any other questions.
Not sure if you're only providing particular lines of your code or this is the whole thing, anyway this is definitely NOT how you should handle AJAX requests in WordPress:
You should use wp_ajax_ for actions that requires authentication or wp_ajax_nopriv_ for ones that doesn't
You should create an action for this function and send your request through admin-ajax.php using admin_url()
You should definitely secure your requests by creating nonces using wp_create_nonce() and verify it using wp_verify_nonce()
You should restrict direct access to your AJAX file while checking $_SERVER['HTTP_X_REQUESTED_WITH']
There's no need to require db.php since you're already working within functions.php and the db connection is already established.
Use the below method instead:
global $wpdb;
$query = "SELECT * FROM table_name";
$query_results = $wpdb->get_results($query);
To wrap it up, please follow the below structure:
Frontend (php file):
<?php
$ajax_nonce = wp_create_nonce("change_to_action_name");
$ajax_link = admin_url('admin-ajax.php?action=change_to_action_name&nonce=' . $ajax_nonce);
?>
<a class="do_ajax" href="#" data-ajax_link="<?php echo ajax_link; ?>" data-ajax_param="other_param">DO AJAX</a>
<input id="param" value="" />
Script File (js file):
$('.do_ajax').click(function () {
var ajax_link = $(this).attr('data-ajax_link');
var param = $(this).attr('data-ajax_param');
if (ajax_link && param) {
$.ajax({
type: "post",
dataType: "json",
url: ajax_link,
data: {
param: param,
},
success: function (response) {
if (response.type == "success") {
/*Get/updated returned vals from ajax*/
$('#param').val(response.new_param);
console.log('ajax was successful');
} else if (response.type == "error") {
console.log('ajax request had errors');
}else{
console.log('ajax request had errors');
}
}
});
} else {
console.log('ajax not sent');
}
});
Functions File (functions.php file):
add_action("wp_ajax_change_to_action_name", "change_to_action_name");
add_action("wp_ajax_nopriv_change_to_action_name", "change_to_action_name");
function change_to_action_name()
{
if (!wp_verify_nonce($_REQUEST['nonce'], "change_to_action_name")) {
exit("You think you are smart?");
}
$param = $_REQUEST['param'];
/*php actions goes here*/
$actions_success=0;
if($actions_success){
/*Query db and update vals here*/
$new_param = "new_val";
$result['new_param'] = $new_param;
$result['type'] = "success";
}else{
$result['type'] = "error";
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
die();
}
Your current code contains many security flaws, so it's very recommended that you update it and use the above method.
Cheers!
I am trying to call ajax but it always goes in error part. Please help and tell me where I am wrong. I have also tried writing the final value in a text file and it was perfect but don't know why it is not working. I have also checked the URL it is also correct.
PHP Code:
public function checkLockBeforeSend()
{
$mail_key = $_POST['mail_key'];
$this->load->model('dl_master/email_compose');
$result = $this->model_dl_master_email_compose->checkLock($mail_key);
if($result['isopen'] == 1 && $result['openedby'] != $_SESSION['user_id'])
{
$this->load->model('dl_common/commonutil');
$userResult = $this->model_dl_common_commonutil->getUserById($result['openedby']);
$userName = $userResult['firstname'] . " " . $userResult['lastname'];
$html = $userName;
}
else
{
$html = "Empty";
}
/* Just to check what value is coming */
$fp = fopen("C:\\test.txt","w");
fwrite($fp,$html);
fclose($fp);
echo $html;
}
Ajax function:
function checkLockBeforeSend(mail_key)
{
var ajaxUrl = "index.php?route=dl_master/email_compose/checkLockBeforeSend&token=" + token;
$.ajax ({
url:ajaxUrl,
type:'post',
dataType: 'html',
data:{'mail_key':mail_key},
success:function (result)
{
alert(result);
if(result.trim() != "Empty")
{
finalResult = confirm(result);
}
},
error: function ()
{
alert("An error occurred.");
}
});
}
Please help me.
Please try data:{mail_key:mail_key}, instead of data:{'mail_key':mail_key},.