Saving value in "$data" from AJAX output - php

just wondering how i save the value from the "var vname" to "$data" so that i can use the value in my php. Assuming this is pretty easy, but i'm new to this :P
<script id="source" language="javascript" type="text/javascript">
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$data = vname; //HOW AND WHERE??????? :P
}
});
};
</script>
/EDIT - want my var vname which is a color, to be placed in the style.
<body>
<div id="kvadrat1" style="width:200px; height:200px; position:relative; background-color:'HERE I WANT MY VALUE'">
</div>
Greatful for quick answers! :)

Seems to me like you're just trying to fetch a name and an ID, but can't imagine why you'd need to do that every 1000 milliseconds - just seems like a lot of requests for data that isn't going to change?
Personally I'd just suggest making the API call in your PHP before the page loads and you can var name = "<?=echo $name?>"; as avalkab has said in order to access the variables in JavaScript after the page has been loaded.
Should be able to use
$data = json_decode(file_get_contents("api.php?id=5&parent=6")); // Specify or build query however you intended
If you are waiting for the user to interact (onclick or something) to call your javascript then if you expect to use data retrieved by AJAX to change data on the whole page - you might just want to reload the page, or revise your AJAX to make use of the data returned?
EDIT:
Since you are trying to change a colour you can simply use this line with jQuery
$("#kvadrat1").css({"background-color": vname});
So your code would be like so:
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall() {
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$("#kvadrat1").css({"background-color" : vname});
}
});
};

Take a read here : Pass javascript variable to php with ajax and the result doesn't show anything
This will explain you to use javascript varaiables with PHP. Great answer from Zladuric.

You can not save it in php.
You can save it to HTML element
If you need it in php variable send it to other page using ajax or header redirection

PHP code is executed once when a page is loaded by the user. JS is executed while the user is on the page. This is why it is impossible to bind values generated by JS to PHP variables.

You cant use php code when page loaded or in js.
javascript works only browser base. php works only server before
loading page.
// you can
var name = "<?=echo $name?>";
//you CANT!
var name = "joe";
$name = name;

you can not store it in php rather than you can use any html element to store it
you can keep data in html element by using $("#id").html(data[0]);

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Using POST data in a query with Ajax and PHP

I have a website that uses bootstrap tabs so I'm trying to make everything work with minimal refreshing with Ajax, however I'm having trouble with getting an ajax post to work with a mysql query until the page is refreshed.
Once a button is pressed the value is grabbed from the ID of that element by Ajax and a bootstrap tab is opened. This is where I want the data to be passed so the results are relevant to the option that the user has selected.
Modules.php
(Ajax request)
$(".completed").click(function() {
var element = $(this);
var ID = $(this).attr("id");
var dataString = 'id='+ ID;
$.ajax({
cache: false,
url: "includes/scripts/ajax/module_parts.php",
type: "POST",
datatype: "text",
data: dataString,
success: function (html) {
$('#moduleNum').html(ID);
console.log(ID);
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
});
return false;
});
module_parts.php
$module_id = mysqli_real_escape_string($connection, $_POST['id']);
echo $module_id;
$query = mysqli_query ($connection, "SELECT number FROM Modules WHERE number = '".$module_id."'");
I know that the post is working correctly because I tried turning the post into a session then when refreshing the page the data was displayed.
Also the data is displaying correctly when appending the ID to an html element.
Many thanks,
Zack.
Just as a side note, I prefer to do this with ajax shenanigans. It may help you ...
Altered the anchor element:
Click me
Javascript:
ID = $(this).attr("id")
$('body').on('click', '[rel="completed"]', function() {
$.post('includes/scripts/ajax/module_parts.php', { id : ID }, function(data) {
$('#moduleNum').html(data); // data or ID ?
}).fail(function() {
alert('request failed');
});
});
The $('body').on part helps to keep scripts alive should you insert new links or buttons. It means anything within the body tag but you can and maybe should narrow it down further such as the surrounding div.
I, personally, find this way to be easier to deal with, especially if there is just simple data passing to and fro.
1) Check if id is passed by post and get by module_parts.
2) I'd rather use object when passing post data via ajax:
data: { id : ID }
3) Good option to check ajax requests is to use Firebug (on Console), you can check requests details without echoing.
At least two things in your script need resolution.
datatype should be changed to dataType (text is not one of jQuery's "intelligent guess" types (xml, json, script, or html), so dataType must be correctly spelled.
You should prevent the default behavior of the anchor click event.
(".completed").click(function(e) {
e.preventDefault
...
There may be some additional problems, but these two jumped out at me.

jquery ajax call of mysql

I have found many threads regarding this issue, but unfortunately I couldn't get it running. Problem is I don't know much about JQuery.
I am trying to make an Ajax call using JQuery in order to fetch multiple records from a mysql database. I have the following function :
function updateWebpage ()
{
$.ajax({
url: './sale/api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var username = row[0];
var stateId = row[1];
$('#output').append("<b>id: </b>"+username+"<b> stateId: </b>"+stateId)
.append("<hr />");
}
}
});
};
My api.php is executing a mysql query with something like this:
$array = retrieveUsersInfo('%'); //fetch result
echo json_encode($array);
My main issue, is how to debug an issue like this? Since ajax is calling asynchronously another file, I cannot view any errors. From my firefox debugger, I can see that the $.ajax function is entered, but success is not.
Thanks in advance.
a couple things to try.
hit the api url directly in a browser (not through ajax) and make sure it returns the valid response.
add an error: function(err){} to your jquery ajax call. this method will get called if there is something other than a 200 response back from the server.
I use Chrome's developer tools more than firefox/firebug. It has a Network tab in it that shows me all the communication between the client and the server. You should see a call out to your api in that tab.
just off hand, i think you need to make sure the mime-type is set to text/json in your php file.

Reading from a MYSQL table every 5 seconds and dynamically displaying results on a PHP page without refreshing

I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql

What is correct way to pass data through .ajax() to a PHP script?

I'm attempting to send a piece of data through jQuery .ajax() to a PHP script which will then be loaded into a div container. The PHP script will then run with this piece of data and its contents will be returned into the aforementioned div container.
Initially, I wrote this piece of code (shown below) which successfully added the correct elements upon a click but wasn't able to name them correctly because it didn't doesn't pass the count_bucket variable to the PHP.
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP));
return false;
});
I then altered the code to this (shown below) in attempt to pass the count_bucket variable to the PHP script.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.ajax ({
type: "GET",
url: "create_new_bucket.php",
data: var count_bucket,
dataType: "json",
async: false,
}).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
The PHP file create_new_bucket.php looks like this:
<?php
include_once "test_functions.php"; // include functions page
$i = $_GET["count_bucket"];
drawBunchNew($i);
?>
I'm unclear which aspect of the .ajax() is incorrect. I suspect I'm not collecting the variable correctly in the PHP or I'm using the incorrect syntax to pass it to the PHP file. If anyone could help me identify the error, I would greatly appreciate it.
*UPDATE******
Thanks Tejs & Tandu. I'm clear on how to structure the data now but I still am having trouble getting the whole bit of jQuery to work. I took Tandu's suggestion to use .load() instead and have changed my PHP to use POST to pull the data but it's still not working correctly.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.load ("create_new_bucket.php", {count_bucket: count_bucket}, }).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
And the PHP is:
<?php
include_once "test_functions.php"; // include functions page
$i = $_POST["count_bucket"];
drawBunchNew($i);
?>
Final working jquery I used (final PHP is same as above):
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP, {count_bucket: count_bucket}));
return false;
});
The data property of the ajax request is going to be an object; think of it like JSON:
{ data: var response }
Is not valid JSON. However, you can do something like this:
data: { myKey: 'myValue', myKey2: 'myValue2' }
Or in your situation:
data: { count_bucket: 4 }
And it will send the data contained in the data property to your server as part of that name value set.
Data for ajax in jQuery needs to be passed as a query-string formatted string ('key[]=value&key[]=value&key[]=value') or as a json object ({key: [value, value, value]}). I believe that the var you have there will be a syntax error. You also need to specify the key, so either data: {count_bucket: count_bucket} or data: 'count_bucket=' + count_bucket should do.
Note that it is not necessary to use .ajax(). It's usually a bit nicer to use .load(), .post(), and .get(). In your case, .load() should work fine. Pass the data as the second argument.
Why do you not want the request to be asynchronous? Note that dataType is the data type of the return value, not of what you are sending. Are you receiving json? jQuery can also usually guess this correctly, and if you set the header on the php side, it helps a lot. The GET type is also the default.
Final note: when using .load(), if you pass the data as a string it will use GET, but if you pass it as an object it uses POST.

Categories