So I'm having this issue where I lose all my data on the first window.location.replace try (The second time i reload the same page everything seems to work fine)
I have searched around and haven't found anything like this
Here is the code so I can explain my issue more toroughly:
$(document).ready(function() {
$('#login_form').on('submit', function(event){
event.preventDefault();
// Retrieve form data
var formData = {
'index' : $('input[name=user]').val(),
'password' : $('input[name=pass]').val()
};
//convert formData from JS object to PHP understandable
var formData1=jsObj2phpObj(formData);
var url= 'login.php';
//sending with post in ajax to register.php
$.post(url,{formData1:formData1})
.done(function(data){
if(!(data["Log_success"])){
alert("Log failed")
}
else
{
window.location.replace('http://localhost/CPPv2/admin_commented/index.html#home');
var draw_stringholder="";
draw_stringholder+=data["user_index"]+data["user_email"];
document.getElementById("myPanel").innerHTML=draw_stringholder;
}
}
So what my function does is that it sends data to a PHP page and recieves JSON encoded data back. The first time I submit the form I seem to recieve no network data back (I think it's because of the window.location.replace removing it) but after refreshing the page and submiting the form again everything works fine (The Index and email are written inside myPanel element).
I have tried using window.location / window.location.href ... (I think i tried every other function there is) and they just don't send me anywhere like they're not working at all. The if(!(data["Log_sccuess"])) part always works (so the client - server communication works fine).
It's also important to say that im using JqueryMobile-1.4.4 (also tried their redirect method didn't work)
To sum it up I would like to change my current page link to a other one without losing the server generated data. (Since Im bassicaly staying on the same page just changing the Id part of it). I can fix my issue by refreshing the page after I have logged in (sending server request after log in) but that doesn't seem like the right way to do it.
Instead of window.location.replace I used $.mobile.changePage( "#ulr", { transition: "slideup"} );
Related
I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓
I have made a Ajax Like Button. After clicking the like button, it takes around 800ms - 1100 ms to do the following things:
Open insertlike.php page in the background using Jquery
Add the like to database in insertlike.php page
Confirm the like using JSON
Turn the like button color into green.
But Facebook's and other website's Like button works very fast.
Facebook directly change the like button color on click or it only change after adding the like into database?
This is my code:
index.php code to make ajax request
$(".insertlike").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this);
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(form).children("button").html(data.addremove + " Watchlist");
$(form).children("input#addedornotsend").attr("value",data.addedornotsend);
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
Code inside insertlike.php
<?php
// Add to Database code
$response = new \stdClass();
$response->addremove = "".$addremove."";
$response->addedornotsend = "".$addedornotsend."";
die(json_encode($response));
Any way to insert the like button speed? Maybe some php cache trick or something like that? I am still newbie.
Edit: This is my server response time speed test:
You can follow the Event Based Architecture. As soon as, user clicks on the like button, put the message in queue and then write to DB in background(Data Grid also can be a solution here, not sure if PHP has good data-grid solutions). And response to client will be sent back, assuming DB record is updated successfully.
https://martinfowler.com/articles/201701-event-driven.html
If you are updating single table, 800ms - 1100 ms does not seem to be acceptable timeline. Try to tune your SQL, check if the DB is properly tuned.Try to use ConnectionPool etc.
In Facebook, a. apart from updating the DB on like, b. It also does other background processing like generating the NewsFeeds to relevant parties etc. I am speculating that FB might be doing part b using events based architecture rather than keeping the user to wait.
Why are you doing . submit(), you should be doing . click().
And what Facebook does is probably changing button's color right on click, without waiting for response. If the response results in error then probably the button's color is changed back to normal.
I am having a problem with posting data from javascript to php.I am using the $.post method, though due to conflicts with wordpress I am alos using $J = jQuery.noConflict().
Therefore consequently I have the following, in javascript:
$J = jQuery.noConflict()
x=1
$J.post('/the directory',{x: x}, function(data){
});
alert($J.cookie("y"));
In php I have:
if(isset($_POST['x']))
{
setcookie("y", 1);
}
else{
setcookie("y", -1);
}
Every time I get to see that y = -1, indicating that x in php is not found. What am i doing wrong?
What did I try so far, which all did not work:
Connecting the post to different events (when submit is pressed, or when page is loaded)
Putting the alert ($J.cookie("y")) between the brackets which are behind the function (data)
Trying to remove the J after the $ or adding them up front in php
I am a bit afraid that the problem of the post is because I added $J = jQuery.noConflict(). Though I used many other functionality and then I did not have any problem, do you maybe know the solution or can you help me into the right direction? Thanks in advance!
The entire premise is faulty, cookies are part of the HTTP header being sent with every request, and to receive new cookies you would have to receive a new header, which would require a pageload.
You can't do an ajax request and set a cookie on the server, and then expect it to be accessible in javascript on the clientside without actually reloading the page and receiving the new and modified headers containing that cookie.
I'm in a situation where I have an Ajax function making a call to a remote site, saving data into a database, then I want to refresh the current page to show the new data. The problem is I'm also using tabs, so I need to pass #tab6 with the URL to get the visitor back to the correct tab.
I'm using
window.location.href = '/clientarea.php?action=productdetails&id=<?php echo $_POST['pkgid']; ?>#tab6';
as my refresh code. It does appear to change the URL, since after it runs I can see #tab6 on the end of the URL. The problem is it's not actually doing a real refresh of the page data, because it's not showing the new info that's pulled from the remote server. I can see that data after a real refresh.
The hacky option would be to run the window.location.href code to get the anchor in the URL, followed by location.reload(); to get the new data, but I'd like to avoid that if there is a better way to handle it.
You should change something between ? and #.
E.g. you could add/replace a random value just before #, generated with Math.random():
window.location.href = '/clientarea.php?action=productdetails&id=<?php echo $_POST['pkgid']; ?>&random='+Math.random()+'#tab6';
Try
window.location.reload(true);
And hacky solution for chrome
setTimeout(function(){window.location.reload(true);},100)
Instead of window.location.href use window.location.assign.
I'm having a bit of difficulty conceptualising this: I have some data stored to a button:
var input2 = '<button id="viewmap1" class="viewmap">Find on Map</button>';
//MAKE DATA
$(input2).data('longlat', coords);
Now I want to send that data to another page. I understand I am to use jQuery post, eg:
$.post("test.html", { func: "getNameAndTime" },
function(data){
alert("Hello");
}, "json");
But im not entirely sure how to go about it. Can any one point me in the right direction? Thanks
Sending data to a different page isn't as simple as it sounds. If it were simple, crackers could manipulate all the other pages that you currently have open in browser tabs.
When you call $.post(), that just sends data to the server, not to another page. The URL is a way to tell the server how to process the data but it doesn't magically connect you to the browser tab/window which has test.html open.
The usual solution is to use a single page which contains the button and the elements to display the results (a.k.a "view"). You send the POST request and then update the view in the callback function.
$(input2).on('click', function(){
// do your post stuffs
});
then need to trigger the button click
$(input2).click();