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
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.😅
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 wanna make header location like stackoverflow system has. After posting, it will load the page based on lastinsertid. I tried to use php, it works, but I wanna change it using ajax jquery because of its single page. Could I use ajax jquery in this case? how to make it work?
here's the code :
PHP
if($sumn>0 && $sump>=0) {
echo "banned";
}
else if($sumn==0 && $sump<=3) {
echo "oot";
}
else{
$insert=$db_con->prepare("INSERT INTO tb_post (id_user,title,description,created_date) VALUES(:id_user,:title,:description,NOW())");
$insert->bindParam(":id_user",$id_user);
$insert->bindParam(":title",$title);
$insert->bindParam(":description",$description);
$insert->execute();
$id_post=$db_con->lastInsertId();
if ($insert->rowCount()>0) {
$post = $db_con->prepare("SELECT * FROM tb_post WHERE id_post=:id_post");
$post->execute(array(":id_post"=>$id_post));
$row=$post->fetch(PDO::FETCH_ASSOC);
$title = clean_url($row['title']);
$detail ="../discuss/".$row['id_post']."/".$title;
header("location:$detail");
echo 'success';
}else {
echo 'fail';
}
ajax jquery
$.ajax({
url: 'create_process.php?page=send_post',
type: 'post',
data: 'title='+title+'&description='+description,
success: function(msg){
if(msg=='success') {
window.location='/'; //This the problem.. need to know how to use header location based on lastinsertid
}
else if(msg=='banned') {
$("#dis-mes").html('<div class="allert alert-danger">Banned</div>');
}else if(msg=='oot'){
$("#dis-mes").html('<div class="allert alert-danger">OOT</div>');
}else {
alert('failed');
}
}
});
instead of using a header, you should return the redirect url in the response.
the php response should be a json string like this :
{
status: "success",
url: "../discuss/".$row['id_post']."/".$title
}
in the javascript just check the content of msg.status and use msg.url in your window.location
If you still want to use headers, you can use this in your success function:
success: function(msg, textStatus, request){
if (msg == 'success') {
window.location = request.getResponseHeader('location'));
}
},
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.
I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.
The client side:
<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();
$.ajax({
url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
});
</script>
The server side:
<?php
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
$query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Additional fix, you should check whether the query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Hope it helps.
Just so you know, you can use this for debugging. It helped me a lot, and still does
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.
However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WAS found.
Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.
e.g. in PHP you'd have
$results = array(
'error' => false,
'error_msg' => 'Everything A-OK',
'data' => array(....results of request here ...)
);
echo json_encode($results);
Then in your client-side code you'd have
if (!data.error) {
... got data, do something with it ...
} else {
... invoke error handler ...
}
In order to build an AJAX webservice, you need TWO files :
A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
Server side:
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
Client side:
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
adding to the top answer: here is some sample code from PHP and Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - send custom message / status:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
I had the same issue. My problem was that my header type wasn't set properly.
I just added this before my json echo
header('Content-type: application/json');
...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.
Typically, right mouse->inspect on your html page.
Then look in the error console for errors like
Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.