how to adjust margin session flash in php? - javascript

I am trying to flash a success message when data store successfully. My database code and every other thing working fine but when I give $_SESSION success message it always come under navigation.
1) I want to know is there any way in php to set margin of $_SESSION['success_flash'] message
2) is there any way like /n/n type so that my flash message will show two line below
3)
My real code is:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried /n/n but not working:
$_SESSION['success_flash'] = '\n\n<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
I tried style="margin-top:200px;" but not working:
$_SESSION['success_flash'] = '<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
Kindly check the image below only green background is showing under the navigation bar and the text message "Data saved successfully!" not showing because it is hidden under the navigation.
One more thing I am using below code after the flash message and my code end.
echo "<script type='text/javascript'> document.location = 'index.php'; </script>";
Any idea or suggestion would be helpful.
Thanks you.
I am getting data and passing the data to database successfully. I just want to reload my page after php call and show sucess flash to the user.
My Ajax Call: top my php page.
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>

PHP once loaded it does not change on the page, it is not dynamic. The way you do this is rather weird, but can be acomplished if you will set $_SESSION['success_flash'] just right after saving the data in the database, and reaload the page.
In my opinion the best way is to use ajax here, and the ajax response can change the container under the menu to "success".
But I don't know how do you send your data, is it by POST form or something?

Add display:inline-block; or display:block; in the styles of the span.
As long as dom elements behaviour can depend on outer dom objects (and you do not specify them): if it still does not work try using padding instead of margin, if it still does not work place two span tags one inside other both with inline-block.
All that stuff using $_SESSION is kinda weird, however XD... but from your description I assume that it shows already the span, but without the margin... but you should not use $_SESSION in that way.

OK, now we are getting somewhere. But now location.reload is unnecessary, because if you will receive 'passed' answer, you can set the communicate without reloading (and without using any code in session variable, get rid of $_SESSION['success_flash']), like below.
Please note that I do not know what is the CSS class or ID of your green DIV (if any), so for this specific example I will assume, that it has a class ".msg-response"
<script>
function createD () {
var data = {
'name' : jQuery('#name').val(),
'phone' : jQuery('#phone').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/mycodpage/includes/codfile/product.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
// This will show error
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
//clear the errors if any
jQuery('#modal_errors_1').html("");
// this new line will change the content of your message div
$('div.msg-response').html('<span style="margin-top:200px;color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>');
}
},
error : function (){alert("Something went wrong.");},
}); //Ajax call End Here
}
} // Function End
</script>
there is also a security risk here: "if (data != 'passed')" - you will echo PHP errors (path, filename, variables, class, code row etc.) when something unpredictionary will happen, unless you will turn display_errors off on your server (display errors should be enabled only in development mode, that's a good practice).
To avoid it you can use JSON response here, handle the "error" status, "success" status, and do nothing if JSON response is different from "success" or "error".

Related

Send JS variable to PHP on another page without form

I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player's profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page.
I'm new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I've come to:
$(document).ready(function() {
$('#playerList td').click(function(e) {
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function() {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don't think I'm understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I've seen) to a url, but can also return information from a page? That's where I'm a bit confused and am wondering if I'm just using it wrong.
As a quick note: playerList is my table's id.
When I click the hyperlink, it takes me to profile.php, which is what I want, but php's $_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both 'playersSteamID' and 'playersName'. var_dump() returns NULL as well, so I'm wondering if there's a problem with the way the data{} field is being sent in the ajax. I'm still very new to this so any help would be much appreciated.
Update: How I'm accessing the variables in profile.php
<?php
echo var_dump($_POST['playersName']);
echo var_dump($_POST['playersSteamID']);
if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}
?>
The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $_POST[] is empty I can't continue past the above point as the first two lines return null and the conditionals are never true since isset() is false.
The ajax is used to, post or get parameters/info from/to URL without redirecting/refreshing/navigating to a particular page.
Please note down without redirecting/refreshing/navigating
In your case you want to send 2 parameters to profile.php and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice.
Solutions:-
-> Use normal form submission kinda thing, and post the parameters to profile.php, in this case you will get redirect to profile.php and can expect proper functionality.
You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}.
you function would look like this...
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
//Do some other stuffs
document.forms['someform'].submit();//submitting the form here
}
});
});
The rest in profile.php remains same.
-> If you really wanna use ajax do following.
Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page.
You should change the way your response is in profile.php file.
for eg:-
<?php
if(isset($_POST['playersSteamID'])){
$name = $_POST['playersName'];
$id = $_POST['playersSteamID'];
//Do your stuff here db query whatever
//Here echo out the needed html/json response.
echo "<h3>".$name."</h3>";
echo "<h4>".$playersSteamID."</h4>";
}
?>
The response {from: echo} will be available in data of function(data) in ajax success, you can use this data in whatever you want and however you want.
for eg:-
success: function(data){
console.log(data);//for debugging
$('#mydiv').html(data);//appending the response.
}
-> Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website.
$_SESSION['steamID'] = //the steamID here;
This variable can be used anywhere in site use by calling session_start() in the page, you want to use sessions.
for eg:-
click here to view your profile
profile.php
<?php
session_start();
$id = $_SESSION['steamID'];
//echo var_dump($_POST['playersName']);
//echo var_dump($_POST['playersSteamID']);
/*if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}*/
echo $id;
//Do your work here......
?>
For any queries comment down.
A hyperlink may be causing the page navigation, which you dont want.
Page navigation will make a get request but your endpoint is expecting a post request.
You can stop the navigation by setting the href to # or by removing the <a> altogether.
You could also try calling the preventDefault on the event object.
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function(data) {
console.log('success', data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});

$("Div").load() appending html page after completion of $(document).ready() when written inside $(document).ready()

Sorry if this type of question is already been answered.
I am trying to add a page using $("Div").load() inside $(document).ready().
Page is getting loaded but it is not showing anything inside its' variables.
Steps in my code:
Page starts loading
Value come from back-end code (spring java)
Loading a specific page when values are present and show them on page.
If values are null, do not load page.
Jquery version: "2.1.3"
Below is my code:
$(document).ready(
if(condition1){
var var1= data //some json data;
$('#divId').load('url/mypage.jsp');
if(condtition == true){
myFunctionToProcessData(var1);
}
}
)
I have tried ajax call, but its not working.
After completion, I can see my page is loaded and appended in division but not showing on UI and have empty variables.
Please help.
Thank you for your responses. I could not reveal my full code, so made a snippet to give an idea about what i wanted. Issue is fixed now.
Issue was: I wanted to append a JSP on certain condition inside $(document).ready() but the working of $(document).ready() is something like, it ensures executions of methods and conditions written inside it.
Problem was:
Method "myFunctionToProcessData" and "$('#divId').load('url/mypage.jsp');" was called simultaneously , and HTML was not complete at the same time when method called and due to this, my method did not find division to set values and do other validations.
To solve this I have used below approach:
Appended html/jsp page using .load function.
used an ajax method in which i am getting data.
execution steps:
1. Code appended HTML in some time (Using setTimeout function)
2. after execution of all lines in $(document).ready(), ajax function called
3. Now myFunctionToProcessData ca find divisions to set values and proper out put shown on the UI.
code:
$(document).ready(
if(condition1){
var var1= data //some json data;
setTimeout(function() {
$('#divId').load('url/mypage.jsp');
}, 10);
if(condtition == true){
$.ajax({
type : "GET",
contentType : "application/json",
data : "&sid=" + Math.random(),
url : "url", // change to full path of file on server
success : function (data) {
myFunctionToProcessData(var1);
});
}
}
)
This is just a workaround to make sure that myFunctionToProcessData executes only after jsp appended succesfully in it.
now myFunctionToProcessData is executing at the end.

Location: Header not working for one particular trigger

Okay, so, I have a PHP and JS-based webapp that does mostly what it's supposed to do. This being said, before I show any code, bear in mind a few things.
1.)The top two location headers inside the 'if' loops work as intended.
2.)In the development tools in Chrome, the location is in the header for this request.
PasteBin to my code here.
In my JQuery (defined in html head), we see a button name "subAll2", which is supposed to post the intended data, and do a redirect using aforementioned JQuery. The other two redirects work via intended forms. Why does this one not work?
$('#subAll2').click(function() {
var action = $('#frmUser').attr('action');
$.ajax({
url : action,
type : 'POST',
data : $('#frmUser,
#frmUser2').serialize()+"&butSubmitAll=submitAll",
success : function() {
window.location.replace(action);
}
});
return false;
});
Obligatory codeblock for requirements. Please check the PasteBin.
I found the answer. In the JS, replace the success function with
success : function(data) {
if (data == "success")
windows.location = "list_user.php";
else
alert("Form didn't go through.");
}
And instead of
header("Location:list_user.php");
Replace with
echo "success";

Auto refresh with ajax/jQuery after initial form submit then change page title

I have a form set up that, when submitted, uses an ajax call to retrieve data via a PHP file that in turn scrapes data from a given URL based on the input field value.
Everything is working perfectly, but what I'd like to do now is implement a couple of additional features.
1) After the initial form submission, I'd like it to auto-update the query at set intervals (Chosen by the end user). I'd like to append the new results above the old results if possible.
2) When new results are returned, I'd like a notification in the title of the page to inform the user (Think Facebook and their notification alert).
Current jQuery/Ajax code:
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'jobSearch.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.val('Searching....'); // change submit button text
},
success: function(data) {
$('#container').css('height','auto');
alert.html(data).fadeIn(); // fade in response data
submit.val('Search!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
I'm not too sure how I'd go about this, could anyone give me an insight? I'm not after somebody to complete it for me, just give me a bit of guidance on what methodology I should use.
EDIT - jobSearch.php
<?php
error_reporting(E_ALL);
include_once("simple_html_dom.php");
$sq = $_POST['sq'];
$sq = str_replace(' ','-',$sq);
if(!empty($sq)){
//use curl to get html content
$url = 'http://www.peopleperhour.com/freelance-'.$sq.'-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}else{
$url = 'http://www.peopleperhour.com/freelance-jobs?remote=GB&onsite=GB&filter=all&sort=latest';
}
$html = file_get_html($url);
$jobs = $html->find('div.job-list header aside',0);
echo $jobs . "<br/>";
foreach ($html->find('div.item-list div.item') as $div) {
echo $div . '<br />';
};
?>
Question 1:
You can wrap your current ajax code in a setInterval() which will allow you to continue to poll the jobSearch.php results. Something like:
function refreshPosts(interval) {
return setInterval(pollData, interval);
}
function pollData() {
/* Place current AJAX code here */
}
var timer = refreshPosts(3000);
This has the added benefit of being able to call timer.clearInterval() to stop auto-updating.
Appending the data instead of replacing the data is trickier. The best way, honestly, requires rewriting your screen scraper to return JSON objects rather than pure HTML. If you were to return an object like:
{
"posts": [
// Filled with strings of HTML
]
}
You now have an array that can be sorted, filtered, and indexed. This gives you the power to compare one post to another to see if it is old or fresh.
Question 2:
If you rewrote like I suggested above, than this is as easy as keeping count of the number of fresh posts and rewriting the title HTML
$('title').html(postCount + ' new job postings!');
Hope that helps!
If i understand correctly. . .
For updating, u can try to do something like this:
var refresh_rate = 2500
function refresh_data() {
// - - - do some things here - - -
setTimeout (refresh_data(),refresh_rate); // mb not really correct
}
You can read more about it here
Hope, i helped you

Twitter API getJSON for Status ID Meta -- Response Empty!

There are some similar posts on SO about this topic but they are all dealing with search and I am trying to do something different. I have tried to apply some of the logic in answers to other questions here but w/o success. Essentially I just want users to be able to enter a status update ID into a text field, hit a button then display all meta data associated with that tweet. If I leave the callback=? part off of the URL string I get a response back but it's empty, which is obviously due to the security restrictions put in place by the Twitter API.
Here is what I am working with currently:
$.getJSON("http://www.twitter.com/statuses/show/73051651728084992.json?callback=?",
function(Data)
{
if(Data.length)
{
var Content = "";
$.each(Data, function(i, Row)
{
alert("We Have Data");
Content += Row;
});
$("#Result").append(Row);
}
else
alert("No Result for that ID!");
})
Which comes back w/ no data, yet the request does come back w/ a 200 HTTP response. Obviously I am missing something as far as the callback goes, I am just not sure what. Just as a crude proof of concept I was going to output all of the data to the Result div and pretty it up later. Obviously first things first I need to actually have some data to work with!
What am I missing?
Remove the ?callback=? from the url and try again. You are asking Twitter's api to wrap the response in a callback ? which would result in invalid JSON. Also, whenever in doubt, load the url manually in your browser to examine whether the response is correctly formatted.
Also, change to this, since $.getJSON() returns an Object, not a string:
if (Data) {
var Content = "";
..
}

Categories

Resources