I want to return multiple data (variables) from PHP instead of just 1 piece of returned html code.
Right now I got this:
$.ajax({
url: "test.php",
cache: false
})
.done(function(html) {
$('video').attr('src', html);
});
But I want to be able to do someting similar to this:
$.ajax({
url: "test.php",
cache: false
})
.done(function(data) {
$('video').attr('src', data.videoUrl);
$('video').attr('poster', data.posterUrl);
});
In my test.php I have this:
$posterUrl = "thumbnail.png";
$videoUrl = "video.mp4";
echo $posterUrl;
echo $videoUrl;
How can I accomplish something like that?
The easiest way? JSON.
JavaScript:
$.ajax({
url: "test.php",
dataType: "JSONP"
}).done(function(json) {
$("video").attr("src", json.videoURL).attr("poster", json.posterURL);
});
PHP:
$output = array();
$output["posterURL"] = "poster.png";
$output["videoURL"] = "video.mp4";
echo json_encode($output);
You may need to json_encode the response like this.
$response = array("videoUrl"=>"video.mp4","posterUrl"=>"video.mp4");
echo json_encode($response);
You can return a JSON instead of a string.
More info here: http://api.jquery.com/jQuery.getJSON/
Related
I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>
Hello I am new to js and I stuck on the problem about passing variables to php via ajax.
<script>
$date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: ({'date': date}),
success: function(data){
console.log("successfully");
}
});
</script>
And below is my code in record.php file.
<?php
session_start();
if(!empty($_POST['date'])){
//$hello = 'hh';
$_SESSION['date'] = $_POST['date'];
echo($_SESSION['date']);
}else{
echo "its empty(var)";
}
?>
Page always print out "its empty(var)" and I checked console, it shows "successfully"... I already stayed on this problem for several hours and looked for a lot of similar post, but I still can't find where is the problem. Can anyone have a look at it? I also already loaded the jQuery library.
you ar mixing js variable with php variable, js variables are declared with var and php variables are declared with $fieldname
<script>
var date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: {'date': date},
success: function(data){
console.log("successfully");
}
});
</script>
if you want a PHP variable insite javascript you should define php variable first then asign it into js.
<?php $date = "123"; ?>';
<script>
var date=<?php echo $date; ?>';
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: ({'date': date}),
success: function(data){
console.log("successfully");
}
});
</script>
Hope it wil helps you.
You cant mix server (php) and client (js)
you might to this
<?php $var = 0?>
then in html you create
<input id="something" type="hidden" value="<?php echo $var?>">
then you get that value via
document.getElementById("something").value;
You are declaring $date and pass in your ajax as date.
Try this:
<script>
var date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: {'date': date},
success: function(data){
console.log("successfully");
}
});
</script>
View File product_grid
<div data_id="<?php echo $ro['category_id']; ?>" name="id" class="cbp-filter-item">
<?php echo $ro['category_name']; ?></div>
// try to post data using ajax
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>.index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
Hear i can pass the id to view but not work properly please help me to solved this problem
Controller ::
public function product_grid()
{
$id= $this->input->post('id');
}
You must have to use print or echo otherwise there will be no response sent to client side so use echo like,
public function product_grid(){
$id= $this->input->post('id');
echo 'Data-Id is: '.$id;
}
And use the URL like,
url:"<?=base_url()?>index.php/Home/product_grid", // let there is / in the end of base_url()
AJAX Code,
jQuery.ajax({
url:"<?=base_url()?>index.php/Home/product_grid",
type:'POST',
data: {id:id}, // no need of quotes to JSON Object keys
success:function(data) {
alert(data);
}
});
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>+index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
url:"<?=base_url()?>+index.php/Home/product_grid"
Use + for concatination instead of .
How can I use some PHP variables from the ajax-send.php to the index.php file? I use AJAX as shown below. Do I have to replace AJAX with something else?
index.php
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
}
});
ajax-send.php
$token = $_POST['one'];
echo "ok"
$toINDEX = "use this in index.php"
Try this
Ajax
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
var response = data;
//alert(data);To see what you have received from the server
}
});
PHP
if(isset($_POST['one'])){
$token = $_POST['one'];
echo "ok";
$toINDEX = "use this in index.php";
die();
}
In PHP just echo variable or json_encode array. In JS do the following:
var result = $.ajax({
url: this.fileUrl,
type: "POST",
data: data,
async: false,
dataType: 'json'
}).responseText;
Your vaiable is fully accessable.
take the variables in php sessions
//On page 1(ajax-send.php)
session_start();
$_SESSION['token'] = $_POST['one'];
//On page 2(index.php)
session_start();
$var_value = $_SESSION['token'];
You can simply echo the variable and then access it via javascript inside the success function.
But a better approach would be to json_encode the data. The beauty of this is that it will help you to pass multiple values/variables in a single echo. So
PHP
.
..
if(<all is okay>)
{
$toINDEX = "use this in index.php"
$data['result'] = 'ok';
$data['msg'] = $toINDEX;
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
Javascript
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
dataType:'json',
success: function(data) {
if(data.result == 'ok')
{
console.log(data.msg);
console.log(data.some_other_value);
}
else
{
// something went wrong
}
}
});
The important thing to note here is dataType:'json' which tells the function to expect the returned data in json format.
EDIT:
As per you comment, you could do this
$toINDEX = "use this in index.php";
// now use the variable here itself
mysql_query("SELECT * FROM table WHERE column = '$toINDEX'");
.
.
if(<all is okay>)
{
$data['result'] = 'ok';
$data['msg'] = 'anything you would like to show the user';
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
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'
});
});
});