print alert box in response to a ajax call in yii2 - javascript

I have this jquery code in my view file
$('#ticket-ticket_impact_id').change(function() {
var priority = $('#ticket-ticket_priority_id :selected').val();
var impact = $('#ticket-ticket_impact_id :selected').val();
if ($('#ticket-ticket_priority_id').val() == '' || $('#ticket-ticket_impact_id').val() == '') {
} else {
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' + priority + '&ticket_impact_id=' + impact);
}
})
$('#ticket-ticket_priority_id').change(function() {
var priority = $('#ticket-ticket_priority_id :selected').val();
var impact = $('#ticket-ticket_impact_id :selected').val();
if ($('#ticket-ticket_priority_id').val() == '' || $('#ticket-ticket_impact_id').val() == '') {
} else {
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' + priority + '&ticket_impact_id=' + impact);
}
})
from here the value the of priority and impact id is sent to the controller/ajax function
public function actionAjaxTicketSla(){
$ticket_priority_id=$_REQUEST['ticket_priority_id'];
//var_dump($ticket_priority_id);die();
$ticket_impact_id=$_REQUEST['ticket_impact_id'];
if(Sla::find()->where(['ticket_priority_id'=>$ticket_priority_id,'ticket_impact_id'=>$ticket_impact_id])->exists())
{
} else{
echo '<script type="text/javascript">alert("No sla defined!");</script>';
}
}
I am not able to even echo something in response here don't know whats wrong here any help would be appreciated.
response

You are mixing POST , GET and REQUEST
in ajax you use a POST but don't send nothins as POST param
instead you pass param in url as GET params
and in action you look for REQUEST but not for GET (or post)
And you access directly to the $_REQUEST instead of using yii2 method for this
You should rethink you code ..
anyway just as a first step
looking to your ajax call you could use the param you pass as get param
public function actionAjaxTicketSla(){
$request = Yii::$app->request;
$get = $request->get();
$ticket_priority_id=$get['ticket_priority_id'];
//var_dump($ticket_priority_id);die();
$ticket_impact_id=$get['ticket_impact_id'];
if(Sla::find()->where(['ticket_priority_id'=>$ticket_priority_id,'ticket_impact_id'=>$ticket_impact_id])->exists())
{
echo 'OK';
} else{
echo 'No sla defined';
}
}
and in client post
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' +
priority + '&ticket_impact_id=' + impact,
function(data){
if (data !='OK') {
alert(data);
}
});

Try Echo in the If condition also and share the "response" (of page) from Network console.

Sending javascript code from the PHP server to js isn't a good practice. What you are doing is essentially making a call to the server and sending it the data and not doing anything with the resposne you've received.
Try to create a proper callback function like shown in this example,
Add a callback function (AJAX is Asynchronous, so your return is being hit before there is any data to return):
function returnData(param) {
console.log(param);
}
Now add that callback function as a parameter to your AJAX function, and lets run it:
function getCartProduct(id, callback){
$.post('sever.php',
function(data){
callback(data);
});
}
getCartProduct(id, returnData);
Also the server's response is treated as a string in javascript. To evaluate it as a javascript syntax, pass the string into the eval() method.
eval('alert("this works");');

Related

how do i send javascript variables to PHP and return the results

I have a form with inputs (each with ID param,param1,param3 respectively) and an external php file with a function called getform() that takes three parameters from the form (param, param1, param3 respectively).
A text feild with id results to display the response from php file.
I have placed onclick function on param3.
I need whenever a user types something in param3 it should be sent to php file and the results displayed in the text filed of id results.
here is my code
<script>
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.post('curencyconvert.php', {
postparam: param,
postparam2: param2,
postparam3:param3
}, function(data){
$('#results').html(data);
});
}
</script>
my php function in the php file
function Conv($param,$param2,$param3){
//my code here
return $output;
}
if(isset($_POST)){
//Calling the defined function here
Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Add these line below your function code.. and better echo the output in your function instead of returning it.
jQuery(document).ready(function($) {
$('#param3').change(function() {
// put here the code //
} );
})
What errors you get in Console(firbug)?
As stated by other answers $_POST should be used.
What your php code returns if it returns an array or returns an object It can not be put into the Input. Return value must be a
string
PHP code must be :
function Conv($param,$param2,$param3){
//my code here
// take particular field of the DB results or resultset that you want to show in the input.
return $output['name'];
}
I know answer is incomplete because your question is incomplete.
Please let me know errors from the console so that i can help you further
echo instead of return.
if(isset($_POST)){
echo Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Do something like this, it is more clean:
Conv($param, $param2, $param3){
// your code here
return $output;
}
As for the javascript part, jquery ajax is your friend
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.ajax({
url: '/path/to/file',
type: 'POST',
data : { postparam: param, postparam2: param2, postparam3: param3 },
}).done(function(data) {
$('#results').html(data);
});
}

response from php to javascript via json

I have this function in php
public function get_updated_session_value()
{
$sql = "SELECT IF(Session = 12345678 , 1,0) AS login FROM `psf_users` WHERE id = 236";
$var = $this->addDb($sql)->execute();
$Session = $var['login'];
return json_encode('2');
}
and the javascript code to fetch this value,
function check() {
$.ajax({
url : 'auctions.php',
type : 'get',
// dataType: 'json',
data : {page:'__request', module:'PSF_auctions', action:'get_updated_session_value'},
success: function(data) {
console.log(data);
}
});
}
also, this function runs every 5 seconds via
setInterval(check, 5000);
the problem is, console.log(data); prints nothing, i believe that means it is not getting any data (or json response) from the php function. am i missing something?
It can't work as you're returning the value. The difference between returning a value and emitting a response is that the latter writes a response on the HTTP stream whilst the first one merely returns the control to the parent with a specific value.
Sanjay has spotted it very well, and I'd recommend that you use a very simple function to wrap up your responses:
function emit_response( $status_code, $data ) {
http_response_code( $status_code ); // 200 is it's success. find more http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
die( json_encode( array(
"status_code" => $status_code,
"data" => $data )));
}
Then modify that echo (though it's fine as well) with
emit_response( 2 );
and since the response is valid JSON, JavaScript will love it; in your callback, you can simple do this:
success: function(res) {
var response = JSON.parse( res );
// response.data will be 2. :)
// ... rest of the code ...
Replace return with echo like this:
public function get_updated_session_value()
{
$sql="SELECT IF(Session = 12345678 , 1,0) as login FROM `psf_users` WHERE id=236";
$var= $this->addDb($sql)->execute();
$Session= $var['login'];
echo json_encode('2');
}

Can't set new value for variable

I'm possibly missing something that is very obvious, but I'm not getting nowhere with this problem.
I'm simple trying to set a value of a variable after getting the value from a json feed.
I'm using jquery to get a jsonp feed and then store the value in a variable that I can use later, but its not working and the value doesn't get stored. If I console.log the value it returns it.
jQuery(document).ready(function($){
serverip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
stream_domain = "";
$.ajax({url: 'http://load.cache.is/inspired.php?ip=' + serverip, dataType:'jsonp',
success: function(data){
$.each(data, function(key, val) {
if (key == serverip){
stream_domain = val;
console.log("val: " + val);
}
});
}
});
console.log(stream_domain);
});
Here is the same code on jsfiddle.net
You are making an asynchronous request. So your code which appends the HTML execute before the success does which assigns the variable.
The code following the ajax request executes immidiatly after the request is made.
So if you require the response data then you should move your append code to be executed from the success method similar to this:
if (key == serverip){
stream_domain = val;
console.log("val: " + val);
$("<span>" + val + "</span>").appendTo(".json");
$("<span>" + stream_domain + "</span>").appendTo(".variable");
}
DEMO
The ajax call is asynchronous, so the timeline of the events is :
make ajax call
console.log
ajax call success, variable assign
Wait for the success event before using the variable. Here is your updated jsFiddle where I've added a function called in the success callback function:
function continueWorking(){
console.log(stream_domain);
$("<span>" + stream_domain + "</span>").appendTo(".variable");
}

passing multiple object to controller using ajax in ASP.NET MVC

I work on an ASP.NET MVC project.
I have to pass two parameters to an action in my controller. the first is a serializable object, and the second one is an integer.
First time I tried to pass only one parameter, the serializable object. There is no problem, but when I add the second parameter, the serializable object doesn't delivered (null value), but the integer parameter delivered successfully.
this is my action look like :
[HttpPost]
public bool MyAction(MySerializableObject myData, int intParameter)
{..}
and this is how I try to pass the parameters :
$('#submit-button').click(function () {
var formData = $("#MyForm").serialize();
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, { myData: formData, intParameter: '5005' }, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});
});
Anyone can explain about it ? how can it happens and how to solve the problem ?
thanks.
this may be a bit of a longshot but have you tried swapping the order of the parameters around (IE public bool MyAction(int intParameter, MySerializableObject myData) The reason im asking is that it may be that your client side serialize isnt working quite right.
If not your best bet is to take a look at whats actally getting posted to the server. Open up firebugs net tab or similar in webkit and take a look at whats actually going back to the server.
You could use the following plugin (serializeObject) instead of .serialize:
var formData = $('#MyForm').serializeObject();
// add some data to the request that was not present in the form
formData['intParameter'] = 5005;
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, formData, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});

Prototype believes JSON from PHP is string

I have the following code in JS:
new Ajax.Request('http://www.some_random_url.com',
{
parameters: { start : this.start, stop : this.stop },
method: 'post',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response.posts);
$(response.posts).each( function(item) {
alert(item.title);
}
},
onFailure: function(){ alert('Something went wrong...') }
});
and then I have the following code in PHP. The function takes an array as an argument, and is meant to output JSON.
function view_api($array) {
header('Content-type: application/json');
echo json_encode(array('posts'=>$array));
}
Still, it seems to be treated by prototypejs as a string. When response is alerted, everything is fine. But the each loop in JS says response.posts is undefined.
Do you know why?
If it's returning the JSON as a string then you should parse it first.
var data = JSON.parse(payload);
use evalJSON() to typecast the response in JSON object as
var response = transport.responseText.evalJSON() || "no response text";
set evalJSON: 'force' in the prototype ajax request options. then use var response = transport.responseJSON
A neat trick with prototype.js is that you can pass the following headers and it will automatically be converted to json.
header('X-JSON: (' . json_encode($data) . ')');
header('Content-type: application/x-json');

Categories

Resources