Why Ajax successful response is not accessible - php

I have a simple jQuery Ajax post call that works. A product is generated & added to cart.
I did find many answers but none seem to apply here.
But I cannot access the response content (post id) itself in my JS code.
In the code below - in comments - few more trials that I tried to no avail.
What am I missing??
Ajax post request:
jQuery.post(
ts_woo.ajax_url,
{'action': 'do_ts_woo',
'order': orderfilename,
'tilesize': globalTileSize,
'board': urlAtts,
'table': table
},
function(data) {
console.log("type of response="+ typeof data + " string=" + data); // data is a string but does not display it.
var response = jQuery.parseJSON(JSON.stringify(data));
console.log("do_ts_woo. Got id="+response); // undefined & so is response.id
pid = response;
if(pid>0){
//pid = response['id'];
console.log("do_ts_woo. SUCCESS response="+pid);
alert('Add to cart: ' + response.id);
ts_iframe(shopdomain + "/cart/?add-to-cart="+pid);
} else {
// ALWAYS end up here while all was successful...
console.log("do_ts_woo. FAILURE response="+response.id);
}
return false;
}
).done(function(response) {/* alert( "done:"+response );*/})
.fail(function(msg) {alert( "error msg="+msg );})
.always(function(response) {
//console.log("do_ts_woo. ALWAYS respone.id="+response.id); SAME PROBLEM HERE
});
Here is the PHP code
$pid = generate_woo_product("ts-".date("Ymd_His"), $product_price[1], $pimage, $allTable); // PRODUCT is GENERATED
error_log("pid =". $pid);
if ($pid > 0){
error_log ("product pid=".$pid." generated successfully");
echo $pid;
//tried wp_send_json_success($pid);
//tried wp_send_json_success(array('success' => true, 'id' => $pid));
} else error_log("do_ts_woo: FAIL generate_woo_product returned".$pid);
wp_die();

Please, try to use
wp_send_json(['pid' => $pid]);
exit;
instead of echo
And then access your $pid in js with
data.pid
Please, use data.pid without JSON.parse, cause data, in this case, needs to be object
If not - please, consider adding this code to you functions.php
add_action( 'rest_api_init', 'salient_child_rest_api_init' );
function salient_child_rest_api_init() {
register_rest_route(
'namespace/v1',
'/example',
[
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'salient_child_process_example_endpoint',
]
);
}
function salient_child_process_example_endpoint() {
// your logic ...
$data = [
'pid' => 1
]; // example data for testing if it is working
return new WP_REST_Response( $data, 200 );
}
And change your jQuery.post with this
jQuery.post(
{
url: `${document.location.origin}/wp-json/namespace/v1/example`,
data: {
'action': 'do_ts_woo',
'order': orderfilename,
'tilesize': globalTileSize,
'board': urlAtts,
'table': table
},
xhrFields: {
withCredentials: true
}
})
.done(function (data) {
const pid = data.pid;
if (pid > 0) {
console.log("do_ts_woo. SUCCESS response=" + pid);
alert('Add to cart: ' + response.id);
ts_iframe(shopdomain + "/cart/?add-to-cart=" + pid);
} else {
console.log("do_ts_woo. FAILURE response=" + response.id);
}
return false;
})
.fail(function (msg) {
alert("error msg=" + msg);
})
.always(function (response) {
});
If not - maybe there are PHP warnings modifying your response output with enexpected messages and breaking your response data.

Related

how to put value on progress bar when data is huge in php/laravel?

I want to show a progress of data processed (in backend )on progress bar (on front).
For this 2 things am doing,
1] Sent one request to get session variable
interval = setInterval(function () {
$.getJSON('/importProgress', function (data) {
$('#putProgressPercent').html(data['progressPercent'] + "%");
$('#putProgressPercentMessage').html(data['progressMessage'] );
$("#progressBarLine").css("width", data['progressPercent'] + "%");
if (data['progressPercent'] == 100) {
clearInterval(interval);
$("#loaderModal").hide(); // hide div
}
});
}, 1000);
Initially will get 0, but when other (below) request is processing will get percentage
2] Send other request for data submission on backend side (in my case with for loop) like below
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "/storeData",
type: "post",
data: {
'someValue': someVaribaleToProcress,
},
success: function (response) {
var returnDetails = jQuery.parseJSON(response);
if (returnDetails['error']) {
alert(returnDetails['error']);
return false;
}
},
error: function (jqXHR, textStatus, errorThrown) {
clearInterval(interval);
}
});
and on back side this processes as below :
$chunksData = array_chunk($myData,3);
foreach ($chunksData as $index => $oneChunkData) {
foreach ($oneChunkData as $oneIndex => $details) {
$isImported = ImportData::addImportData($variables_1, $variables_2);
}
$parsedChunk += sizeof($oneChunkData);
$completedPercent = (round(($parsedChunk * 100) / sizeof($getTempTableData)));
echo $completedPercent. " : is percent <br>";
session()->put('importProgress', $completedPercent);
session()->save();
}
}
This $myData is huge. (suppose 1k now).
Now the problem is until this above for loop (of putting data in db) is completed, the interval hits are in pending state. so not getting updated with data.
even above line of printing percentage (echo $completedPercent. " : is percent";) is also not printing output until all data is processed.
can someone give me solution for this?

POST admin-ajax throwing error 400 - not finding custom functions

I am adding a function that should be called when a button is clicked, i have a js file with the following jquery code and the ajax call :
jQuery(document).ready( function() {
function getUrlParameter(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
jQuery('#upload_btn').click( function(e) {
e.preventDefault();
var flag = true;
var postId = getUrlParameter('preview_id');
var files = jQuery('#file_tool').prop('files');
console.log(files);
var dataS = {
'action': 'upload_button',
'preview_id': postId,
'files': files,
'set': flag
}
jQuery.ajax({
type : 'post',
url : diario.upload,
processData: false,
contentType: false,
data : dataS,
success: function(response) {
if(response.type == "success") {
console.log('jquery works');
} else console.log(response);
}
});
});
});
When i click the button the console.log shows the files obj so at least the onClick works, but just after that it shows up jquery.js:4 POST custom/wp-admin/admin-ajax.php 400. This is how my functions.php looks like :
add_action( 'wp_enqueue_scripts', 'enqueue_onClick_upload' );
//custom_js_enqueuer
function enqueue_onClick_upload() {
wp_register_script( 'onClick_upload', WP_CONTENT_URL.'/themes/microjobengine/onClick_upload.js', array('jquery') );
wp_localize_script( 'onClick_upload', 'diario', array( 'upload' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'onClick_upload' );
}
add_action('wp_ajax_upload_button', 'upload_button');
add_action('wp_ajax_nopriv_upload_button', 'upload_button');
// upload button function
function upload_button() {
$postID = $_POST['preview_id'];
if ($_POST['set']) {
if($_POST['files']['size'] === 0 )
echo "<script>console.log('There's no images.');</script>";
}
$result['type'] = 'success';
echo json_encode($result);
wp_die();
}
I have no idea why it doesn't find the action, it's all done as wp says it should, I hope somone could give a hand, thanks.
--EDIT--
Okay so now i tried to only pass 'action': 'upload_button', the error does not appear but the response doesn't get success, I did this with all the code inside my function commented and just leaving the las 3 lines, in order to return the success, but it doesn't, so it might find the function but for some reason it doesn't get performed, and of course that means something wrong happens when i pass the extra data, any thoughts about why this happens?
Sorry i wasn't getting the right thing to get feedback from the functions, i just had to delete all echos and save everything i needed into an array and returne it json encoded.

Phonegap returns object Object but echo correct data

I'm making a phone app using PhoneGap with PHP on the server side. the Login function has been working fine, but AJAX returns an error [object Object] while PHP returns the correct value's in JSON.
it's for making a phone app for an existing website and using its database.
the data my PHP prints is correct yet I receive an error response from ajax.
Alert(response)
Gives an [object Object] return value on error
whenever I try
alert(response.val)
I strangely get undefined, but in the network, I can see the printed data is correct in JSON.
{{"user_id":"390","response":"Success"}}
but when I look in the console on my browser I see an unexpected error.
Unexpected parameter ':'
my ajax function is as follows
$(document).ready(function () {
$("#btnLogin").click(function () {
var gebr = $("#login_username").val().trim();
var pass = $("#login_password").val().trim();
var dataString = "username=" + gebr + "&password=" + pass + "&login=";
var msg = "";
$("#message").html("Authenticating...");
if (gebr != "" && pass != "") {
$.ajax({
type: "POST",
data: dataString,
dataType: "json",
//contentType: "application/javascript",
crossDomain: true,
url: "http://url/page/app/index.php?&jsoncallback=?",
headers: "application/json",
success: function (response) {
var user_id = response.user_id;
var success = response.response;
localStorage.setItem("user_id", user_id);
window.location = "home.html";
alert("login successfull");
},
error: function (response) {
$("#message").html("error..");
alert(response);
}
});
} else {
msg = "Please fill all fields!";
$("#message").html(msg);
}
return false;
});
PHP
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$gebruikersnaam = $_REQUEST['username'];
$wachtwoord = md5($_REQUEST['password']);
$user = [];
//if user and password are filled
if (!empty($gebruikersnaam) && isset($wachtwoord)) {
//checks if user_id has been found
if (!$found_user_id) {
$msg = "user not found!";
print json_encode($msg);
} else {
if (($gebruikersnaam == $user['gebruikersnaam'] && $wachtwoord == $user['wachtwoord']) && ((!empty($user['single_allowed_ip_address_for_login']) && $user['single_allowed_ip_address_for_login'] == $_SERVER['REMOTE_ADDR'])|| empty($user['single_allowed_ip_address_for_login']))) {
//responds with this data
$user_id = $user['user_id'];
$response[] = array(
'user_id' => $user_id,
'response' => 'Success'
);
print json_encode($response);
} else {
$msg = "user is incorrect";
print json_encode($msg);
}
}
}
I have been wanting to get a successful response and saving the user_id in local storage so it can be used on a different page.
Edit:
after using console.log on the response i got an odd object.
​
abort: function abort()​
always: function always()​
catch: function catch()​
done: function add()​
fail: function add()​
getAllResponseHeaders: function getAllResponseHeaders()​
getResponseHeader: function getResponseHeader()​
overrideMimeType: function overrideMimeType()​
pipe: function pipe()​
progress: function add()​
promise: function promise()
​
readyState: 4
​
setRequestHeader: function setRequestHeader()​
state: function state()
​
status: 200
​
statusCode: function statusCode()
​
statusText: "load"
​
then: function then()​
<prototype>: {…
which is strange because none of these functions are made and the only thing which i can recognize is the statuscode.
You need to correct your JSON. {{"user_id":"390","response":"Success"}} is not valid JSON. It needs to be {"user_id":"390","response":"Success"}.
You're getting a strange object in your console.log because your response in the error: function (response)... is actually the jqXHR jQuery object and will not return your response directly in its arguments. Stick with success: function(response)... and output whatever your server sends back.

Laravel Ajax - success executed even when db row is not present

I'm working on a project where I have some jQuery code that is supposed to check if a certain row in the database exists. If the row does exist, The code within the success stage gets executed. But the problem I have with this script is when the 'checkdb' function gets executed the code within success happens even though the row doesn't exist in the database. What is causing this?
jQuery code
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);
The jQuery above gets executed every minute, To check if the row is present.
The PHP code below is supposed to check if the row in the database exists. If it does, it should return a response which then ends up in the succeeding stage in jQUery. If it does not already exist, Do something else
PHP code
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing');
}
}
Why is it executing the succeeding stage even though the row does not already exist? Thanks in advance
response('content', 200, $headers) and `json()` helper also takes three param `json($data, status, $headers)`
methods take three parameters replace the content of the else
like
public function getAll(Request $request, $id)
{
$droplet = Droplet::where("webshop_id", "=", $id)->exists();
if ($droplet != null) {
$info = Droplet::where("webshop_id", "=", $id)->get();
return response()->json(array($info));
} else {
return response()->json('There is nothing',404);
}
}
In jQuery, success block gets executed when response status code is 200. If you send status code as 404 which is in else block when DB is not exist, then error block will get executed instead of success. Laravel by default will send 200 as status code for AJAX requests in response.
Add dataType:"JSON"
checkdb = function () {
$.ajax({
type: 'GET',
url: '/droplet/get/' + {{ $webshop->id }},
data: '_token = <?php echo csrf_token() ?>',
datatype:'JSON',
success: function(data) {
var id = setInterval(frame, 500);
function frame() {
console.log('Executing "Frame"');
if (width2 >= 30) {
clearInterval(id);
clearInterval(mainInterval);
installWebshop();
alert('This is done');
} else {
width2++;
elements(width2);
}
}
},
error: function(data) {
alert('Something went wrong' . data);
}
});
console.log('Executing "checkDB"');
};
mainInterval = setInterval(checkdb,1000 * 60);

call rest api service from jquery

I am trying to understand restful services.i can create a class and define a function into this but when i call it through jquery it return null and when i call directly by typing url in address bar it return a json response
this is the code
class Api extends REST
{
public function processApi()
{
$func = strtolower(trim(str_replace("api/","",$_REQUEST['request'])));
if((int)method_exists($this,$func) > 0)
{
$this->$func();
}
else
{
$this->response('',404); // If the method not exist with in this class, response would be "Page not found".
}
}
private function json($data)
{
if(is_array($data))
{
return json_encode($data);
}
}
public function demo()
{
$error = array('status' => '200', "msg" => "OK");
$this->response($this->json($error), 200);
}
}
$api = new Api;
$api->processApi();
i just want to call demo method from jquery.this is what i am trying
$.post("db/api/demo",
function(data,status){
data = jQuery.parseJSON(data);
alert("Data: " + data + "\nStatus: " + status);
});
i am getting response through jquery when demo method is this
public function demo()
{
$error = array('status' => '200', "msg" => "OK");
echo json_encode($error);
//$this->response(json_encode($error), 200);
}
You should send datatype to server.
Try this code:
$.post( "db/api/demo")
.done(function( data ) {
$.each(data, function(index, element) {
alert('Data: ' + element.data + ' Status: ' + element.status);
});
}, "json");

Categories