Ajax Internal Error, jqXHR: underfined - php

Ive butchered my code trying to find this bug. I have a Ajax post function working elsewhere on my code and it works fine.
For some reason this one does not want to cooperate.
Im going to reduce the amount of inputs so the code doesnt look too long.
Here is the php
<?php
// --------Connect to DB --->
include 'connect.php';
$conn = connect ();
//====================================================================>
//grab data
$this_id = $_POST('pid_num');
$this_start_date = $_POST('date_ammend');
$sql_update_query = "UPDATE Galaxy_jobs SET date ='$this_start_date' WHERE PID = $this_id";
//====================================================================>
mysqli_query ($conn,$sql_update_query);
//close
mysqli_close($conn);
?>
Here is my Ajax call.
function ammend_job()
{
pid = '2'; // test figures
start_date_ammended = '11-11-1111'; // test figures
var Data = {
pid_num : pid,
date_ammend : start_date_ammended,
};
$.ajax({
url:"ammend_job.php",
type: "POST",
dataType: 'text',
data: Data,
success: function(data){
if(data.status == 'success')
alert('Post has been uploaded to Database');
},
error: function(xhr,textStatus,err,jqXHR) {
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
console.log("Jquery error:" + jqXHR)
// alert('There is an error, screenshot this error and send to Admin : TextStatus: ' +textStatus+" - Error: "+errorThrown+" - XMLRequest: "+XMLHttpRequest+"- Response Text"+xhr.responseText);
}
});
}
Here are the error codes :
main.php:102 readyState: 4
main.php:103 responseText:
main.php:104 status: 500
main.php:105 text status: error
main.php:106 error: Internal Server Error
main.php:107 Jquery error:undefined
Any help will be greatly appreciated.

It took a while.
I wouldnt have found it if it wasnt for user : tereško who suggested to look closely at the errorlog on the server.
I found that when I replaced my code in php file
//grab data
$this_id = $_POST('pid_num');
$this_start_date = $_POST('date_ammend');
with the square brackets
//grab data
$this_id = $_POST['pid_num'];
$this_start_date = $_POST['date_ammend'];
The code didnt throw an error and worked.
I hope somebody else out there finds this post and figures out that this may be 1 reason for their error.

Related

Jquery Ajax call to PHP don't give me any data back with dataType JSON

I'm working everyday with ajax and php at work, so it's nothing new. But now i tried a little project at home and i can't get it to work. I really don't know what i have done wrong. I just select a value from a dropdown and press a Button. The button has a onclick to a function calles "showTable". It selects the value of the dropdown and send it via ajax call to my index.php where i do a simple select to my database and wanna return the results, so i can build a table with it. But my ajax call always go to the error case, even if the result of the select is correct.
If i console.log my error, it just says "parseerror" but the network part always says 200 ok
So, this is my function within my index.html...
<script>
function showTable() {
var coin = $('#selectCoin').val();
$.ajax({
type: 'POST',
url: 'index.php',
dataType: "json",
data: {
act: 'showTable',
'coin' : coin
},
success: function(data) {
alert("ok")
},
error: function(request, error) {
alert("error")
}
});
}
</script>
And this is my php part
if($_POST) {
switch ($_POST["act"]) {
case 'showTable':
$token = $_POST["coin"];
$token_buy = $token.'_buy';
$token_sell = $token.'_sell';
$sql = "SELECT * FROM $token_buy";
$stmt = $PDO->prepare($sql);
$stmt->execute(array());
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
break;
}
}
I tried to update the composer and added the
"ext-json": "*"
Also i tried to remove the dataType Attribute from my ajax call. After that it don't get into the error case, but also i don't get my data from backend.
If i let me show the error with following function
error: function(jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText)
}
It says:
parseerror: SyntaxError: unexpected token "<", "<!DOCTYPE"...is not valid JSON: and continue with the whole html part in the error message

Can I use a jQuery Ajax request in Code Snippets Plugin for Wordpress?

I am using the Code Snippets Plugin for WordPress to send a jQuery Ajax request but I keep receiving a
POST https://mywebsite.com/wp-admin/admin-ajax.php 400 (Bad Request)
I have tried what seems to be a thousand ways to formulate the Ajax request following examples from stackoverflow, jQuery forums, WordPress forums, and it goes on. Always with the same error.
Here is what I currently have in my Snippet editor:
JavaScript code
var jq = jQuery.noConflict();
// a bunch of code to determine what day is selected on a calendar, this all works up until the ajax call
jq(".c-day-content").click(function () {
console.log ("handled the day being picked quite nicely...");
day = jq(this).text();
day = day.replace(/[^0-9]/g,'');
console.log("day=" + day);
bookingStart = bookingStart.concat(day);
//query the db looking for time slots with appointments and returning this array
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>';
console.log(ajaxurl);
jq.ajax({
url: ajaxurl,
data: {
action: "retrieveAttendees",
dateSelected: bookingStart //bookingStart is variable that has a string value
},
method: 'POST',
success: function(data, XMLHttpRequest) {
//never been able to make it to here
console.log(JSON.stringify(data));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("we failed again: " + JSON.stringify(XMLHttpRequest));
console.log("text status: " + textStatus);
console.log("errorThrown: " + errorThrown)
}
});
Then my php handler inside the same snippet editor:
function retrieveAttendees_request() {
console.log("made it to the ajax request"); // I've never made it here either
if ( isset($_REQUEST)) {
$bookingDay = $_REQUEST['dateSelected'];
global $wpdb;
$sql = $wpdb->prepare("select apps.bookingStart, COUNT(*) as booked from wp_amelia_customer_bookings as books inner join wp_amelia_appointments as apps on books.appointmentId = apps.id where apps.bookingStart like %s'%' and apps.status = 'approved' GROUP BY books.appointmentId;", $bookingDay);
$result = $wpdb->get_row($sql, ARRAY_A);
echo json_encode($result);
}
die();
}
add_action('wp_ajax_retrieveAttendees', 'retrieveAttendees_request');
add_action('wp_ajax_nopriv_retrieveAttendees', 'retrieveAttendees_request');
I have tried adding the dataType to the Ajax, no luck. Tried adding both dataType and ContentType, no luck. I have no clue as to why I keep getting the same POST 400 Bad Request error. I would appreciate any help and insight.

PHP + jQuery - undefined index: , but it still posts successfully?

When inserting a record to a database, the server returns an 'undefined index: category', error, but still posts the successfully.
$('#button').click(function(){
var newvendor = $('#input_vendor').val();
newplantcode = $('#input_plantcode').val();
newcategory = $('#input_category').val();
$.post("php/addSite.php",
{vendor: newvendor,
plant_code: newplantcode,
category: newcategory}, // <--- Error on this line, for some reason...
function(result){
console.log("server returned : " + result);
[ RELOAD THE PAGE ]
}
You having missing quote in almost all your code:
$('#button').click(function(){
var newvendor = $('#input_vendor').val();
var newplantcode = $('#input_plantcode').val();
var newcategory = $('#input_category').val();
$.post("php/addSite.php",
{vendor: newvendor,
plant_code: newplantcode,
category: newcategory}, // <--- Error on this line, for some reason...
function(result){
console.log("server returned : " + result);
[ RELOAD THE PAGE ]
}
//closing the post function
)
//closing the click event
});
Now try that again

jQuery/JSON/PHP failing

I am trying to call a php script that accepts JSON data, writes it into a file and returns simple text response using jQuery/AJAX call.
jQuery code :
$("input.callphp").click(function() {
var url_file = myurl;
$.ajax({type : "POST",
url : url_file,
data : {puzzle: 'Reset!'},
success : function(data){
alert("Success");
alert(data);
},
error : function (jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + "<" + errorThrown + ">");
},
dataType : 'text'
});
});
PHP Code :
<?php
$thefile = "new.json"; /* Our filename as defined earlier */
$towrite = $_POST["puzzle"]; /* What we'll write to the file */
$openedfile = fopen($thefile, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
echo "<br> <br>".$towrite;
?>
However, the call is never a success and always gives an error with an alert "Error : [Object object]".
NOTE
This code works fine. I was trying to perform a cross domain query - I uploaded the files to the same server and it worked.
var url_file = myurl"; // remove `"` from end
Arguments of error function is:
.error( jqXHR, textStatus, errorThrown )
not data,
You can get data (ie. response data from server) as success() function argument.
Like:
success: function(data) {
}
For more info look .ajax()
NOTE
If you're trying to get data from cross-domain (i.e from different domain), then you need jsonp request.
Your data object isn't valid; the key shouldn't be quoted:
data : { puzzle: 'Reset!' }
In addition, SO's syntax highlighting points out that you have missed out a " in your code:
var url_file = myurl";
Should be
var url_file = "myurl;

[JQUERY][PHP] AJAX request returns OK but it goes to error

I'm trying to make JQUERY and PHP communicate with some strange results
Here's the JQuery
$.ajax({
type : "GET",
url : "background.php",
dataType: 'json',
success : function(response){
alert("OK: " + immagini);
},
error: function(xhr, ajaxOptions, thrownError){
eval('var immagini = xhr.responseText');
alert("CODE: " + xhr.status);
alert("ERROR: " + immagini + "\n\n\nTIPO: " + typeof immagini);
}
});
And here's the PHP
<?php
include "amministrazione/config.php";
include "amministrazione/database.php";
header("Content-type: application/json");
$db = new DB($db_server,$db_name,$db_user,$db_pass);
echo $db->loadBackgroundImages();
?>
And finally there is the answer I build from PHP function
{'immagini':[{'image': 'gallery/alto.jpg'},{'image': 'gallery/esterno.jpg'},{'image': 'gallery/gelateria.jpg'},{'image': 'gallery/vitelli.jpg'}]};
Strange thing is that the Jquery ends up in the error handler even if code is 200... how can I fix this?
This shouldn't be a Cross-Domain problem, since they are on the same directory on EasyPHP, or am I wrong?
Many thanks,
Tiwiz
change single quote to double quote in your json
{"immagini":[{"image": "gallery/alto.jpg"},{"image": "gallery/esterno.jpg"},{"image": "gallery/gelateria.jpg"},{"image": "gallery/vitelli.jpg"}]}

Categories