pass xmlhttp.responseText data to php variable - php

i have a jquery that brinds text from a page through ajax and displays that text in a div
i want to pass that data to a php variable how can i do that ?
my jquery code is
<script type="text/javascript">
var xmlHttp = null;
window.onload = function() {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "abc.php", true);
xmlHttp.onreadystatechange = onCallback;
xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttp.send(null);
}
function onCallback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
document.getElementById('show').innerHTML=xmlHttp.responseText;
}
}
}
</script>
here i want to save xmlhttp.responseTexrt in a php variable in the same file how i can do that ?

Javascript is executed on the browser, and php is executed in the web server. You can not directly pass values from javascript to php.
Therefore, you need to make another ajax call (POST) from javascript to the web server that sends the xmlHttp.responseText, and write php code in the server to store the value to database.

Pass your data in URL,
var data = "somedata";
xmlHttp.open("GET", "abc.php&send=" + data, true);
For Passing a serialized array, first convert it into string
var send = toString(array);
xmlHttp.open("GET", "abc.php" + send, true);
For storing array to PHP variable use $receive = explode(',',$_POST['send']);

Related

Assign the jquery value of a div to a php variable

I am using a jquery calendar script that assigns the content of a div using ajax.
$('#details-event-id').html(id);
The div tag:
<div id="details-event-id"></div>
is in another file and displays the id correctly.
<div id="details-event-id">91</div>
Is it possible to get the id, 91, to be assigned to a PHP variable?
Using ajax you can send the value to the server and then assign to the php variable.
If you think you assign php variable in any javascript event in client side, its not possible without any asynchronous calling of the server script.
If I understand correctly you would like to send the variable id to a PHP file. You can achieve this by using AJAX. Bellow I'm showing two ways to get it done.
var id = $('#details-event-id').html(id);
AJAX with good old JS
ajax(myfile.php, {id:id}, function() {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
});
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
AJAX with JQuery
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({
id: id
}),
success: function(data) {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
}
});
Offtopic: you can see why some prefer JQuery...
When either function (Jquery or plain JS) is launched it will send the variable id to the file myfile.php. In order to retrieve the variable from the call you won't use $_GET[...] but $_REQUEST[...].
myfile.php
<?php
if(!isset($_REQUEST['id'])) {
echo "no variable was sent";
}
$id = $_REQUEST['id'];
// process data, save in db, etc ....
You may return a value to the JS callback function by using echo() not return

AJAX Call not returning data

Can someone tell me why the div called tellme is showing only showing something for half a second.. or less and then just doing nothing? I have tried everything and just can't get the code to work. It is funny because I have the exact same code on my other page and it works with no problems what so ever, I am trying to call an AJAX call and it is just not working and its not making the div called tellme anything, it's just keeping it blank...
<script type="text/javascript">
function fireWorkerFixed(userid)
{
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://private.com/fire_worker.php";
var id = userid;
var vars = "userid="+id;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById('tellme').innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById('tellme').innerHTML = "<div class='alert alert-info'>Please wait, Processing request...</div>";
}
</script>

How do I pass javascript to PHP on a javascript command?

I'm new to PHP, but I'm developing in Visual Studio LightSwitch.
I'd like to pass several javascript variables from a data record to a PHP script during a javascript save event.
What are my options?
Your options are limited to ajax, or an image request.
Option 1. AJAX
function success() {
console.log(this.responseText);
}
var ajax = new XMLHttpRequest();
ajax.onload = success;
// myVars is a string containing the values you need to record. In the format
// of ?var=value&var1=value&var2=value
ajax.open("get", "/record.php?" + myVars, true);
ajax.send();
Option 2. Image
var a = document.getElementById('my-button');
a.addEventListener('click', function(e) {
var target = e.target || e.srcElement;
var img = new Image();
// get your variables values and create a url here.
img.src = 'http://myserver.tld/record.php?' + myVars;
});

split return data from old way ajax

i have page that do add new record by old way ajax, this code was add new record and return the error or done result message , how can i print the message on div and print result on other div. i try but some one tell me to use JOSN, how can i do that
<script language="JavaScript">
$(document).ready(function() {
});
$("#closeerr").live('click', function() {
$("#gadget").hide();
});
var HttPRequest = false;
function doCallAjax(Mode,Page,ID) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'AjaxItemsGroupsRecord.php';
var pmeters = "titems_groups_GroupName=" + encodeURI( document.getElementById("items_groups_GroupName").value) +
"&titems_groups_sys_type_ID=" + encodeURI( document.getElementById("items_groups_sys_type_ID").value ) +
'&myPage='+Page +
"&tID=" + ID +
"&tMode=" + Mode;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "looding";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
}
}
}
</script>
If jQuery is an option... As mentioned in my comment I'd recommend you try out jQuery http://jquery.com/ as you look to be fairly new to JavaScript.
It makes AJAX requests a lot simpler and you don't have to worry about making XMLHttpRequest work cross browser.
For making an actual AJAX request see: http://api.jquery.com/jQuery.ajax/
Now if you want to use JSON you need to convert the data to return in your PHP script.
This is really easy, you just pass the data in json_encode() and it will convert the data to a JSON string. You then just echo it out so that it's returned to the AJAX request.
echo json_encode($data);
Now if you've setup your AJAX request to expect a JSON response then you can use the data that comes back. So something like this:
$.ajax({
url: 'request.php', // the php you want to call
dataType: 'json' // the type of data being returned
}).done(function(json) {
// you now have a json object
});
If you can only use native JavaScript...
If you can't use jQuery then it roughly works the same way. You'd have the code in your example for the AJAX request. You'd still use json_encode() in the PHP. The only difference is when the data comes back you'd need to parse it like so:
JSON.parse(json);
For more info on this last bit checkout: Parse JSON in JavaScript?

Ajax call will not refresh inner html with php function that makes the html - help?

I have the following code generating content on my site:
<div class="content" id="links">
<?php displayTitle("Links"); ?>
<?php displayContent("Links", $isLoggedIn); ?>
</div>
The content has a button that calls a Javascript function 'addLink()' to edit itself. Here is the Javascript with an Ajax call to change the content:
function addLink(){
var ajaxRequest; // The variable that makes Ajax possible!
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send(null);
}
'addLink.php' adds things to a table, theoretically allowing the content function 'displayContent()' to show the new entries in the table ('displayContent()' queries a table).
The PHP call works fine, but I have to refresh the page to see the changes.
Is there some problem with how I am doing this? Possibly because there are already PHP calls in the inner HTML when the page is loaded in the first place?
Any help is appreciated, I'm a bit of a beginner with Ajax.
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
Sorry a little correction. You are attempting to access the pre-ajax php scripts inside ajax callback function. That's not how it works. You want the data that is retrived after-ajax call. Ajax retrives the output from the GET request, and store in ajaxRequest.responseText. Try replacing that and then see what you get.
In your addLink.php you should add the link and then echo out the data that you wish to display as the responseText. What had happened is that you inject the data VIA addLink but you never actually display it on the client side VIA ajax correctly. However, when you refresh the page, the script retrives what has been injected and display it accordingly.

Categories