Access Javascript variable in php in same page - javascript

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

Related

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

Passing javascript variables to another php page

I have a select list where in using javascript i get the selected values i want this selected values to pass through php file init.php so that i can use those variables in mysql query.
my javascript code is as follows:
$(document).ready(function(){
var e = document.getElementById("product");
var pro = e.options[e.selectedIndex].text;
alert(pro);
});
$('select').change(function(){
var e = document.getElementById("city");
var cit = e.options[e.selectedIndex].text;
alert(cit);
I have used ajax to send variables to init.php. my ajax code below is not working,can anyone tell whats the issue in this code:
$.ajax({
url: 'init.php',
type: 'POST',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
and in init.php i have written :
<?php
$var1 = $_POST['y'];
$var2 = $_POST['x'];
$result = "Select amount from ". _DB_PREFIX_ ."demo_detail where product = '". $var1 ."' and city = '" . $var2 . "' ";
//echo json_encode($result);
Can you alter the url line to include the / to make sure that you're referring init.php relative to the root of your directory?
So it should look like this:
$.ajax({
url: '/init.php',
type: 'POST',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
I don't know enough to say for sure but there's a chance that AJAX is making a POST request to the wrong URL.
Have you tried to pass absolute as well as relative path in url. What I mean is
have you tried using:
url:'localhost:xxxx/myapp/init.php'
or
url:'/init.php'
If you're passing variables into the data parameter in Ajax, they don't have to be in quotes.
$.ajax({
url: 'init.php',
type: 'POST',
data: { x: cit, y: pro },
success: function(data) {
console.log(data);
}
});
Use Query String. HTML5's Session Storage can also help you.
Try to replace your script code with following and see if it makes a difference
$(document).ready(function(){
$('select').change(function(){
var e = document.getElementById("product");
var pro = e.options[e.selectedIndex].text;
alert(pro);
var e = document.getElementById("city");
var cit = e.options[e.selectedIndex].text;
alert(cit);
$.ajax({
type: 'POST',
url: 'init.php',
data: { x:'cit',y:'pro' },
success: function(data) {
console.log(data);
}
});
});
});

Not sending data into controller with onclick function

I use this button in jason.
<button id="bid" type="button" class="button" onclick="connect()">Save</button>
It show altert when I use alert after document.getElementById. But it not works in ajax function. Here is my connect function
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
//**alert(BID + REF + POU);**
var url ='<?php echo base_url()."index.php/main/transacIn/" ?>';
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
}
alert(BID + REF + POU); this alert works but not works alert in success. And it don't sent any data into controller. Help me about it. Thanks in advance.
try this
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
var site_url = document.getElementById('site_url').value;
var url = site_url+'main/transacIn';
$.ajax({
type: "POST",
url: url,
data: {
BID : BID ,
REF: REF,
POU:POU
},
success: function(data) {
//$("#bid").hide();
alert(BID);
},
error: function(err) {
console.log(err);
}
});
}
you should a hidden field in your corresponding page <input id="site_url" type="hidden" value="<?php echo site_url(); ?>"/>
You cannot inject the php syntax into javascript file. Either you define the script in codeigniter template file as
<script type="text/javascript">
// Your javascript function
</script>
...or you can define a javascript variable in the template file which actually get the path to your controller:
var url = <?php echo base_url()."index.php/main/transacIn/" ?>';
Then on your javascript file on ajax post you are pointing to the variable defined in the template file:
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
Hope you got the idea.
Anyway you need to be careful defining global variables. It's a good practice to guard the variables by using namespaces.
Try this solution. It will work:
$.post(url , {BID: BID, REF: REF, POU:POU },
function(data){
alert(BID);
});

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?

append ajax result to div

I'm making an ajax call to the IMDb API to get the movie data for 'The Shawshank Redemption'. I want this data to be put in the div I created.
<div id="movie-data"></div>
My js code currently:
$(init);
function init() {
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(data);
}
});
It doesn't give any response. However, I can see the data in my console. When I append <p>Test</p> instead of data it does return 'Test' to the screen.
This is what I did. It seems to be working now. Thanks everyone.
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(JSON.stringify(data));
The following should work
$("#movie-data").html(data.Title);
because data will be in json format, like this:
{"Title":"Titanic","Year":"1997","Rated":"PG-13","Released":"19 Dec 1997","Runtime":"3 h 14 min","Genre":"Drama, Romance","Director":"James Cameron","Writer":"James Cameron","Actors":"Leonardo DiCaprio, Kate Winslet, Billy Zane, Kathy Bates","Plot":"A seventeen-year-old aristocrat, expecting to be married to a rich claimant by her mother, falls in love with a kind but poor artist aboard the luxurious, ill-fated R.M.S. Titanic.","Poster":"http://ia.media-imdb.com/images/M/MV5BMjExNzM0NDM0N15BMl5BanBnXkFtZTcwMzkxOTUwNw##._V1_SX300.jpg","imdbRating":"7.6","imdbVotes":"449,162","imdbID":"tt0120338","Type":"movie","Response":"True"}
Check these resources:
Using AJAX to Extract Data from IMDB API
http://99webtools.com/blog/php-get-movie-information-from-imdb/
Try like this. API is returning JSON values you need to get the values like mentioned below. Hope this helps you.
var content = 'Title : '+data.Title ;
content += ' Year : '+data.Year ;
content += ' Rated : '+data.Rated ;
content += ' Released : '+data.Released ;
$("#movie-data").append(content);
<div id="movie-data"></div>
function init() {
var html='';
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
for(var key in data) {
var value = data[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#movie-data").append(html);
}
});
}
init();
working demo
the answer is:
function init() {
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").html($(data).append(data));
}
});
You could try to delete dataType: "json" from your ajax call
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(data);
}
});
You can try with JSON.stringify(data)
The code would be the following:
$(document).ready(function(){
$.ajax({
method:"get",
url:'{{ route('getnotificationcount') }}',
success:function(data){
console.log(data);
for(var key in data) {
var value = data[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#notifyy").append(html);
}
});
});

Categories

Resources