This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 1 year ago.
this is my code:
<script>
jQuery(function() {
jQuery.getJSON('lessons.json', function(data) {
var lessonID = data.t["sfwd-lessons"];
$.each(lessonID, function(i, val) {
lessonID = val;
console.log(lessonID);
})
});
});
</script>
I get a list of IDs that I can use for different curl api call.
So, what's the best way to pass these jquery variables to PHP for an api call?
It should be something like this:
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://website.com/wp-json/ldlms/v2/sfwd-lessons/'.lessonID,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$token.'',
'Cookie: cookie'
),
));
Thank you all.
There are three steps: (1) Retrieving DOM data: inputs, textarea, etc, (2) Sending via AJAX, (3) Retrieving it in PHP:
1 - DOM Data with jQuery: build a single object (easier to send)
let myData = {
name: $('#name').val(),
description: $('#description').val(),
...
}
2 - Send it via Ajax:
jQuery.ajax({
data: myData,
url: PHPurl,
type: "post",
method: "POST",
success: function (response) {
// whatever
},
error: function (e) {
// whatever
}
});
3 - Retrieve it in PHP
$name = isset($_POST['name']) ? $_POST['name'] : '';
$description = isset($_POST['description']) ? $_POST['description'] : 'default description';
... more data
Now if you need to make a cURL call using that data, you have two options:
Pass an array and use header Content-Type 'multipart/form-data':
$data = array(
'name' => $name,
'description' => $description,
...
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
Or encode the same array as json, and use header Content-Type 'application/json':
$data = array(...);
$data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
---- EDIT
(Relative to your question below) I see you read a 'lessons.json'. So you get a list of lessons from there. In that case you need to keep the relation between each lesson object, and the DOM elements. For example:
for(let lesson of lessons) {
// Create your HTML inputs to edit the lesson
let container = $("<div class='lesson-editor'></div>");
container.append(...);
container.append(...);
// Now add a reference to the ID of the lesson
container.attr("lessonId", lesson.ID);
}
Now you have an editor for each lesson, and each "container" has the ID of the lesson it's editing.
Later in Javascript, when you want to build your list of lessons and send it with AJAX:
let lessons = [];
let containers = $(".lesson-editor");
containers.each(function() {
let ID = $(this).attr("lessonId");
let lesson = {
ID: ID,
name: $(this).find("#nameInput"),
description: $(this).find("#descInput"),
....
}
lessons.push(lesson);
});
// -> ajax, data: { lessons: lessons }
Then remember that in PHP you have $_POST['lessons'] that is an array of objects (associative arrays).
Related
I have added an extra action to the recordlist view;
custom/modules/Opportunities/clients/base/views/recordlist/recordlist.js:
({
extendsFrom: 'RecordlistView',
initialize: function(options) {
this._super("initialize", [options]);
//add listener for custom button
this.context.on('list:opportunitiesexport2:fire', this.export2, this);
},
export2: function() {
//gets an array of ids of all selected opportunities
var selected = this.context.get("mass_collection").pluck('id');
if (selected) {
return App.api.call('read',
App.api.buildURL('Opportunities/Export2'),
{'selected_ids':selected},
{
success: function(response) {
console.log("SUCCESS");
console.log(response);
},
error: function(response) {
console.log('ERROR');
console.log(response);
},
complete: function(response){
console.log("COMPLETE");
console.log(response);
},
error: function(response){
console.log("ERROR");
console.log(response);
}
});
}
},
})
The tutorial here
http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.7/Integration/Web_Services/v10/Extending_Endpoints/
Explains how to create an endpoint.
However it doesn't explain how to get the json data (the stringified array of selected ids);
custom/modules/Opportunities/clients/base/api/OpportunitiesApi.php:
class OpportunitiesApi extends SugarApi
{
public function registerApiRest()
{
return array(
//GET
'MyGetEndpoint' => array(
//request type
'reqType' => 'GET',
//set authentication
'noLoginRequired' => false,
//endpoint path
'path' => array('Opportunities', 'Export2'),
//endpoint variables
'pathVars' => array('', ''),
//method to call
'method' => 'Export2',
//short help string to be displayed in the help documentation
'shortHelp' => 'Export',
//long help to be displayed in the help documentation
'longHelp' => 'custom/clients/base/api/help/MyEndPoint_MyGetEndPoint_help.html',
),
);
}
/**
* Method to be used for my MyEndpoint/GetExample endpoint
*/
public function Export2($api, $args)
{
//how to access $args['selected_ids']?
}
}
$args contains
Array
(
[__sugar_url] => v10/Opportunities/Export2
)
Is it possible to access the json data?
I did the same but my rest api was coded in java. I used java #Path annotation to annotate my get method. I then deployed above rest api code to a server(Tomcat in my case). Starting the server and then hitting the URL formed by the #Path will give you the json data on the browser.
The solution was to change the call method to create and the endpoint method to POST; $args now contains
Array
(
[selected_ids] => Array
(
[0] => 0124a524-accc-11e6-96a8-005056897bc3
)
[__sugar_url] => v10/Opportunities/Export2
)
PUT vs POST in REST - I was using GET because I didn't plan to change anything, but the body is typically ignored in a GET request.
Currently I am using plugin called jQuery TagHandler. How can I link with database to listout data. I have listed code samples below. Below code are not working. Please correct me.
js
$("#array_tag_handler").tagHandler({
getData: { id: '1', type: 'user' },
getURL: '/tag/interest',
updateData: { id: 'user234', type: 'user' },
updateURL: '/ajaxtest/update',
autocomplete: true,
autoUpdate: true
});
PHP
$select_pos = "SELECT title FROM homegrid";
$select_exec = mysql_query($select_pos);
$return_data = array();
while($dataFromDB = mysql_fetch_assoc($select_exec)) {
$return_data[]= array(
"title" => $dataFromDB['title'],
);
}
header('Content-Type: application/json');
echo json_encode($return_data);
I have removed keys from my response {"availableTags":[{"title":"Music"},{"title":"Reading"}]}
Now the response look likes {"availableTags":["Music","Reading"],"assignedTags":["Music","Reading"]}
I'm trying to do an AJAX POST request to an external domain from a post metabox in WordPress.
I know that it's not possible to do it directly because of cross domain access errors. As far as I know it's also not possible to do it simply by using PHP code like
if ( isset ( $_POST( 'button_name' ) ) ) { .. }
since all the metaboxes are inside the wordpress post form.
So this is what I came up with:
I use the wp_localize_script() function to make the php variables available in the js-file (this works). The localized variable is ajax_request_args.
The javascript file looks like this:
jQuery(document).ready(function($) {
$('#button').click( function() {
$.ajax({
type: "POST",
url: php_post.php,
data: ajax_request_args,
success: function(data) {
alert(data["success"] + " " + data["code"]);
},
dataType: 'json'
});
});
});
The php_post.php looks similar to this:
if (is_ajax()) {
...
if (isset($_POST["arg_1"]) && !empty($_POST["arg_1"])) {
$response = wp_remote_post( $external_url, array(
'method' => 'POST',
'body' => $args,
'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
'timeout' => 90,
'blocking' => true
) );
$return = $_POST;
$return['success_message'] = $response['success_message'];
$return['code'] = $response['code'];
$return["json"] = json_encode($return);
echo json_encode($return);
}
}
The AJAX request works without the POST request in the php file, for example when I set
$response['success_message'] = 'success';
$response['code'] = '1234';
and delete the wp_remote_post()part.
The POST request to the external domain also works when I call it directly using a button click like
<?php
if (isset( $_POST['test-maintenance-btn'])){
...
$response = wp_remote_post( $external_url, array(
'method' => 'POST',
'body' => $args,
'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded' ),
'timeout' => 90,
'blocking' => true
) );
}
?>
<form method="post">
<input type="submit" id="test-btn" name="test-btn" value="<?php _e('Execute', 'textdomain'); ?>">
</form>
The weird thing is that it doesn't work in connection. The Javascript should post to the php file which posts to the external server and returns the result to the ajax post request.
When I try to do the wp_remote_post (even if I don't use the result) I always get "NetworkError: 500 Internal Server Error" in the console.
Could you help me find the problem and help me with the correct approach? Thanks in advance for your help.
Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});
I have a function which sends specified form data to a php processing page.
function get(){
$.post('data.php',{"name":$('#Fname').val(),"age":$('#age').val()},
function(output){
$('#Rage').hide().html(output).fadeIn(1000);
});
}
After posting the script takes all the outputs from the php page (ie: echo's) and puts them all the in #Rage div. $('#Rage').hide().html(output).fadeIn(1000);
I am wondering is it possible to have two different outputs for each of the inputs.
By this i mean an echo response for "name":$('#Fname').val() goes to #Rname and an echo response for "age":$('#age').val() goes to #Rage.
I hope i have explained myself well enough.
Cheers guys.
You could have your PHP script return some JSON with those keys, and in the callback function, assign the values to their respective elements.
Say you had the PHP script return this:
header('Content-type: application/json');
$return_obj = array('age' => 'someAge', 'name' => 'someName', 'success' => true);
echo json_encode($return_obj); //{"age": "someAge", "name": "someName", "success":true}
You could do this on the client side:
$.ajax({
url:'data.php',
type:'POST',
data: {"name":$('#Fname').val(),"age":$('#age').val()},
dataType: 'json',
success:function(json) {
if(json.success) {
$('#age').val(json.age || '');
$('#Fname').val(json.name || '');
}
}
});