Data automatically change in ajax call - javascript

I am try to pass a div and elements in Ajax success response but it will automatically change and extra front slash the div .
my Ajax code is
$.ajax({
'method': 'GET',
'url': base_url +'show/elementshoe',
success: function(data) {
if(data == ""){
}else{
//alert(data);
$("#date-div-id").html(data);
}
}
});
in controller
public function elementshoe() {
$result = [];
$data = $this->elemtsModel->getRandompart($state);
if (!empty($data)) {
$i = 0;
foreach($data as $list){
$result.='<div class="data"><div class="icon"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32" height="32" viewBox="0 0 32 32"><defs>...'.$list->party .' Party';
}
}
$res = json_encode($result);
sendJsonResponse($res);
}
the alert data show the result like
" Array<div class=\"data\"><div class=\"icon\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" xmlns:xlink=\"http:\/\/www.w3.org\/1999\/xlink\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\"><defs>...Tirupathi govind Party "
so this element does show in web page
How to solve this issue, the start of the line the word Array and "" in starting and end of this data also remove that,please help me

You should return the html code directly from the controller without using the json_encode. Try using 'echo' instead of 'json_encode'.
public function elementshoe() {
$result = '';
$data = $this->elemtsModel->getRandompart($state);
if (!empty($data)) {
foreach($data as $list){
$result .= '<div class="data"><div class="icon"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32" height="32" viewBox="0 0 32 32"><defs>...'.$list->party .' Party';
}
}
echo $result;
}

Related

How to replace custom tag with span containing textual representation of tag

I'm trying make a visual representation of xml code in HTML.
A simple case is this:
Original source:
<g id="1">some content</g> other content <s/>
Desired output:
<span data-id="1"><g id="1"></span>some content<span data-closingof="1"></g></span> other content <span><s/></span>
I tried much with regex having great results, but in case of nested elements it fails.
Is there any other way? (for example some XML parser that will allow such transformations)
Thank you.
Unusual for me to suggest regex for XML processing, but this may be more appropriate.
$input = '<g id="1">some content</g> other content <s/>';
echo preg_replace_callback("/(<.*?>)/", function($tag) {
return "<span>".htmlentities($tag[1])."</span>";
},
$input);
This will look for any content in < and > and encode it - whilst enclosing it in <span> tags.
Outputs...
<span><g id="1"></span>some content<span></g></span> other content <span><s/></span>
As this is only a limited example, this may not fit all sizes, but may be worth a go.
Update:
With the update for adding the data-id I've updated the code, it keeps a stack of the levels of tags and adds in when a matching close tag is found (although it doesn't check the type of tag), it will ignore and self closed tags as these don't have any other content.
$input = '<g id="1">some <g>2</g>content</g> other content <s/>';
$tagID = [];
echo preg_replace_callback("/(<.*?>)/", function($tag) use (&$tagID) {
if ( substr($tag[1], -2) == "/>" ) {
$out = "<span>".htmlentities($tag[1])."</span>";
}
else {
$add = "";
if ( substr($tag[1],0,2) == "</" ) {
$id = array_pop($tagID);
if ( !empty($id) ) {
$add = ' data-closingof="'.$id.'"';
}
}
else {
if (preg_match('/id="(.*?)"/', $tag[1], $match)) {
$id = $match[1];
$add = ' data-id="'.$id.'"';
}
else {
$id = "";
}
array_push($tagID, $id);
}
$out = "<span{$add}>".htmlentities($tag[1])."</span>";
}
return $out;
},
$input);
I ended up with something like this.
class TagsConverter {
private $parser;
private $nestedIDs = [];
private $output = '';
function __construct() {
$this->parser = xml_parser_create();
xml_set_object($this->parser, $this);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($this->parser, "tagOpen", "tagClose");
xml_set_character_data_handler($this->parser, "tagData");
}
function __destruct() {
xml_parser_free($this->parser);
unset($this->parser);
}
function reset() {
$this->output = '';
$this->nestedAttribs = [];
}
function transform($xml) {
$xml = '<root>' . $xml . '</root>';
xml_parse($this->parser, $xml, true);
$finalOutput = $this->output;
$this->reset();
return $finalOutput;
}
function tagOpen($parser, $tag, $attributes) {
if (isset($attributes["id"]))
$this->nestedIDs[] = $attributes["id"];
switch($tag) {
case "bx":
$this->output .= '<span>' . htmlentities('<bx />') . "</span>";
break;
case "g":
$id = $attributes["id"];
$this->output .= '<span data-id="' . $id .'">' . htmlentities('<g id="'.$id.'">') . "</span>";
break;
default:
break;
}
}
function tagData($parser, $cdata) {
$this->output .= $cdata;
}
function tagClose($parser, $tag) {
switch($tag) {
case "g":
$id = array_pop($this->nestedIDs);
$this->output .= '<span data-closingof="' . $id .'">' . htmlentities('</g>') . "</span>";
break;
default:
break;
}
}
}
Example run:
$p = new TagsConverter();
echo $p->transform('<g id="1">test g <g id="2">222</g></g> <g id="3">3333</g> other <x/> content <g id="4">444</g> <bx/>');
<span data-id="1"><g id="1"></span>test g <span data-id="2"><g id="2"></span>222<span data-closingof="2"></g></span><span data-closingof="1"></g></span> <span data-id="3"><g id="3"></span>3333<span data-closingof="3"></g></span> other content <span data-id="4"><g id="4"></span>444<span data-closingof="4"></g></span> <span><bx /></span>
I wonder if there is a way to do in JS.
you can use this, but I dont know how your xml file looks like so I cant give you an example with your code.
this will make the xml in an array so you can easily get it out
$getXml = file_get_contents('xml.xml');
$xml = simplexml_load_string($getXml) or die("Error: Cannot create object");
this will loop trough the array
foreach($xml->channel->item as $item) {
//here you could do something like this
echo "<h1>";
print_r($item->title);
echo "</h1>";
echo "<br>";
}
you can also do this, this will print all elements from the xml
print_r($xml);
documentation about simplexml_load_string:
https://www.w3schools.com/php/func_simplexml_load_string.asp
if you dont understand plz comment

How to transfer data from sql to javascript?

I work with this example: https://www.sitepoint.com/dynamic-geo-maps-svg-jquery/ But I need get data from MySql DB.
I have 2 main files:
1) map.php (connect to db and show svg map)
2) map.js (show colorized map with static data)
In JS file I see rows:
enter code here
var regions=[
{
"region_name": "Lombardia",
"region_code": "lom",
"population": 9794525
},
{
"region_name": "Campania",
"region_code": "cam",
"population": 5769750
},
// etc ...
];
I need change value of region name to value from db. But I do not how?
In my php main variable are:
echo "Region: ".$row['region_name']."
echo "Code of region: ".$row['region_code']."
echo "Value: ".$row['value']."
First of all your PHP code should connect to the database, extract the data you are interested in and build a json string from it, just like the regions data from your example. Your PHP will return this json. You will probably want to work with json because it is the most ajax/js friendly format.
Your JS code should make a Ajax call to that PHP for retrieving the json formatted data. Assuming you are using jquery, it is something like this:
$.ajax({
url : "map.php",
dataType : "json",
done: function(data){
// the data parameter is the json returned by the php
// already converted to javascript object...
// Just like the regions array from your example.
}
});
For further information and options about the jquery ajax api, see http://api.jquery.com/jquery.ajax.
Normally you won't be modifying your js file. Instead you need to load your data from DB using i.e. an ajax call and then "give" it to the control you're using.
To do that you need i.e. a web service that returns your data and some javascript function that calls it. You can do something like this:
var jqxhr = $.get( "map.php", function() {
alert( "success" );
}).done(function(data ) {
refresh_your_map(data);
});
check https://api.jquery.com/jquery.get/ for more details
Edited - do something like this:
/* define this function in your js file*/
var getRegionsData = function()
{
var result =[];
$.ajax({ url: 'map.php',
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
//then do this
var regions=getRegionsData();
//the rest of your code from map.js
index.php
enter code here
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="map.css" rel="stylesheet" media="all">
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script src="map.js"></script>
<title>Моя карта</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "happy_user";
$password = "1234567890";
$dbname = "freesite_zzz_com_ua";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT region_name, region_code, value FROM map";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "region_name: " . $row["region_name"]. " region_code: " .
$row["region_code"]. " value: " . $row["value"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<h1>svg map</h1>
<div class="map">
<svg version="1.1" id="map_x5F_id" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="595.3px" height="841.9px" viewBox="0 0 595.3 841.9" style="enable-
background:new 0 0 595.3 841.9;" xml:space="preserve"
>
<g id="id_x5F_1">
<rect x="58" y="163" width="85" height="85"/>
</g>
<g id="id_x5F_2">
<rect x="143" y="163" width="85" height="85"/>
</g>
<g id="id_x5F_3">
<rect x="228.1" y="163" width="85" height="85"/>
</g>
</svg>
</div>
</body>
</html>
map.js:
var regions=[
{
"region_name": "region-1",
"region_code": "id_x5F_1",
"value": "10"
},
{
"region_name": "region-2",
"region_code": "id_x5F_2",
"value": "20"
},
{
"region_name": "region-3",
"region_code": "id_x5F_3",
"value": "30"
}
];
var temp_array = regions.map(function(item){
return item.value;
});
var highest_value = Math.max.apply(Math, temp_array);
$(function() {
for(i = 0; i < regions.length; i++) {
$('#'+ regions[i].region_code)
.css({'fill': 'rgba(11, 104, 170,' + regions[i].value/highest_value
+')'})
.data('region', regions[i]);
}
$('.map g').mouseover(function (e) {
var region_data=$(this).data('region');
$('<div class="info_panel">'+
region_data.region_name + '<br>' +
'value: ' + region_data.value.toLocaleString("en-UK") +
'</div>'
)
.appendTo('body');
})
.mouseleave(function () {
$('.info_panel').remove();
})
.mousemove(function(e) {
var mouseX = e.pageX, //X coordinates of mouse
mouseY = e.pageY; //Y coordinates of mouse
$('.info_panel').css({
top: mouseY-50,
left: mouseX - ($('.info_panel').width()/2)
});
});
});

Page Scrolling Effect With Ajax How Data Is Loaded Into The Page

I am loading data from a mysql table into a html table. I am using AJAX php Jquery to accomplish this. I need to make sure that the way I built this will work regardless of how much data is in the table.
Right now I am working with a table that is 5000 rows long but there will eventually be 88000 rows in this table.
I know if I load all the data on page load this could end up bogging down the server and the load time of the page.
My question is the way my logic is now will it load all the results into the $results and only query the needed amount of rows because it is paginated. Or even though it is paginated is my webpage taking every row in the whole database for load time.
if the whole table is being loaded how can I change the query to only load the data when needed. It loads on page scroll.
Also I need to write a search function. Since the data is paginated would I search the data in $results or query the table with separate search functions? Which way would provide less load times which would cause a bad experience for my user?
The AjAX
<script type="text/javascript">
jQuery(document).ready(function($) {
var busy = true;
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
(function($) {
$(document).ready(function() {
if (busy == true) {
displayRecords(limit, offset);
busy = false;
}
});
})( jQuery );
(function($) {
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#productResults").height() && !busy) {
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
})( jQuery );
});
</script>
This is how I am querying the database
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 5;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
By transferring a JSON object from the server the limit, offset and html (and maybe others lime status_messsage, etc.) values could be transferred to the client at the same time.
On the client side I meant something like this:
var limit = 5;
var offset = 0;
var assetPath = "<?php echo $assetPath ?>"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#productResults").append(json.html); // corr to $output['html']
$('#loader_image').hide();
if (json.html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.wuno.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
...and on the server side:
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
$sql = "SELECT * FROM wuno_inventory WHERE 1 ORDER BY id ASC LIMIT $limit OFFSET $offset";
// Make sure to handle invalid offset values properly,
// as they are not validated from the last request.
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
$output['html'] .= $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
$output['html'] .= '<tr class="invent">';
$output['html'] .= '<td>' . $res['wuno_product'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_alternates'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_description'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_onhand'] . '</td>';
$output['html'] .= '<td>' . $res['wuno_condition'] . '</td>';
$output['html'] .= '</tr>';
}
}
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
I do this exact thing you want on my site http://www.flixnetforme.com/ where as you can see as you scroll to the bottom of the page the next set of records is loaded. I have over 150,000 records but it only loads 36 at a time when the user scrolls to the bottom of the page.
The way you want to do this is is by loading your first initial records through ajax and not hardcode them into the page.
index.php
$(document).ready(function(){
var last_id;
if (last_id === undefined) {
genres = $("#genres").val();
$.ajax({
type: "POST",
url: "includes/getmorefirst.php?",
data: "genres="+ genres,
success: function(data) {
$( ".append" ).append(data);
}
});
};
};
<html><div class="append"></div></html>
In this example when the user gets to the page and is loaded it calls getmorefirst.php and return the first records.
getmorefirst.php is a file that will load the first set amount of records you want to show when the user gets to the page. In my case I load 36 records at a time when a user scrolls to the bottom of my page.
getmorefirst.php
$sql = "SELECT * FROM table ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
The last_id div is important so that ajax will know the last record sent and which one to pick up after when it loads the next set of 36 records.
.append is the div where I am appending the data from ajax when the user its the bottom.
.last_id is your key to knowing how to load the next set of records. In whatever order you send the records back its important that ajax knows the last ID of the record loaded so it knows where to start loading the next time ajax calls for more records. In my case when the users scrolls to the bottom of the page.
when user scrolls to bottom of index.php
if($(window).scrollTop() === $(document).height() - $(window).height()) {
last_id = $(".last_id:last").attr("id");
$.ajax({
type: "POST",
url: "includes/getmore.php?",
data: "last_id="+ last_id,
success: function(data) {
$( ".append" ).append(data);
}
});
return false;
};
};
last_id = $(".last_id:last").attr("id"); will get the last ID sent.
data: "last_id="+ last_id, will send the last id to getmore.php so it knows the last id of the record sent.
getmore.php
$sql = "SELECT * FROM table WHERE ID > '$last_id' ORDER BY ID ASC LIMIT 36"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$last_id = $row['ID'];
echo '<div>'.$row['column'].'</div>';
echo '<div style="display:none" class="last_id" id="'.$last_id.'"';
}
As you can see getmore.php will return the next 36 records but AFTER the last_id sent.
Hope this make sense and gives you a start.
Here is a reduced example of the JSON / AJAX mechanism that I have tested:
HTML (file test.html)
<html>
<head>
<!-- THE NEXT LINE MUST BE MODIFIED -->
<script src="../jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
var limit = 5;
var offset = 0;
// THE NEXT LINE MUST BE MODIFIED
var assetPath = "http://www.example.com/stackoverflow/test.php"
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
url: assetPath,
dataType: "json", // We expect to receive a json object
data: "limit=" + lim + "&offset=" + off,
async: true,
cache: false,
beforeSend: function() {
$("#content").html("");
},
success: function(json) {
limit = json.lim; // corr to $output['lim']
offset = json.offs; // corr to $output['offs']
$("#content").html(json.html);
window.busy = false;
}
});
}
</script>
</head>
<body>
<div id="content"></div>
<div onclick="displayRecords(limit,offset); return false;" style="cursor:pointer">Click to Call</div>
</body>
</html>
PHP (file test.php)
<?php
$limit = (intval($_REQUEST['limit']) != 0 ) ? $_REQUEST['limit'] : 5;
$offset = (intval($_REQUEST['offset']) != 0 ) ? $_REQUEST['offset'] : 0;
// Prepare the $output structure (will become a json object string)
$output = array(
'lim'=>$limit,
'offs'=>$offset+$limit,
'html'=>''
);
$output['html'] .= '<span style="color:red;">limit='.$output['lim'].', offset='.$output['offs'].'</span>';
// Now encode $output as a json object (string) and send it to the client
header('Content-type: application/json; charset=utf-8');
echo json_encode($output, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_FORCE_OBJECT);
Result
1st time
2nd time
nth time

parse return data from html to ajax

I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.

How to properly load one ajax request after another

I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Categories