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!
Related
I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
This is my first baby step with Ajax and I'm already struggling. I have a request that inserts into the DB but my code for the moment is behaving like all the requests are successful, but I want to be able to handle the errors when updating the DB. I want to alert() a success/error message depending on the MYSQL response.
My Ajax call:
$("a.bgbtb").click(function(){
var btnid = $(this).attr("id").split('newbudbtn-')[1];
var newbudget = $("INPUT[id=newbud-"+btnid+"]").val();
var platform = $("span#"+btnid).text();
$.ajax({
url:"campbdgtedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newbudget:newbudget},
success:function(data){
myAlertTop();
}
});
});
campbdgtedit.php:
$query = "INSERT INTO campaigns (camp_budget, camp_campaignid) VALUES ('".$_POST['newbudget']."', '".$_POST['btnid']."')";
if ($conn->query($query) === TRUE) {
echo "Success<br/>";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
How can I catch if there is an error in the query and handle my alerts accordingly? I've tried many solutions I've found here but I can't seem to make them work.
I would recommend returning JSON from your PHP code, this can be interpreted directly as an object in the JavaScript if you use dataType: 'json' on your ajax call. For example:
if ($conn->query($query) === TRUE) {
echo json_encode(array('success' => true));
} else {
echo json_encode(array('success' => false,
'message' => "Error: Insert query failed"
)
);
}
Note that in general it's not secure to pass back query details and connection errors to the end user, better to pass back a generic message and log the actual error to a file or other location.
In your JavaScript:
$("a.bgbtb").click(function(){
var btnid = $(this).attr("id").split('newbudbtn-')[1];
var newbudget = $("INPUT[id=newbud-"+btnid+"]").val();
var platform = $("span#"+btnid).text();
$.ajax({
url:"campbdgtedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newbudget:newbudget},
dataType: 'json',
success:function(data){
if (data.success) {
// all good!
myAlertTop();
}
else {
// problems
alert(data.message);
}
}
});
});
If i understand correctly, you need to analyze the "echo" from the php side in the JS side in order to alert the appropriate error.
Use the "data" that is returned here:
success:function(data){
myAlertTop();
}
and do the following:
success:function(data){
myAlertTop(data);
}
function myAlertTop(replyfromPHPside)
{
if (replyfromPHPside =="abc")
{
alert('..');
}
else
{
...
}
}
I believe the best way is to echo out a json-string from PHP and "catch" the response in javascript like this:
campbdgtedit.php:
$query = "INSERT INTO campaigns (camp_budget, camp_campaignid) VALUES ('".$_POST['newbudget']."', '".$_POST['btnid']."')";
$arr = array();
if ($conn->query($query) === TRUE) {
$arr['response'] = true;
} else {
$arr['response'] = false;
}
echo json_encode($arr);
Javascript:
$("a.bgbtb").click(function(){
var btnid = $(this).attr("id").split('newbudbtn-')[1];
var newbudget = $("INPUT[id=newbud-"+btnid+"]").val();
var platform = $("span#"+btnid).text();
$.ajax({
url:"campbdgtedit.php",
method:"POST",
data:{platform:platform, btnid:btnid, newbudget:newbudget},
success:function(data){
if (data.response == 'true') {
alert('DB success');
}
else {
alert('DB fail');
}
}
});
});
I am using two modals forms in one page, one for login and another for register. From login form you can access the register one. I am trying to show an error based on what I echo without reload the page. Instead of echo I tried to return or print,but I got nothing.I don't receive anything from the server. In console.log show me only "Message".
Here is my code:
register.php
if ($count == 0) {
if ($check == 1)
$query = "INSERT INTO..
elseif ($check == 2)
$query = "INSERT INTO..
else {
$query = "INSERT INTO ..
}
if ($db->query($query)) {
echo "1";
} else {
echo "2";
}
} else {
echo "3";
}
My jS
$("#register").on('submit',function (event) {
event.preventDefault();
/*var $form=$(this);*/
$.ajax({
url : 'register.php',
type : 'POST',
data : $('#id02').serialize(),
success : function (data) {
console.log("Message:"+data);
$('#error-reg').text("Success").css('color', 'green');
},
error: function (msg) {
if(msg=="2") $('#error-reg').html('Error while registering.Please try again');
if(msg=="3") $('#error-reg').html('The username already exists.');
}
});
});
try your error: function with below code to check in details
error: function (xhr, err) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
},
Try This :
success : function (data)
{
if(data==1)
{
$('#error-reg').text("Success").css('color', 'green');
}
else if(data==2)
{
$('#error-reg').html('Error while registering.Please try;
}
else if(data==3)
{
$('#error-reg').html('The username already exists.');
}
}
I've got the Problem that I can't reach my php file with my $.ajax() call. I always get
a jqXHR.status of 0. This is my code:
function with $.ajax() call:
function updateClubInfo(text) {
var data = text;
$.ajax({
type: 'POST',
dataType: 'json',
url: '../php/updateInfo.php',
data: {
infoText: data,
action: "update"
},
success: function() {
// do nothing
alert('success');
},
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.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}
I've build this request similar to others in my project, but this one is the only one
that doesn't work. Here the PHP file I want to reach:
php code snippet (updateInfo.php):
<?php
$action = $_POST['action'];
$text = $_POST['data'];
myLog($action);
myLog($text);
echo "hello";
/*
* Writes entry in Logfile
*/
function myLog($data) {
$text = #file_get_contents('log.txt');
$text = $text . "\n" . $data;
#file_put_contents('log.txt', $text);
}
?>
When I try to reach this PHP file in the URI the echo is outputted. So I think the
Problem should be in the ajax call.
Does someone has an Idea what I'm doing wrong? I'm grateful for any help.
Thx alot for your help
Cris
You have a copy/paste error in your PHP file. It should be :
$action = $_POST['action'];
$text = $_POST['infoText'];//instead of $_POST['data']
UPDATE
Because your AJAX request asks for JSON data, but you are writing only text in your PHP file. Therefore, the AJAX request interprets the answer as void, then HTTP status = 0
Solution
dataType option is not about the type of data you are sending to the server, but the type or data you are expecting back from the server. Change dataType: 'json', to dataType: 'html', or symply remove it to let JQuery chose the appropriate mode.
$action = $_POST['action'];
$text = $_POST['data'];
myLog($action);
myLog($text);
$arr[] ='hello';
echo json_encode($arr);
/*
* Writes entry in Logfile
*/
function myLog($data) {
$text = #file_get_contents('log.txt');
$text = $text . "\n" . $data;
#file_put_contents('log.txt', $text);
}
json data fetch only in array
When using the code below I am having trouble setting the right location. Somehow in the callback file the php constant is not recognised, thus the rest of the code is not functioning.
snippet from html:
<a href="#" class="selectLocation" id="ABC">
snippet from .js
var locationID;
$(".selectLocation").click(function(){
locationID = this.id;
setLocation();
});
function setLocation() {
$.ajax({
data: {location: locationID},
success: function (data) {
// do something
};
});
};
// DEFAULT AJAX SETUP
$(function () {
$.ajaxSetup({
type: "POST",
url: "dir/callback.php",
dataType: "json",
cache: "false",
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
console.log('No connecting.\n Verify Network.');
} else if (jqXHR.status == 400) {
console.log('Bad Request. [400]');
} else if (jqXHR.status == 404) {
console.log('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
console.log('Internal Server Error [500].');
} else if (exception === 'parsererror') {
console.log(jqXHR.responseText);
console.log('Requested JSON parse failed.');
} else if (exception === 'timeout') {
console.log('Time out error.');
} else if (exception === 'abort') {
console.log('Ajax request aborted.');
} else {
console.log('Uncaught Error: ' + jqXHR.responseText);
};
}
});
snippet from callback.php:
<?php
header("content-type:application/json");
session_start();
require_once ('config.php');
...
$connect->setLocation($_POST['location']);
the $_POST['location']; will send ABC to the rest of my code instead of the right value defined below.
snippet from config.php:
define('ABC', 'some location');
While if I do:
echo (ABC);
in the callback file, I will get the correct location value.
In your $_POST['location'] variable, there's a string 'ABC'.
So if you do echo($_POST['location']);, you'll get ABC, not some location.
Try this one :
$connect->setLocation(constant($_POST['location']));
If you intend to set the a-element's id property to your ABC-constant, you'd have to do it like this:
<a href="#" class="selectLocation" id="<?php echo ABC; ?>">
PHP constants are only resolved in PHP-code, not in HTML.
Besides that, encoding data in a DOM-element's ID seems somewhat convoluted to me. If I have to encode stuff in HTML elements, I prefer to use hidden span-tags or hidden elements if I'm inside a form. You can also try adding the following to your PHP script producing the HTML file:
<script type="text/javascript">
locationID = <?php echo ABC; ?>;
</script>
Assuming locationID is in global scope. Alternatively, you can provide some kind of init()-function in your JS file and call it via a snippet similar to the above.