jQuery - AJAX POST Request is giving a 500 Internal Server Error - javascript

So like this post's title says, I'm sending a POST request via jQuery's AJAX method. However, the PHP code it runs does indeed run. Everything in the PHP code works as it should. The only issue is that it's not returning a success in order to run the success function.
Client-Side JS Code:
<script>
function commandUpdate(command, action, element) {
$.ajax({
type: "POST",
url: "update/commands.php",
data: {id: window.location.href.split("?id=").slice(1).join("?id="), type: "NA", command: command, action: action, value: document.getElementById(command + "Text").value},
success: function() {
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
})
}
</script>
Server-Side PHP Code:
<?php
$connection = mysqli_connect("myIP", "user", "pass", "dbName");
$loginID = $_POST["id"];
$type = $_POST["type"];
$value -> command = str_replace("\"", "\\\"", $_POST["command"]);
$value -> action = str_replace("\"", "\\\"", $_POST["action"]);
$value -> value = str_replace("\"", "\\\"", $_POST["value"]);
$value = json_encode($value);
mysqli_query($connection, "INSERT IGNORE INTO requests (loginID, category, type, value) VALUES ('$loginID', 'commands', '$type', '$value')");
mysqli_close($connection);
?>
All of it works, except for the fact that the console has the 500 Internal Server Error and the success: function() {//code} part isn't being executed. Is there something that I'm missing here?

500 Code means something isn't working on the server-side. I had a similar situation where a different server than my own gave this problem even though it provided all of the information itself and seemed to work well.
I couldn't resolve the 500 error, so eventually just put an always() listener on the call and conditioned 200 and 500 codes along with expected data structure.
since you're not storing the call in a var. you can do it like this:
function commandUpdate(command, action, element) {
$.ajax({
type: "POST",
url: "update/commands.php",
data: {id: window.location.href.split("?id=").slice(1).join("?id="), type: "NA", command: command, action: action, value: document.getElementById(command + "Text").value},
success: function() {
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
statusCode: {
200: function(){
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
500: function(){
document.getElementById(element).innerHTML = "🗸"
location.reload()
}
}
})
}
or chain it:
$.ajax({
/*options*/
}).always(function(data){
if(data.statusCode === 200 || data.stausCode === 500){
/*Do things with data*/
}
});

I had this same issue. For me the problem was in the page to which the ajax call was made (calling a function which wasn't available in that page). My suggestion is to go to the page that you are calling in ajax and see the errors in that page. Once you fix that, the ajax call should go through fine.

Related

Sending data of ajax by another ajax to controller in laravel

I want to know is that possible to send data from one ajax by another ajax or not?
Sounds confusing I know, but here is explanation:
I have payment method where it gets data and handling them by Ajax (unfortunately the creators of this API limited their code a lot) so even if i try to add input request in controller code of that Ajax nothing will work, that's why I need to make another Ajax to handle that input request.
Lets explain more by codes:
controller
public function orderspayonline(Request $request, $id){
error_log('masuk ke snap token dri ajax');
$midtrans = new Midtrans;
//products data + user info etc.
//here magic happens
try
{
$snap_token = $midtrans->getSnapToken($transaction_data);
echo $snap_token;
}
catch (Exception $e)
{
return $e->getMessage;
}
}
If I add anything (I mean anything) in that try{ part it will stop functioning and return error! `even I tried to redirect back my users except echoing token code that gave error as well. So it seems I really don't have any option here but to create new function and Ajax.
JavaScript
<script type="text/javascript">
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("orderspayonline")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type,data){
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
}
snap.pay(data, {
onSuccess: function(result){
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result){
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result){
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
</script>
The part I need to manipulate is snap.pay(data, { where results gets back.
Currently they are return in console and disappear in a sec as the result of echo $snap_token; in my controller.
I have tried to get them in hidden input, but as I mentioned I cannot get results because I can't change my try code, even I tried to get them after catch part closed, the same thing happens Error.
Question
How can I get my results in controller?
I need to update my database with that results.
Thanks.
From what I can see you have two choices.
Add another client-side AJAX call within the snap.pay function
Redirect the submission of payment-form towards your own app and then do the onward submission from the server-side.
Option 1:
function serverSubmit(d) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$.ajax({
url: '{{url("newroute")}}',
type: "POST",
cache: false,
data: d
});
};
Then amend snap.pay to submit, e.g.
snap.pay(data, {
onSuccess: function(result){
changeResult('success', result);
console.log(result.status_message);
console.log(result);
serverSubmit(result); // <----------
$("#payment-form").submit();
}
...
You may want to encrypt the data if it is sensitive, and you may want to decide not to submit the form if you don't get a successful result from the serverSubmit. You may also want to submit supplemental data beyond the result, but this is a start.
Option 2
Change the <form id="payment-form... action to {{url('newroute')}}
In your controller add a new method and map a post newroute to it.
public function new_method(Request $request)
{
$data = $request->validate(...);
YourModel::create($data); //however you want to save it
$url = 'old_form_submit_URL';
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* There was an error */ }
}

$_POST empty in post Ajax Request

I tried to check the solution in the other similar post on the forum, but I did not resolve my problem yet.
So, I have this Ajax Request in my .js page
JS Code
$(document).ready(function(){
$(document).on('click', '.mySubmitTextButton', function() {
var dataToSend = {};
dataToSend.text = $("#comment").val();
console.log(dataToSend);
$.ajax({
type: "POST",
url: "../submitPages/submitText.php",
data: dataToSend,
dataType: "json",
success: function(result){
console.log(result);
var mediaToClone = $(".rowToCopy").clone();
$(".userId", mediaToClone).html(result.user);
$(".textTweet", mediaToClone).html(result.text);
$(".userAvatar", mediaToClone).attr("src",result.avatar);
mediaToClone.removeClass("rowToCopy hidden");
mediaToClone.appendTo($(".tweetBox"));
},
error: function(result){
console.log(result);
}
});
});
});
PHP Code
if (!isset($_SESSION)) { session_start(); }
include ("../db/db.php");
var_dump($_POST);
if(submitText($_POST["text"], $_SESSION["name"])){ //which is the call to the query function
$propic = getUserPic($_SESSION["name"]);
$result = array(
"text" => $_POST["text"],
"user" => $_SESSION["username"],
"avatar"=>$propic
);
echo json_encode($result);
}
FROM THE BROWSER
Form Data
text: test //This is the Params Tab
//In the response tab
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
'text' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'ccccccccc'</font> <i>(length=9)</i>
</pre>{"text":"ccccccccc","user":"blackout_chisel","avatar":"..\/..\/img\/useravatar\/0826fc411cd2dc627ddd0b0cac0f7fb7.jpg"}
The datas seem to be correctly passed from the js to php (in the browser console I see the parameters correctly passed), but with var_dump($_POST) in the php file, I get an empty array, so I can't use $_POST["text"] in the query case the index is undefined.
Any ideas?
Ok guys, thanks all, I had a misunderstood on it. It works perfectly. I was trying to see the result var_dump($_POST), when the ajax call was already done. That's why it was obviously empty.

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

some precision about the success function of a ajax call

I'm creating a wordpress plugin and I use the wp_ajax_[your action] callback. In my code the php return nothing to the javascript (no echo, no return). If the php return no value, the 'data' in 'success: function(data)' is empty so why the 'click' trigger work?
the js:
$(document).one('click', '#publish', function (event) {
event.preventDefault();
jQuery.ajax({
type:"post",
url: ajaxurl,
data: {action: 'save_img_data', imgUrlsArray: iUrlsArray, imgNamesArray: iNamesArray, pid: pl_vars.post_id},
success: function(data) {
$('#publish').trigger( "click" );
}
});
});
the php:
function lmg29_img_data() {
$pid = $_POST['pid'];
$iUrlsArray = $_POST['imgUrlsArray'];
$iNamesArray = $_POST['imgNamesArray'];
if (isset($iUrlsArray) and isset($iNamesArray)) {
update_post_meta( $pid, 'lg29_urls', $iUrlsArray );
update_post_meta( $pid, 'lg29_names', $iNamesArray );
die();
}
}
add_action("wp_ajax_save_img_data", "lmg29_img_data");
as you can see there's no response:
The HTTP response code is 200, so it's considered a successful request. Actual data in the response is not required.
And, to be clear, functions in JS don't have mandatory arguments. There's no error if you call a function with arguments in its' declaration without any arguments provided.
A failure occurs if the response code is, for example, 400-something or 500-something. Like 404 or 503. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
To see how to set a response code read this:
http://php.net/manual/en/function.http-response-code.php
if you make a POST request, there is no data in success.
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction /*no data argument*/,
error: errorFunction
});
Therefore, success is "called" (and your trigger happens) but data means nothing.

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Categories