I want to send/get a variable to/from controller action. My codes:
view file
....
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var $radio = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
type: 'POST',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
data: {radio: $radio},
// datatype: "html",
success:function(){
alert($radio);
}
});
$.ajax({
type: 'GET',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
datatype: "json",
data: {change: $sql},
success: function(data) {
alert(data.change);
}
});
});
</script>
....
controller action
public function actionSech ($radio)
{
$sql = Yii::app()->db->createCommand()
->select ('m.maraq')
->from ('maraq m')
->where ('m.idsinif=:ids', [':ids'=>$radio])
->queryAll();
$gonderilen = CJSON::encode(['change'=>$sql]);
}
I read articles from Yii offical site and other forums. But I couldn't understand how can I do it.
Please tell me, how can I send $sql variable to my view file?
Thanks.
I'm not pretty sure what you want. But, I want to pointing out some snippet.
In view file
<?php
Yii::app()->clientScript->registerScript("header-info","
var baseUrl = '".Yii::app()->baseUrl;."';
",CClientScript::POS_HEAD);
?>
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var radioValue = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
url: baseUrl +'/ideyalar/sech',
dataType:'json',
type:'POST',
data:{radioValue:radioValue},
async:false
}).done(function(data){
if(data['status'] == 'OK'){
alert(data['returnValue']);
}else if(data['status'] == 'ERROR'){
alert("HERE WE GO ERROR");
}
});
});
</script>
Your controller action;
public function actionSech()
{
//In my point, I never call db layer in controller. Controller should be routing purpose
If(Yii::app()->request->isAjaxRequest){
$radioValue = isset($_REQUEST['radioValue']) ? $_REQUEST['radioValue'] : "";
$returnObj = array();
if($radioValue !=""){
$query = "SELECT `maraq` FROM maraq WHERE idsinif='$radionValue'";
$result = Yii::app()->db->createCommand($query)->queryScalar();
if($result != "" || $result != null){ //ensure result is correct or not
$returnObj['returnValue'] = $result;
$returnObj['status'] = 'OK';
}else{
$returnObj['status'] = 'ERROR';
}
}else{ //if radiovalue is blank string
$returnObj['status'] = 'ERROR';
}
echo json_encode($returnObj);
}
}
Hope this help! Btw, JavaScript variable can't not initialize with $. Just only var yourVar="";
Related
Please help me find the problem here. I am trying to upload a file via AJAX but For some reason which I am unaware of this code has refused to work i.e uploaded file is not copied to the location.
function save()
{
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append('files',files[i],files[i].name);
}
var datastring = $("#businessform").serializeArray();
$.each(datastring,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
Here's the PHP
$success = 0;
$logo = "";
$logo_error = 0;
$sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
$fields = array(
':bname'=>$_POST['businessname'],
':phone'=>$_POST['businessphone'],
':email'=>$_POST['businessemail'],
':id'=>$_POST['vendorid']
);
$q=$con->update_query($sql,$fields);
if($q)
{
//save logo
$businessid = $con->lastID;
if(!empty($_FILES['files']['tmp_name']))
{
$ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
{
$logo = "logo".$businessid;
move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
}
else
{
$logo_error = 1;
}
}
$success = 1;
}
echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));
The serialized form appended is sent and inserted without issues but the uploaded file is not sent this way. Please what are my doing wrong and what's the better way.
Thank you so much.
You don't need to append files in FormData() just put Form tag selector in side FormData($("#businessform")[0]);
function save()
{
var datastring = FormData($("#businessform")[0]);
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
I have one issue with ajax when I get echo success on my php. I don't get execute the first if
if(text[0]==="success")
Code inside php
if(count($error)==0)
{
$user = ORM::for_table('usuario')->create();
$user->username = $username;
$user->contrasenia = password_hash($password, PASSWORD_DEFAULT);
$user->email = $email;
$user->admin = $is_admin;
$user->save();
echo "success";
}
else
{
$error = json_encode($error);
echo $error;
}
My code in ajax
[![$("#create-button").on('click', function(event){
//cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm()
{
var dataString = $("#userForm").serialize();;
$.ajax({
dataType: "json",
type: "POST",
url: "/altausers",
data: dataString,
success: function(text)
{
console.log("hola");
console.log(text);
if(text\[0\]==="success")
{
alert("hola");
//$("#error").addClass('hidden');
}
else if(text.length > 0)
{
$("#error").removeClass('hidden');
texterror = "<ol type='disc'>";
$.each(text,function(index,value)
{
texterror+="<li>"+value+"</li>";
});
texterror+="</ol>";
document.getElementById("error").innerHTML = texterror;
}
}
});
}
Image console
What is the problem?
Could say me which it is problem?
I have that convert the message success to json too
Replace the success echo with
echo json_encode(["success"]);
or leave echo the same and replace if in ajax
if(text == "success")
The problem could be that it is an array, so you can try this:
$.ajax({
url: "items.php",
async: false,
type: "POST",
dataType: "JSON",
data: { "command" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});
And if you want to see the results:
Object.keys( response ).forEach(function( key ) {
console.log('key name: ', key);
console.log('value: ', response[key]);
});
Racking my brains for hours with this. I have the following PHP AJAX script:
<script type="text/javascript">
$(document).ready(function(){
$("#submitValue").click( function(){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
success: function(data){
$('#results').html('Success').delay(1000).fadeOut();
}
});
});
});
</script>
I am trying to get the message 'Success' to populate this span element;
<span id="results"></span>
But just can't seem to get it to work.
The PHP is as follows (the table is updated just fine);
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
}
Anyone be of assistance please?
dataType: "dataString"
Please comment this part and it will work.
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
echo 'yes';
}
// add echo 'yes'; at php submit page.
change the script as follows
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
// dataType: "dataString",
dataType : "text",
success: function(data){
$('#results').html(data).delay(1000).fadeOut();
return false;
}
});
return false;
In php file change this
$qry = mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
if($qry)
echo "Success";
}
When you make an ajax call and you pass the values to a php file, you will also need to return the response.
So at the end of your query if everything is completed successful you will do something like this:
return Response::json(array(
'success' => true,
'message' => trans('admin.update_success'),
), 200);
And your ajax cal looks something like this:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
})
.done(function(response) {
alert(response.message)
})
.fail(function(response) {
if (response.status == 400) {
var output = '<ul>';
var errors = $.parseJSON(response.responseText).errors;
$.each(errors, function(id, message) {
output += '<li>' + message[0] + '</li>'
});
output += '</ul>'
alert(output)
} else {
alert('UnknownError');
}
})
e.preventDefault();
})
So to recap:
You make the ajax call
The php file will process the data
You pass the response back to the 'done function)
And hier you can make anything you want with your response.
I have just as example inserted an alert message
Hope this helps.
Sorry but the code I have provider for you is for a Laravel framework and I suppose you are not using it. So you don't have the 'Respone::' class.
In the php file:
//if the query has success
$return = array();
$return['responseCode'] = 1;
$return['responseHTML'] = 'Success'
echo json_encode( $return );
And the ajax call:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
})
.done(function(response) {
if( response.responseCode == 0 ) {
//alert(respomse.responseHTML)
$('#results').html(response.responseHTML);
} else if( response.responseCode == 1 ) {
//alert(res.responseHTML)
$('#results').html(response.responseHTML);
}
})
e.preventDefault();
})
So I don't use the response anymore but I will just return an array with the response.
I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}
I have a big issue with $.ajax. I try to send a file name to the PHP part (in the same file), to help me stocking that name in a $_SESSION.
It worked perfectly yesterday, but not anymore. Is there a browser issue instead of code issue ?
Here is my code :
JS function
<script type="text/javascript" charset="utf-8">
function no_select(){
var images = $("#selected_images").text();
if(images != ''){
var tmpFile = $("#selected_images").text();
var arrayFile = tmpFile.split(",");
if (arrayFile.length > 2){
alert("Il ne faut selectionner qu'un seul badge !");
return false;
}
var value = $.ajax({
type: "GET",
dataType: "json",
url: "overview_list.php",
data: "selectedImage="+arrayFile[0],
async: false,
success: function()
{
return true;
}
});
return true;
} else if(images == ''){
alert("Il faut selectionner un badge");
return false;
}
}
</script>
PHP
<?php
if(!empty($_GET['selectedImage'])){
$let = $_GET['selectedImage'];
} else {
$let = "";
}
$_SESSION['selectedImage'] = $let;
?>
I have already check a lot of solutions around the web, but there was no solution for me.
It should be like
$.ajax({
type: "GET",
dataType: "json",
url: "overview_list.php",
data: {selectedImage:arrayFile[0]},
async: false,
success: function()
{
return true;
}
and makesure arrayFile[0] is getting value