jquery json post not working - javascript

Well, im trying to post a variable in jquery to my controller. But it seems that the posting is not successful. I am not getting any value when i try to retrieve it in my controller. It says undefined index. Here's what I have:
my jquery:
$(document).ready(function(){
$('.buttons').click(function(){
var data = $(this).attr("value");
// var test = 'test';
jQuery.ajax({
url:'<?php echo $this->Html->url(array('controller'=>'maps','action'=>'instantiateButtonValue'));?>',
type: 'POST',
async: false,
data: data,
dataType: 'json'
// success:function(data){
// alert(data);
// },
// error:function(data){
// alert(data);
// }
});
});
});
my controller:
function instantiateButtonValue(){
echo $_POST['data'];
// $this->set('data','some');
// $this->render('json');
}

I think you should enclose with " quotes instead of ' quotes in URL.
From PHP you should encode as JSON instead of direct echo, to retrieve the value by JQuery.
like below
echo json_encode($_POST['data']);

i got an idea from this link here
$(document).ready(function(){
$('.buttons').click(function(){
var data = $(this).attr("value");
// var test = 'test';
jQuery.ajax({
url:"<?php echo $this->Html->url(array('controller'=>'maps','action'=>'instantiateButtonValue'));?>",
type: 'POST',
async: false,
data: {data:data},
dataType: 'json'
});
});
});

Related

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});

Saving data with ajax to a database

How can I save info that I have in a div named '#time' to a database?
<div id="time" style="float:right;font-size:15px;">0:00:00</div>
The code above is a jq count up timer.
What I'm trying is to save every tick in the database.
How can I do this?
$.ajax({
type: "POST",
url: "setupcounter.php",
data: {action: 'save',
field: $("#time").val(),},
success: function(msg){
}
error: function(){
alert('error');
}
});
Actually you want to get text of div. So do this..
Just replace
$("#time").val()
with
$("#time").text()
var time = $('#time').val();
//Just add whatever params you need to the datastring variable.
var dataString = 'time='+time+'&action=save';
//Check console that you are sending the right data
console.log(dataString)
$.ajax({
type: "POST",
url: "setupcounter.php",
data: dataString,
success: function(msg){
console.log(msg);
}
});
In php you would do:
$time = $_POST['time'];
$action = $_POST['action'];
//Db stuff
Fiddle

Pass PHP array to external jQuery $.ajax

Basically what I want to do is get an array that has t.php, and alert it with JavaScript with the response of t.php.
The problem is that the variable doesn't exist in this file...
So, how you can pass this variable to JS?
I tried with 'return':
return $sqlData = $q->query_array_assoc();
But doesn't work.
Here is my $.ajax code:
<script type="text/javascript">
$(document).ready(function(){
$('#brand').change(function(e){
console.log(e);
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value }
})
.done(function(msg){
$('#debug').html(msg);
var pArray = <?php echo json_encode($sqlData);?>
for (var i = 0; i < pArray.length; i++) {
alert(pArray[i]);
};
});
});
</script>
Note: I sent
data: { type: 1, brand: this.value }
To validate a switch statement in the .php file, but there isn't problem with that. I get the data from the database and fetch in the variable $sqlData;
So the array has data, the problem is get it with $.ajax
in your php file, you need to echo instead of return
echo json_encode($q->query_array_assoc());
in javascript code:
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value },
success: function(data) {
$('#debug').html(data);
// if you want to use it as array
var json_data = JSON.parse(data);
}
});
Make 2 files please, a "t.php" file and a "t.html" file and add my code there. Run the code and see response. You just have to work with the response to get the values se perated by comma "," !!!
/******************** UPDATED ***********************/
//t.php
<?php
$a = array();
$a[]=1;
$a[]=2;
$a[]=3;
echo "$a[0],$a[1],$a[2]";
?>
//t.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
$.ajax({
method: "GET",
url: "t.php",
data: { },
dataType: "html", //expect html to be returned
success: function(response){
//$("#debug").html(response); //Outputs the html of php file into #dialog div
alert(response);
document.getElementById("debug").innerHTML = (response); //Outputs the html of php file into #dialog div
}
})
}
</script>
<button onclick="fun()">Call Ajax Fun</button>
<div id="debug"></div>
Did this help?

Create array from PHP SQL query and pass it to ajax

I'm trying to get my results from a SQL query into an array in javascript. I'm trying the following:
PHP:
$query = mysqli_query($connection, "select a, b, c from table");
$result_a = array();
$result_b = array();
$result_c = array();
while($row = mysqli_fetch_array($query)) {
$result_a[] = $row['a'];
$result_b[] = $row['b'];
$result_c[] = $row['c'];
}
echo json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
javascript:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
},
});
return false;
The PHP arrays have the data I'm looking for but the alerts in javascript are undefined. Any help would be appreciated.
In PHP you echo data in json format json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
So if you want to use the json as an object directly in the ajax success function, you need tell the ajax call "You are expecting a json object coming bakc!";
So you should modified js code to this:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
dataType : "json", // <------here, auto parse json for you
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
}
});
Or in the success function, manually parse json before use;
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false
error: function(){},
success: function(data){
var obj = jQuery.parseJSON(data); // <---- here, manual parse
alert (obj.a);
alert (obj.b);
alert (obj.c);
}
});

Access Javascript variable in php in same page

Hi I am facing problem with json data. Here is my js code.
<script>
$(function(){
$.ajax({
url:"http://example.com/salary?from=USD&to=GBP",
dataType: 'jsonp',
success:function(json){
alert(json['to']);
},
error:function(){
alert("Error");
},
});
});
</script>
I want to use json data in PHP in same page.
I know that you cannot assign Javascript value to PHP variable.
Is there way to do this?
Or is possible to do similar task in php (Jquery Ajax cross domain) like above javascript code ?
Any help?
your js code
var my_json_obj = new Object();
my_json_obj .name = "Lanny";
my_json_obj .age = "25";
my_json_obj .location = "China";
var json_str = JSON.stringify(my_json_obj);
<script>
$(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "my.php",
data: {
postData: json_str
},
success: function (data) { alert(data) },
eror: function (data) { alert(data) }
});
});
</script>
your my.php file
$postData=$_POST['postData'];
$my_obj=json_decode($postData,true);
$name=$my_obj['name'];
$age=$my_obj['age'];
$localtion=$my_obj['location'];
You could do that with AJAX.
You need a script, which will give javascript vars to the PHP Script, like:
var PHPFile = 'PHPFile.php?arg1=' + arg1 + '&arg2=' + arg2;
In the "PHPFile.php" you can access them by
$arg1 = $_GET["arg1"];
$arg2 = $_GET["arg2"];
Or you could do that with jquery $.ajax-> data, too.
You can access them by
$arg1 = $_POST["arg1"];
$arg2 = $_POST["arg2"];
Something like that:
result = $.ajax({
type: 'POST',
async: false,
url: 'PHPFile.php',
data: ({
arg1: arg1,
arg2: arg2
})
}).responseText;
alert(result);
EDIT:
If you want to do that with a json-object, try this:
json_decode();
http://www.php.net/manual/en/function.json-decode.php
http://www.php.net/manual/en/function.json-encode.php

Categories

Resources