I am the beginner, so do not have much experience.
The task is to translate the blocks of text the user writes.
So html-file:
<script type="text/javascript">
$('#some_id').on('click', function(){
var text_var = JSON.stringify("{$text_without_adv}");
var own_script = 'gTApi.php';
$.ajax({
method: 'post',
url: own_script,
data: $.parseJSON(text_var)
}).done(function(data) {
console.log(data);
});
});
</script>
php-file "gTApi.php" (where the magic happens):
<?php
require_once "../../vendor/autoload.php";
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$text = file_get_contents('php://input');
$apKey = '**************************';
$client = new Client(
array(
'headers' => array(
'Accept' => 'application/json'
)
)
);
try {
$response =$client->get('https://translation.googleapis.com/language/translate/v2?key='
. $apKey
. '&source=en&target=es&q=' . $text);
} catch (\Exception $e) {
echo $e->getMessage();
}
$response_body = json_decode($response->getBody(), true);
echo $response_body['data']['translations'][0]['translatedText'];
another php-file:
$smarty->assign('text_without_adv', htmlspecialchars((implode(' ', $text_array))));
after the page loads I get unexpected token after the first sentence in variable $text_without_adv and can't do the translation, nothing happens when I click the button.
For example:
var text_var = JSON.stringify ("
But she had a sweetheart, and he said he would go and get the ball. ///token/// So he went to the park gate, but 'twas shut; so he climbed the hedge, and when he got to the top of the hedge, an old woman rose up out of the dyke before him, and said, if he wanted to get the ball, he must sleep three nights in the house. He said he would.");
But the main question is that there can be no errors in other posted texts from other users. I can't understand, 3 different texts from 3 different users have unexpected token, then the next 2 have no error, then the next one has the error and so on. Where could be the problem?
In this case you don't need to pass a json instead just pass a post data
To do that
First change this line
// to stored your php variable in a js variable
var text_var = "<?php echo $text_without_adv; ?>";
then
in your ajax
$.ajax({
method: 'post',
url: own_script,
data: {
// just use the declared js variable above which contains your php variable at the first place
text: text_var
}
}).done(function(data) {
console.log(data);
});
and in your php
instead of
$text = file_get_contents('php://input');
change to
$text = $_POST['text'];
so your code would be like this
JS
<script type="text/javascript">
$('#some_id').on('click', function(){
var text_var = "<?php echo $text_without_adv; ?>";
var own_script = 'gTApi.php';
$.ajax({
method: 'post',
url: own_script,
data: {
text: text_var
}
}).done(function(data) {
console.log(data);
});
});
</script>
PHP
<?php
require_once "../../vendor/autoload.php";
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$text = $_POST['text'];
$apKey = '**************************';
$client = new Client(
array(
'headers' => array(
'Accept' => 'application/json'
)
)
);
try {
$response =$client->get('https://translation.googleapis.com/language/translate/v2?key='
. $apKey
. '&source=en&target=es&q=' . $text);
} catch (\Exception $e) {
echo $e->getMessage();
}
$response_body = json_decode($response->getBody(), true);
echo $response_body['data']['translations'][0]['translatedText'];
Related
I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it
My JavaScript always returns an error, even if PHP did what it should.
No matter if I write dataType: "JSON" or "JSONP" or delete it completely.
When I remove echo json_encode(... it works as it should. I see the alert for success.
But I want to make two or three success messages appear in-line in html.
Here is my JS code:
jQuery(document).ready(function($){
$('#przypinanie').click(function() {
var data_cat = $('select#cat').val();
var data_post_id = $('input#przypinanie-post-id').val() ;
var przypinanie = $('input#przypinanie').val();
$.ajax({
url: ajaxurl,
data: {
cat_id: data_cat,
post_id: data_post_id,
przypinanie_usuwanie: przypinanie,
action: "przypinanie_php"
},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
},
});
});
My PHP code:
if ( $przypinanie == "PRZYPNIJ" ) {
$validate = $wpdb->get_var("SELECT przypieta_cat_id FROM polecane_przypinane WHERE przypiety_post_id = '$post_id'");
if ( isset($validate) ){
$msg = 'Wpis jest już przypięty do kategorii '. $validate ;
}else{
$wpdb->insert( 'polecane_przypinane',
array(
'przypiety_post_id' => $post_id,
'przypieta_cat_id' => $cat_id,
)
);
$msg = 'Wpis został przypięty do kategorii '. $validate ;
}
$responce = $msg;
}
header('Content-type: application/json');
echo json_encode($responce);
OK. Thank You for answers.
I resigned from JSON and I just did echo $responce; at the end of function.
Pleased to solwed my first question here.
here is my simple code
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
Here i am sending request to action.php
and if in action.php i have echo two variables separately for example.
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs.
i hope you guys help me. thanks.
Send the responses as JSON.
In PHP
$return = array( $return_value, $return_value2 );
echo json_encode($return);
In Javascript
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
your could return a json from action
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
then in your js,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
You need to use json_encode in order to get multiple records or data.
action.php
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
and then read your variables in JS
dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
You can use json_encode to create an object like:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
Then add dataType: 'json' to your ajax options. The response then will be an object like:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
Where you can access the specific values with e.g. response.return_value2 and thus separate them.
In my project am using ajax for sending message the problem is i can't get the response in the ajax function the function works perfectly before,Can't find exact cause of the issue help me to solve it
ajax
var str = {
message:message, department_id:department, email:email, username:name
};
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage',
dataType:"json",
data: str,
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
php controller
function savemessage() {
extract($this->input->post());
$data['message_id'] = $this->session->userdata('msgid');
$data['username'] = $username;
$data['email'] = $email;
$data['department_id'] = $department_id;
$data['message'] = $message;
$data['datetime'] = date('Y-m-d H:i:s');
$data['status'] = 'new';
$data['message_by'] = '1';
$this->db->insert('message', $data);
echo json_encode($username);
exit;
}
I cant get the response in it help me to solve it
You use ajax to communicate with a PHP script, inside the PHP script you could have the content of the function you want to execute. For example in your code:
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage.php',
dataType:"json",
data: {myData:str},
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
Then, on the server side the php script "savemessage.php" would receive the POST action, so you could have:
if(isset($_POST['myData']) && !empty($_POST['myData'])) {
$obj = $_POST['myData'];
//rest of your code
echo json_encode($username);
exit;
}
However from your code I cannot see $username defined, so that probably would return an error.
I am using Osclass classified script, trying to alert a message returned by ajax call.
My ajax-test.php file which is saved in my theme folder contains
<?php
$name = $_GET["name"];
echo "I am " . $name
?>
and my JavaScript function code is
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
// url: "oc-content/themes/bender/ajax-test.php",
url: 'http://127.0.0.1/osclass/index.php?page=ajax&action=custom&ajaxfile=ajax-test.php',
data: { name : name },
success: function (data) {
alert(data);
},
})
}
Anybody tell me what am I doing wrong? it alerts
{"error" => "ajaxFile doesn't exist"}
Note: It works fine with commented line of code
You are using
> method: "POST",
in ajax then why are you using GET ?
$name = $_GET["name"];
Using Post to getting value for it.
$name = $_POST["name"];
Unfortunatelyn, that's not exactly how the ajax.php custom action works.
First, page=ajax&action=custom doesn't work with themes, only with plugins since it will search ajaxfile inside the plugins folder by doing something like this:
$filePath = osc_plugins_path() . $ajaxfile; // eg. /oc-content/plugins/$ajaxfile
You then have to pass in ajaxfile the name of the plugin to work. If you were using the Madhouse Messenger plugin, you would do something like:
page=ajax&action=custom&ajaxfile=madhouse_messenger/main.php
However, since 3.3, when using page=ajax&action=custom, you do not use the ajaxfile param anymore but the route param. You can take a look at how routes work here and some examples of routes here.
in your theme functions.php
add something like this:
//name of your custom ajax request
$my_custom_ajax_request_name = 'doSomethingCool';
osc_add_hook('ajax_' . $my_custom_ajax_request_name, $my_custom_ajax_request_name);
function doSomethingCool()
{
// set default response
$response = [
'status' => false,
'msg' => 'Default Error Message...',
];
// token protection
// read more about csrf token:
// https://dev.osclass.org/2013/02/19/make-your-plugins-more-secure-with-anti-csrf-functions/
osc_csrf_check();
// get request parameters
$param1 = Params::getParam('param1');
$param2 = Params::getParam('param2');
// do some logic here ex: check if user is logged in
if (osc_is_web_user_logged_in()) {
$response['status'] = true;
$response['msg'] = 'User is logged in. ;-) ' . $param1 . ' ' . $param2 . '! ' . osc_logged_user_name();
} else {
$response['status'] = false;
$response['msg'] = 'User is not logged in. :-(';
}
// return json response
header('Content-Type: application/json');
echo json_encode($response);
exit;
}
some where in your template files like header.php, footer.php or everything else you need it...
<a data-param1="hello" data-param2="world" href="#" id="make-an-ajax-request">
Make an AJAX Request!
</a>
<script>
//here we hold some usefull info for easy access
var mySite = window.mySite || {};
mySite.base_url = '<?php echo osc_base_url(true); ?>';
mySite.csrf_token = '<?php echo osc_csrf_token_url(); ?>';
$(function(){
$('#make-an-ajax-request').on('click', function(e){
e.preventDefault();
// name of our custom ajax hook
var ajax_hook = 'doSomethingCool';
// get parameters
var param1 = $(this).data('param1');
var param2 = $(this).data('param2');
// build axjxa url
var url = mySite.base_url + '?page=ajax&action=runhook&hook='+ajax_hook+'&'+mySite.csrf_token;
//build data
var data = {
param1 : param1,
param2 : param2
};
$.ajax({
type: 'POST',
dataType: 'json',
data: data,
url: url
}).done(function (data) {
console.log(data);
if (data.status) {
} else {
}
});
});
});
</script>
OSCLASS WAY
to note that the current osclass way of doing an ajax request from a theme page is to call the
http://example.com/?page=ajax&action=runhook&hook=MY_HOOK_FUNCTION_NAME
and register it like osc_add_hook('ajax_MY_HOOK_FUNCTION_NAME',
'MY_HOOK_FUNCTION_NAME'); optionally but very recommended is the use
of the csrf token that you can implement like i have done for url or
by calling the osc_csrf_token_form() directly into your form.
NON OSCLASS WAY
just create a file in your theme or everywhere you want and make sure to put this into it <?php require_once __DIR__ . RELATIVE_PATH_TO_OC_LOAD_FILE . 'oc-load.php'; ?> then build your logic into it.