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
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 believe I have the right syntax but am missing something important. Been searching on here for a while but can't figure out why the POST variable is not being detected. Basically my .ajax is firing because my test statement has been changing due to the value but some reason can't receive variable via $_POST (i.e. my echo in php echo that it is not firing) Also the native file and php that I am sending it to are the same file blankFormTemplate.php but don't think that should be an issue.
$(document).ready(function()
{
var $selectedContexts = [];
$('.allContextField').change(function(){
//alert($(this).val());
hideField = $(this).val();
$('#'+hideField).remove();
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: addedContext=hideField,
cache: false,
success: function(addedContext)
{
$('#test').html($('#test').html()+hideField);
}
});
});
});
in my PHP blankFormTemplate.php:
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
Any help would be greatly appreciated.
Thanks,
Your javascript
$(document).ready(function()
{
$('.allContextField').change(function(){
hideField = $(this).val();
$('#'+hideField).remove();
});
if (hideField.trim()) {
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: (addedContext:hideField},
cache: false,
success: function(msg)
{
$('#test').html(msg);
}
});
}
});
Your PHP
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
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="";
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'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});