On my register page, I am trying to set it up so that when somebody enters a username into the username box, it will either show a green check mark if the username doesn't exist, or a red 'X' if the username already exists. When the page loads though (the body tag is <body on_load="process();">), it doesn't come up with a picture, it comes up with the word "undefined".
JavaScript code:
var xmlHttp = createXmlHttpRequestObject();
//Create object for function
function createXmlHttpRequestObject(){
var xmlHttp;
//Check if IE
if(window.ActiveXObject){
try{
//Setting variable equal to object for IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}else{
//Anything not IE
try{
//Want to use this object if not IE
xmlHttp = new XMLHttpRequest;
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}
//If couldn't set object
if(!xmlHttp){
//Tell people that JS couldn't create the object (new XMLHttpRequest or ActiveXObject)
alert("Couldn't create an object with JavaScript!");
}else{
//Return object
return xmlHttp;
}
}
//Use this attribute for body tag: <body onload="process()">
function process(){
/*readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
*/
try{
//Check if ready to communicate
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
//<input type="text" id="userInput" /> relates to this
//Set variable to value they typed in
username = encodeURIComponent(document.getElementById("register_name").value);
//Creates request to send to server
//Need PHP file, GET would be in PHP file, also can be POST, etc.
xmlHttp.open("POST","functions/check_used.php",true);
//Doing something to make it pretend like it's a form, for POST
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Handle server response when server responds to the request
xmlHttp.onreadystatechange = handleServerResponse;
//Send request (this is used for POST, use null when using GET)
xmlHttp.send("username="+username);
}else{
//Not ready to communicate, wait for 1 second and try again
setTimeout('process()',1000);
}
}catch(e){
//Something doesn't work, tell them what happened
alert(e.toString());
}
}
//When response received, tells what to do with it
function handleServerResponse(){
//Response done communicating
if(xmlHttp.readyState==4){
//Communication went OK
if(xmlHttp.status==200){
//Put response into variable
xmlResponse = xmlHttp.responseXML;
//Get document element
xmlDocumentElement = xmlResponse.documentElement;
//Get data from XML file
message = xmlDocumentElement.firstChild.data;
//Access document, put it in element on page, innerHTML is stuff shown on webpage
document.getElementById("checkedUser").innerHTML = message;
//Pause 1 second before communicating with server again
setTimeout('process()',1000);
}else{
//There was an error with data
alert('Something went wrong!');
}
}
}
On the register page, I have an input box with the div next to it:
<input type="text" id="register_name" name="username" /><div id="checkedUser"></div>
Finally, I have the PHP file that it is posting to:
<?php
require_once('../includes/db.php');
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<username>';
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
echo '</username>';
?>
I have tried troubleshooting it, but I couldn't figure out what was wrong.
Listen for keystrokes in input, and check username when the input changes :
$(function() {
$('#register_name').keyup(function() {
$.ajax({
type: 'POST',
url : 'functions/check_used.php',
data: {username : this.value},
success: function(result) {
$('#checkedUser').html(result);
}
});
});
});
And there's no need to return XML:
<?php
require_once('../includes/db.php');
header('Content-Type: text/html');
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
?>
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
should be
if(xmlHttp.readyState== 4 && xmlHttp.status == 200){
Related
I am working in php where I am inserting some values to data base. And for that purpose i am using Ajax method.I am calling Ajax function on button click and inside ajax i am calling another php file where insertion occur and session variable update. But when insertion occur and i want to show the updates session variable in Ajax response, it shows old session variable and does not show the updated session vairable.
function showDiv() {
document.getElementById('HelpDiv').style.display = "block";
var value ="<?php echo ''.$_SESSION['user_name']; ?>";
alert(value);
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
// alert("ajax start");
} catch (e) {
alert("Your browser broke!");
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
//alert("start2");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
// alert("start3");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var qst_id="<?php echo''.$question_id;?>";
// Create a function that will receive data sent from the server and will update div section in the same page.
ajaxRequest.onreadystatechange = function() {
//var value ="<?php echo ''.$_SESSION['user_name']; ?>";
//alert(value);
var t = ajaxRequest.readyState;
if (t == 4) {
document.getElementById("a").innerHTML = "<?php echo ''.$_SESSION['user_name']; ?>";
// alert("ajax received");
var startSession = "<?php session_start(); ?>";
var value = "<?php echo ''.$_SESSION['user_name']; ?>";
alert(value);
}
// if (ajaxRequest.readyState == 4) {
// alet("ajax received");
// }
}
// passing value to the server script, ajax file
var queryString = "?question_id=" + qst_id;
ajaxRequest.open("GET", "ajax-login.php" + queryString, true);
ajaxRequest.send(null);
}
<?php
session_start();
$_SESSION['user_name'] = "asasd3";
echo "".$_SESSION['user_name'];
?>
First understand that $_SESSION variable are different than the HTML session variables :
please read for more info on PHP session variable on https://www.tutorialspoint.com/php/php_sessions.htm
I am using jQuery to ease solution
$.ajax({
method : "POST",
url: "someFileToUpdateTheSession.php",
data: $(this).serialize(),
success: function(data){
// Do what you want to do when the session has been updated
alert(data);
console.log(data);
}
});
PHP Side
<?php
session_start();
$_SESSION["user_name"] = 'anything you want';
echo $_SESSION["user_name"];
die();
?>
I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";
I've hit a brick wall in my chat system project and I have tried all day to find a solution. So here I am.
In the file insert.php I am trying to use $_REQUEST to get the value of the textarea from chat.php.
When I type something in and click send, a blank message is sent to the database.
After playing around with it, sometimes the webpage displays a "1" in the div element im trying to display the message in.
Any help would be very much appreciated thank you.
chat.php
<!DOCTYPE html>
<html>
<head>
<title>{ Chat App }</title>
<link rel = "stylesheet" href = "styles/style.css" media = "all" />
<script src="insert.js"></script>
<link href='https://fonts.googleapis.com/css?family=Rokkitt' rel='stylesheet' type='text/css'>
</head>
<body>
<form name = "form1">
<textarea name = "message"></textarea>
<br>
Send
<br>
<div id = "msg"></div>
</form>
</body>
</html>
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
insert.php
<?php
include("connection/connection.php");
global $con;
$msg = isset($_REQUEST['msg']);
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
$get_msg = "SELECT * FROM msg ORDER by id DESC";
$run_msg = mysqli_query($con, $get_msg);
while($row = mysqli_fetch_array($run_msg)){
echo $row['message'];
}
?>
The first problem is when you check for the null value, the function continues and submits the form if it is null or not.
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
// stop the submit action
return;
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
The next problem is in the form handler, you are saving a boolean value isset($_REQUEST['msg']). Try this
insert.php
...
$msg = (isset($_REQUEST['msg']) && !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : false;
if($msg){
// save data to database
...
}
or
...
if((isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
// message was submitted and it is not an empty string
$msg = $_REQUEST['msg'];
// save data to database
...
}else{
// do nothing
}
xmlhttp.open('GET', 'insert.php', true); try changing to xmlhttp.open('GET', 'insert.php?msg='+msg, true);
Hope it helps !
better to add "return" on error when you check if message is empty
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
so it could be
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
return;
}
in submit() function
so the rest of function will not execute and empty message won't be sent.
and assign to variable message not the validation ))
if(isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
$msg = $_REQUEST['msg']; //addiotionally this need escape
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
}
My code makes an xmlhttp request to a php file, sending an ID so that a record can be identified and deleted from the database. However, when performing the delete query, I'm get an error saying 'comicID' is undefined (the variable using the ID value sent by POST). I'm not sure how to make sure it is defined correctly. Currently, the error I'm getting back from error handling is: "No comic supplied." and the error I get when removing the ISSET section of code is: "Error. Pages in comic not deleted." As it stands, the delete query doesn't work.
Javascript:
function delComic()
{
var radioButtons = $("#listID input:radio[name='comicList']");
var radioID = radioButtons.index(radioButtons.filter(':checked'));
console.log(radioID);
if (radioID < 0)
{
window.alert("You must select a comic before deleting.");
}
else
{
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php?comicID="+radioID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
}
PHP:
<?php
if (isset($_POST["comicID"]))
{
$comic = $_POST["comicID"];
$dir = 'comics/'.$comic.'/';
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
include_once('includes/conn.inc.php');
mysqli_query($conn, "DELETE FROM serieslink WHERE comicID = '$comic'");
$query = ("DELETE FROM page WHERE comicID = '$comic'");
if (!$result = mysqli_query($conn, $query))
{
echo ("Query1 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
$dirHandle = opendir($dir);
while($file = readdir($dirHandle))
{
if(!is_dir($file))
{
unlink("$dir"."$file");
}
}
closedir($dirHandle);
rmdir($dir);
$query2 = ("DELETE FROM comic WHERE comicID = '$comic'");
if (!mysqli_query($conn, $query2))
{
echo ("Query2 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
echo ("The selected comic was successfully deleted.");
}
else
{
echo ("Error. Comic not deleted.");
}
}
}
else
{
echo "Error. Pages in comic not deleted.";
}
}
$conn->close();
}
else
{
$comic = null;
echo "No comic supplied";
}
?>
With POST you do your Ajax request different that with GET. The query string is an argument to the send() function rather than part of the url, and you leave off the ?:
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send("comicID="+radioID);
Edit:
You also really should urlencode the parameter values, if they can contain spaces, etc. And to circumvent possible browser caching you can add a parameter with the time:
var d = new Date();
xmlhttp.send("comicID="+encodeURIComponent(radioID)+"&ts="+d.getTime());
There's no need to read that timestamp param on the server-side; its only to trick the browser.
Change the three first lines to, and everything should work fine.
if (isset($_GET["comicID"]))
{
$comic = $_GET["comicID"];
I actually solved it myself by accident. It turns out the error is that the program is halting at the point that it tries to delete all pages associated with a comic. When it is presented with an already empty comic, it tries to delete nonexistent records. Manually adding a page to the comic and THEN trying to delete the comic outright worked perfectly.
So basically, I just need error handling for empty comics.
Thanks for the pointers regarding POST, however.
I have main file index.php. Where user perform login I load url.php in <div> inside index.php through ajax request.
Now on url.php, on button click event I submit the form and post data to data.php file. As url.php is loaded into index.php, button click event on url.php will call function in section of index.php.
I am getting two variable $x and $y as a result on data.php.
On index.php I have JS function where I want to use $x and $y. How can I retrieve?
index.php
<script type="text/javascript">
//------------------script 2 starts ---------
function showUser(form, e) {
//alert(myid);
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var sent = form.elements['sent'].value;
//var sent2 = form.elements['sent2'].value;
//alert(sent2);
//var divElements = document.getElementById('d1').innerHTML;
var text1 = document.getElementById('previewUrl').innerText || document.getElementById('previewUrl').textContent;
var text2 = document.getElementById('previewTitle').innerText || document.getElementById('previewTitle').textContent;
var text3 = document.getElementById('previewDescription').innerText || document.getElementById('previewDescription').textContent;
//alert(text3);
console.log(sent);
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
sent = encodeURIComponent(sent);
text1 = encodeURIComponent(text1);
text2 = encodeURIComponent(text2);
text3 = encodeURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
}
</script>
+
$.ajax({
url:'url.php'
,async: true
,type : 'POST'
,cache: false
,data : 'myid=' + myid
,dataType: 'html'
,success: function(data){
$('body').html(data);
FB.XFBML.parse();
}
}
);
url.php
<form action="data.php" method="POST" onsubmit="showUser(this, event)">
data.php
if (preg_match_all('/[^=]*=([^;#]*)/', shell_exec("/home/technoworld/Desktop/test/b '$test'"), $matches)){ //Values stored in ma.
echo "hi";
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
this x and y I want to fetch in index.php.
I know this is not impossible. But complex to thing for me!
My preferred method of sending data back from the server side is responding with JSON response..
$data['x'] = $x;
$data['y'] = $y;
header('Content-Type: application/json');
echo json_encode($data);
That should give a response to your ajax callback, so you could use it like this:
$.post('data.php', { "myid": id }, function(data) {
console.log(data.x); //data.x = $x
console.log(data.y); //data.y = $y
});
I didn't test the code to see if it actually works, but it should give an idea of what to do. Let me know if it makes sense :)
If you want to retrieve only two value.
Simplest solution just like boiling a egg is:
just print both value in with separating value like ':'
echo $x.':'.$y;
and when you getting response. separate value with ':' and then you can use them..
or JSON response is also good practice for this.