AJAX won't load new page content without page refresh - javascript

I executed an AJAX request to load content into my page. Here's the function I created for this request:
function displayForums() {
var session = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/threads/display_forums.php',
data: 'POST',
data: {session: session},
success: function(data) {
console.log("display successful");
$(data).appendTo("#forums-container");
}
});
}
Then, I call this function I just declared (displayForums()) when the document loads:
$(document).ready(function() {
displayForums();
});
Finally, I have an AJAX call that submits user input from a form into a database.
$("#start-thread-form").on("submit", function(e) {
e.preventDefault();
var forum_title = $("#start-thread-form input").val();
var forum_message = $("#start-thread-form textarea").val();
var id = "<?php echo $_SESSION['id'] ?>";
$.ajax({
url: 'includes/threads/insert_forums.php',
type: 'POST',
data: {forum_title: forum_title, forum_message: forum_message, id: id},
success: function(data) {
console.log(data);
$(".success-msg").append("Thread created successfully" + "<br>").show();
setTimeout(function() {
$(".success-msg").hide();
$(".success-msg").text('');
}, 2000);
$('input[type="text"],textarea').val('');
displayForums();
},
error: function(requestObject, error, errorThrown) {
console.log(error);
console.log(errorThrown);
}
});
});
The problem is that when the AJAX call that inserts data into the database completes, the original AJAX call doesn't load the new data into the page unless I refresh the page. I tried placing the displayForums() function inside of the success function, but it didn't work. How can I adjust the AJAX calls to load the newly inserted data without refreshing the page?

You run your JavaScript when the submit event of a form fires.
The default behaviour of a form submission is to make an HTTP request to the action and load the response as a new page.
If you don't want the form to submit, then you have to stop it.
$("#start-thread-form").on("submit", function(event) {
event.preventDefault();

$(document).ready(displayForums());
this is WRONG, it should be:
$(document).ready(function() { displayForums() });

Related

Page is getting Submit Without Refresh Via Otp?

I got this website when I fill the information and try to send the OTP page reload
Here's the website:
https://tunisia.blsspainvisa.com/english/book_appointment.php
After you fill the information and click on (Request verification code) and you will know what I mean
What I tried is:
$(function () {
$('#tunisiaThird').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://tunisia.blsspainvisa.com/book_appointment.php',
data: $('#tunisiaThird').serialize(),
success: function () {
}
});
});
});
I'm only a client, so I'm using Tampermonkey to inject.
You need to read more about jquery ajax post or get method here:
https://api.jquery.com/jQuery.post/
And there are tons of questions here if you search you will find tons of examples
Here is a complete example, which is getting error messages from php part and displaying on html form.
Like this: in php : $error .= 'an error happend'; and ajax $('#result').html(data.error);
to display in html.
<div id="result"></div>
$(document).ready(function(){
$('#tunisiaThird').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"book_appointment.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html('Successfuly');
$('#tunisiaThird')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
}
}
});
});
});

AJAX post method working in one area but not another

I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!

Form submit Ajax using jQuery sometimes does not works

I am doing form data submit using Ajax with jQuery.
When I submit form on popup window, I refresh the parent page.
My code:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webapp/addSpeedDataAction.do",
data: $(this).serialize(),
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});
However page gets refreshed on success of callback but i can not see update on my parent page. Sometimes I can see updates and sometimes not. What is the issue? I also need to know how I can write it in native javascript and submit form using ajax javascript.
Maybe your getting this error due the fact that javascript is async and your code will proceed even when you have yet no response from the request.
Try this:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webfdms/addSpeedDataAction.do",
data: $(this).serialize(),
async: false, // This will only proceed after getting the response from the ajax request.
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});

Make page refresh if successful login with ajax/jquery

Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?
Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);

jQuery AJAX post to PHP everytime a click is fired off

I want to keep a record of every click that occurs within a specific DIV and child DIVS on page. The client should not be aware of this. Inside of the div is a link to an external website.
Client clicks link inside div > ajax inserts record in db > client is sent to site of link clicked
PHP on page
include('quotemaster/dbmodel.inc.php');
if(isset($_POST['dataString'])) {
clickCounter();
}
PHP Model Function
function clickCounter() {
global $host, $user, $pass, $dbname;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$stmt = $DBH->prepare("INSERT INTO clickcounter (counter) VALUES (1)");
$stmt->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
AJAX POST
$(function() {
$("body").click(function(e) {
if (e.target.id == "results" || $(e.target).parents("#results").size()) {
//alert("Inside div");
ajax_post();
}
});
})
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: dataString });
}
The problem I am having (I think) is that the AJAX post is not being sent. Any ideas? Thanks!
on your PHP you have
if(isset($_POST['dataString'])) {...
you are expecting a parameter named dataString so you can fix it on your javascript ajax_post function with something like
var postData={dataString:true, CC:1}
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: postData });
this way jQuery will create the proper dataString parameter.
Hope this helps
Try changing the POST check to:
if(isset($_POST['CC'])) {
clickCounter();
}
Also, if your DIV contains a link that navigates away from the page, clicking the link may cause the page location to change before the event bubbles down to the body tag. If so, you could try attaching an event to the link which calls preventDefault and therefore allow the event to bubble. If so, you could then detect that the user clicked the link and perform the navigation manually after recording the click. To show code as to how this can be achieved you need to post your full div code (including the link).
To add callbacks to the ajax call:
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({
type: "POST",
url: "tq/--record-events.inc.php",
data: dataString,
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

Categories