AJAX post method working in one area but not another - javascript

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!

Related

The URL string changes after ajax call return

I have been struggling with a problem for some time. I cannot understand the reason as it happens in a specific case, not with the others.
I have a javascript function that calls a PHP script to upload a file to the server (standard code, have been using it and works perfectly normally).
function upload_picture(fieldID, success, error) {
var folderName;
switch (fieldID) {
case "pop_drawing":
folderName = "pop_dwg";
break;
case "pop_installation":
folderName = "pop_inst";
break;
case "pop_picture":
folderName = "pop_pict";
break;
}
var file_data = $('#' + fieldID).prop('files')[0];
var form_data = new FormData();
form_data.append('folder', folderName);
form_data.append('file', file_data);
$.ajax({
url: 'dbh/upload.php',
dataType: 'text',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
if (response.indexOf("yüklendi") > 0) {
success();
}
},
error: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
error(response);
}
});
}
The function is called from several points in the code and it works OK except one point. At this particular point when it returns it changes the page URL from
http://localhost/pop/#
to
http://localhost/pop/?pop_drawing=&pop_installation=&pop_picture=Compelis-Logo.jpg&pop_need_special_prod=Hay%C4%B1r&pop_need_application=Hay%C4%B1r&pop_order_made=Evet&pop_approval=4&pop_cost_visible=Hay%C4%B1r#
due to a reason I could not understand. This string in the URL line are some parameters on the web page where I press the button to call the function.
The code which call the function is:
function uploadPopPicture () {
if ($('#pop_picture_label').html() !== 'Seçili dosya yok...') {
upload_picture('pop_picture',
function(){
console.log('Görsel yüklendi...');
},
function(error){
console.log('Error:', error);
});
}
}
Same code (obviously with different parameters) is used elsewhere in the program and works OK.
Any ideas what I might be missing.
Many thanks in advance
A button's default behaviour is "submit". If you don't specify any particular behaviour then that's what it will do. So when clicked it will submit your form, regardless of any JavaScript.
Add the attribute type="button" to your button HTML and that will stop it from automatically submitting the form.

Not receiving data from ajax to php

I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});

Trying to post a variable from js to php within a if clause

I am trying to post a variable within a if clause, but the php document is not receiving the variable.
Here is some Code:
JS:
if(data.details.payment_type =="sofo") {
var orderid = data.details.order_id;
$.post("LinkToPhpDocument.php", { orderidvalue: orderid });
window.location.replace("LinkToPhpDocument.php");
}
PHP
$orderID = $_POST['orderidvalue'];
You need to wait for Ajax ended then redirect user:
if(data.details.payment_type =="sofo") {
var orderid = data.details.order_id;
$.post("LinkToPhpDocument.php", { orderidvalue: orderid },function(res){
window.location.replace("LinkToPhpDocument.php");
});
}
Try this :
if(data.details.payment_type =="sofo") {
var orderid = data.details.order_id;
$.ajax({
url: 'LinkToPhpDocument.php',
type: POST,
data: 'orderidvalue='+orderid,
cache: false,
success: function(res){
window.location.replace("LinkToPhpDocument.php");
}
})
}
Note : It will only replace the window location not redirect you to the LinkToPhpDocument.php page.It navigates to the URL without adding a new record to the history.

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);
}
});
}

AJAX success callback only carrying out first function

I've got a simple form submission that upon success I've got an alert and a call to clear the form. I do get the alert, the info gets successfully added to the database, but the second call--for the form to clear, is not being carried out. I'm sure it's something simple I'm doing wrong, but I can't figure it out.
$('#contact_submit').click(function(e){
if ($("#submit_form_contact").valid()) {
var post_data = {
"name" : $('#name').val(),
"email" : $('#email').val(),
"inquiry" : $('#inquiry_dropdown option:selected').text(),
"message" : $('#message').val()
};
$.ajax({
type: "POST",
url: "process-contact.php",
data: post_data,
success: function(data) {
alert("Thank you for contacting us.");
$('#submit_form_contact').reset();
}
});
e.preventDefault();
}
Also, the submit button is just a button, not a submit input. Is it necessary to preventDefault()? I'm new at this.
jQuery doesn't have a .reset() method.
Do this instead:
$('#submit_form_contact')[0].reset();
This grabs the first DOM element, and invokes the native .reset(). If there's any chance the form won't be found, then test for the element.
var f = $('#submit_form_contact')[0];
if (f)
f.reset();
And of course you don't really need jQuery to get an element by ID, especially if you're not going to use any jQuery methods.
var f = document.getElementbyId('submit_form_contact');
if (f)
f.reset();
Another alternative would be to set the submit button as the context: of the ajax call, then use its form property.
$.ajax({
context: this,
type: "POST",
url: "process-contact.php",
data: post_data,
success: function(data) {
alert("Thank you for contacting us.");
this.form.reset();
}
});
this line can be used too
$("#submit_form_contact").trigger('reset');

Categories