PHP directing to error 404 not working - javascript

I have 2 files time.html and time.php. I am trying to show server date and users date(I use JS for this) in time.html. In php I create random number from 1 to 5 and if number is equal or greater than 3, php should wait 5s then show error 404.
NOTE: if random is smaller than 3 everything works perfectly
PHP:
<?php
$rnd = rand(1, 5);
if ($rnd >= 3) {
sleep(5);
header("HTTP/1.0 404 Not Found");
}
if ($rnd < 3) {
sleep(3);
$tz = date_default_timezone_get();
date_default_timezone_set($tz);
$time = date('d.m.Y H:i:s');
echo "Timezone: " . $tz . ". On date: " . $time;
}
?>
jQuery:
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
$("span").text(data);
}
});
document.getElementById("jsTime").innerHTML += Date();
});
});

That is because when server responds with an error, jquery.ajax runs the error function, which means your success function does not run. See error on api.jquery.com/jquery.ajax/#jQuery-ajax-settings
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
$("span").text(data);
},
error: function(jqxhr){
//redirect to 404 page on 404 error
if(jqxhr.status == 404){
window.location.href="HTTP/1.0 404 Not Found";
}
}
});
document.getElementById("jsTime").innerHTML += Date();
});
});

As said, when the server returns an error and the request fails, Jquery Ajax let you handle this error with the error function;
Try to add a couple of options more in the settings:
add the error function.
add the statusCode object and play with it; This lets you have more structured control over the error handling.
So:
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
console.info('success');
$("span").text(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.info(jqXHR.responseText);
console.info(jqXHR.status);
console.info(textStatus);
console.info(errorThrown);
$("span").text(jqXHR.responseText);
},
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
document.getElementById("jsTime").innerHTML += Date();
});
and modify the if inside the php file:
if ($rnd >= 3) {
sleep(1);
echo "my response text";
header("HTTP/1.0 404 Damn, Not Found"); //just for playing, then keep with HTTP standard description
}
Quoting the jQuery.ajax documentation:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn.
Note: This handler
is not called for cross-domain script and cross-domain JSONP requests.

Try to return the data to jquery in array like
$str[0]=true/false;
$str[1]="HTTP/1.0 404 Not Found"/"Timezone: " .$tz . ". On date: ".$time
In success check the condition
success: function (data) {
if(data[0]==true){
$("span").text(data[1]);
}else{
window.location.href="HTTP/1.0 404 Not Found";
}
i think so ajax call must be completed to redirect, above code works in my machine

Related

i can't pass a json object from my php to my jquery

I tried to pass a json object from my test.php to my jquery in index.html but i can't.
here is my test.php script:
<?php
if(isset($_POST["view"]))
{
$output .= '
<li>No Notification Found</li>
';
$total_row=2;
$data = array(
'notification' => $output,
'unseen_notification' => $total_row
);
echo json_encode($data);
}
?>
and here is my jquery script , "the alert in js show undefined as result":
function load_unseen_notification(view = '')
{
$.ajax({
url:"test.php",
method:"POST",
data:{view:view},
dataType:"json",
complete:function(data)
{
alert(data.notification);
$('.dropdown-menu').html(data.notification);
if(data.unseen_notification > 0)
{
$('.count').html(data.unseen_notification);
}
}
})
}
In PHP, you need to put a header response from the server so that the browser knows what it got in response (see: https://www.iana.org/assignments/media-types/media-types.xhtml , http://php.net/manual/en/function.header.php):
<?php
header("Content-Type: application/json");
In JavaScript, you need to use success event:
$.ajax({
url: "test.php",
method: "POST",
data: {
view: 10
},
dataType: "json",
success: function(data) {
alert(data.notification);
}
});
success - A function to be called if the request succeeds.
Arguments: ( Anything data, String textStatus, jqXHR jqXHR ).
complete - A function to be called when the request finishes (after success and error callbacks are executed).
Arguments: ( jqXHR jqXHR, String textStatus )
Documentation: http://api.jquery.com/jquery.ajax/
If to use complete, then access to data can be got by means of jqXHR Object (see: http://api.jquery.com/jQuery.ajax/#jqXHR):
complete: function(jqXHR) {
if (typeof jqXHR.responseJSON !== 'undefined') {
alert(jqXHR.responseJSON.notification);
}
}
Of course if necessary it is possible to combine different event handlers.
P.S. For debugging use console.log(data) instead of alert(data) and look through the log in the browser. For example, for Google Chorme (F12, Tab: Logs): https://developers.google.com/web/tools/chrome-devtools/console/get-started
It might be a good idea as well to set the content-type header at the top of your PHP script:
<?php
header("Content-Type: application/json");
jQuery will probably interpret the body as JSON instead of 'text'.
I added $.trim()to my data.responseText and finally it's working (i don't know why :) )
var obj = JSON.parse($.trim(data.responseText));
$('.dropdown-menu').html(obj.notification);
Thx a lot for you all for your assisting

AJAX in WordPress only returns 0

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.
The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:
JS/jQuery built into PHP function ajax-action()
$ = jQuery;
$('#platform').change(function(e) {
var data = {
action: 'action_cb',
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
PHP functions and add-actions
add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };
My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.
As per the wordpress documentation:
https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")
A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)
Things to check:
Where are you defining your add_action('wp_ajax_action_cb','action_cb');?
Specifically, what portion of your plugin code?
Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)
Additionally, you didn't share the function this is tied to:
add_action('admin_footer','ajax_action');
And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...
So your code would look like so:
function action_cb() { $platform = 'test'; echo $platform; p_die(); };
...and your AJAX could be:
<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
if (data != '0' && data != '-1') {
{YOUR SUCCESS CODE}
} else {
{ANY ERROR HANDLING}
}
},
dataType: 'html'
});
</script>
Try This:
<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
</script>
Probably you need to add
add_action('wp_ajax_nopriv_action_cb', 'action_cb');
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
just make small change in your AJAX. I am assuming you're logged in as admin.
replace action in data object with data:"action=action_cb",
var data = {
data:"action=action_cb",
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl,data,function(data){
$('#user_id').val(data);
});
To prevent WP adding zero into response i always using die(); insted of wp_die();
and registering function:
add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );
function action_cb_init() {
}
When calling to function with AJAX use action: 'action_cb'
Hope this helps. I have already explained standard way of using ajax in wp.
Wordpress: Passing data to a page using Ajax
Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.
$j = jQuery.noConflict();
$j('#platform').change(function(e) {
$j.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'action_cb',
}
}).done(function( data ) {
// When ajax-request is done.
if(data) {
$j('#user_id').val(data);
} else {
// If 0
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
// If ajax failed
console.log(errorThrown);
});
e.preventDefault();
});
I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.
For those by the "Load More" problem.
Normally "0" is used instead of false.
I found such a solution.
So that 0 does not come. Try this code with false.
PHP
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
JS
if( posts[i] == false )
$(".load_more_button").fadeOut();

jQuery.ajax + php 5.3 - always executing error function

(Newb here) I have a PHP function that gets 2 csv files from the server and create a new one with the difference between values contained in those files. This PHP function is inside a separate file test.php and looks like this:
<?php
require_once('libs/parsecsv-for-php-master/parsecsv.lib.php');
$csv1name = $_POST['csv1'];
$csv2name = $_POST['csv2'];
$data1 = 'data/'.$csv1name.'.csv';
$data2 = 'data/'.$csv2name.'.csv';
$csv1 = new parseCSV($data1);
$csv2 = new parseCSV($data2);
$csv = new parseCSV();
$csv->data[0] = array('label','difference');
$j = 1;
for ($i = 0; $i < count($csv1->data); $i++) {
$csv->data[$i+1] = array($j.'d',$csv1->data[$i][$csv1name] - $csv2->data[$i][$csv2name]);
if($i == 0) {$j += 20;}
else {$j += 21;}
}
$csv->save('test.csv');
?>
This function works correctly and produces the expected csv file.
I have a JavaScript function that sits on another page (namely update.html) and calls the aforementioned php function via ajax:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
},
});
}
PROBLEM: The error function is always executed, that is, whenever I run callPHP() I get two alerts.
QUESTION: Why is it error always being called?
(Extra: Is it possible to work with the response variable? How can I debug it without having to upload my files to a server every time? Is it guaranteed that when the complete function is called, the $csv->data function was already resolved?)
Thanks for helping!!! :D
UPDATE 1: I changed the code above by removing the complete function from ajax and I added some extra parameters to the error function.
complete is always called no matter its success or error. So you are running into error condition and complete gets called anyway after error is executed. You can add additional params (jqXHR jqXHR, String textStatus, String errorThrown) in error function to figure out what the error is.
Try using success instead of complete, and add a JSON answer to your PHP script for example echo json_encode((object) array('success'=>true)); because your AJAX call has dataType:"json" parameter for a JSON response, so your AJAX call will try to parse a JSON.
PHP code:
header('Content-Type: application/json');
echo json_encode((object) array('success'=>true));
AJAX:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
},
});
}

Undefined index: Error in ajax POST and/or php script?

I'm trying to send an ajax POST to a php file, however the php file sends a notice of "undefined index", and the php file never seems to receive the value i'm trying to send it. I've been searching for the answer to why this isn't working correctly, so hopefully someone can give me some insight.
My javascript function receives a value from the html, and receives the correct value. (it's "1" in this case)
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {vals : val},
type: 'post',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}
Here is part of my php file that should receive the post:
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$val = $_POST["vals"];
// create connection
$con = mysqli_connect(<stuff you don't care about>);
error_log($val . ' is the value', 3, "./error.log");
?>
I am, however getting this error message from php:
Notice: Undefined index: vals in
/xxx/xxx/htdocs/AdminPanel/deleteMediaFromDatabase.php on line 9
And my javascript always outputs the alert in the error: "Error: Could not delete"
I know this question has been asked and answered many times, however unless I'm skipping over something small, my code, to me, looks correct. (but doesn't it always...)
There is error in syntax of jquery.. You missed out syntax of data. This should be like this-
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}
The problem can come from the dataType not being specified or that the dataType specified does not match thus returned by the server.
Explicitely set the dataType, e.g.
dataType:'json'
and make sure that your script returns data that is "encoded" in the data type that you chose, e.g. in PHP:
echo json_encode($something);
Instead of:
$val = $_POST["vals"];
use this:
if (isset($_POST['vals']) {
$val = $_POST['vals'];
}
Change Ajax syntax...
$.ajax({
type: "POST",
url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},//Have u tried this
success: function(output) {
alert(output);
}
error: function(request, status, error){
alert("Error: Could not delete");
}
);
$val = $_POST["vals"];
I got same problem , i tried declaring the variable as global , that solved my problem.
global $val;
$val = $_POST["vals"];
and always check isset($_POST["vals"])

$.ajax not working first time

I have a button in html page.
<input type="image" src="images/login_button.png" id="imageButton" onclick="LoginButtonClick();" />
I am calling this method on button click:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
alert ("Inside Ajax."); // This alert not executing first 1 or 2 times.
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
}
});
}
As I mentioned above $.ajax not working first 2 , 3 button click attempts.
In mozilla it throws an error "[Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: JQuery.js :: :: line 20" data: no]"
Is there any way to fix this issues..
I'm not sure why it is executing later. But here's the deal--you're placing the alert in the object literal that defines the parameters for the .ajax method. It doesn't belong there. Try putting the alert in your success and/or error handlers.
UPDATE
How long are you waiting? When you initiate an ajax request, it isn't going to hang the UI. It could be that you're seeing the result of the first click on your 3rd or 4th attempt and think that you're triggering it on that 3rd or 4th attempt.
The $.ajax() function receives as a parameter a set of key/value pairs that configure the Ajax request. I don't think that the syntax will be correct by placing the alert() in there.
Note - entering an absolute path isnt going to work if the domain is not the current one - it is against the Same Origin Policy that browsers adhere too - this might explain why nothing happens when its executed - i suggest you look in your browser debugger to verify.
You should be binding the click event like this :
$(document).ready(function() {
$('#imageButton').click(function() {
// code here
});
});
so your complete code will look like this :
HTML
<input type="image" src="images/login_button.png" id="imageButton" />
JavaScript
$(document).ready(function () {
$('#imageButton').click(function () {
alert("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: pmamml.ajaxError,
success: function (response, status, xhr) {
if (response != "") {
alert("Response receive ");
} else {
alert("Invalid Data.");
}
}
});
});
});
I have removed the alert ("Inside Ajax."); line as this will not be executed - you pass an object {} of parameters not code to execute. If you want to execute before the ajax request is sent do this :
$.ajax({
beforeSend: function() {
alert('inside ajax');
}
// other options here
});
Docs for the $.ajax() function are here
I agree that you have the second alert in the wrong place, and dont know what pmamml.ajaxError function is but may be your call returns with error and therefore your success alerts are not firing. You can check with error and complete functions as follows:
LoginButtonClick = function() {
alert ("Button click event raised"); // this alert msg raising every time when onclick event occurs.
$.ajax({
type: 'GET',
url: 'http://URL/Service.svc/LoginValidation',
dataType: 'json',
error: function(jqXHR, textStatus, errorThrown){
alert ("ajax call returns error: " + errorThrown);
},
success: function(response, status, xhr) {
if (response != "") {
alert ("Response receive ");
}
else {
alert("Invalid Data.");
}
},
complete:function(jqXHR, textStatus){
alert('completed with either success or fail');
}
});
}
You can test with Google Chrome's Developer tools -> Network tab, if a request is made and returned (https://developers.google.com/chrome-developer-tools/docs/network)

Categories