AJAX function putting post in URL, rather than to page - php

I've got a dropdown, which when selected, should then go query the DB and get a report back. When the user selects the option from the dropdown, it should dynamically change the field without reloading the page.
However, it does seem to reload the page, and the $_POST data is inserted and visible in the URL.
Code in my custom page (This is in Wordpress btw, but I don't think it's a Wordpress issue)
<form class="get_monthly_report_form" role="form" action="">
<input type="submit" id="function" name="function" value="Retrieve Whole Report"> {code excised here that fills the dropdown}
</form>
<div id="search_results"></div>
and here's the code from the .js file
//Monthly Reports
<script>
// wrap everything in a closure
(function($){
// get our references
var $form = $('form.get_monthly_report_form'),
$search_field = $('#function'),
$results = $('#search_results');
// AJAX search call
function do_search_reps() {
// grab the query value from the search field
var search_text = $search_field.val();
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get_and_view_report",
search_text: search_text
}).serialize(),
success: function (response){
console.log(response);
$results.html(response);
}
}); }
// on submit, do the search but return false to stop page refresh
$form.submit(function(e) {
e.preventDefault();
do_search_reps();
return false;
});
})(jQuery);
and the code in my project_functions file is
function get_and_view_report()
{ var_dump ($_POST);
// first, get data passed
$data_passed = explode("++",$_POST["monthly_report_ID"]);
$report_key = $data_passed[0];
$report_type = $data_passed[1];
//print_r ($report_key);
//print_r ($report_type);
//get data about the report as a whole.
$sql = "SELECT * FROM reports_list WHERE report_key ='" . $report_key . "'";
$report_data = $wpdb->get_results ($sql);
//if statement to set up which table to query from NEED TO FINISH THIS
if (substr ($report_data[0]->report_key,0,3) == "sdr")
{
$sql = "SELECT * FROM deployment_list_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,3) == "Off")
{
$sql = "SELECT * FROM officer_list_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,4) == "stat")
{
$sql = "SELECT * FROM status_report_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,3) == "wtr")
{
$sql = "SELECT * FROM service_time_wages_lines WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
elseif (substr ($report_data[0]->report_key,0,3) == "flr")
{
$sql = "SELECT * FROM fleet_ships_list_rows WHERE report_key = '" . $report_key . "' ORDER BY line_number ASC";
}
//print_r ($sql);
$reports_in_db = $wpdb->get_results($sql);
if (empty($reports_in_db))
{
echo "No Data Returned. Something's Wrong";
}
else
{
//print_r ($reports_in_db);
//print_r ($report_data);
//Time to start building the file to go out.
//so we're going to build an array of things, bringing together all the things
$total_report = array();
foreach($reports_in_db as $key)
{
$total_report [$key->line_number] = $key;
}
// get subtitles/abstract
$sql = "SELECT line_number, field_text FROM subtitle_abstract_summary WHERE report_key = '" . $report_key . "'";
$abs_sums = $wpdb->get_results ($sql);
//now for a series of conditional things
foreach ($abs_sums as $key)
{
$total_report [$key->line_number] = $key;
}
ksort ($total_report, SORT_NUMERIC); //sorting the lines and subtitles into the correct order.
//Now an if statment- calling the sort functions based on report type- NEEDS TO BE DONE
$arrs_to_be_printed = sort_ship_deployment_data_single_report ($total_report);
//Now Create the File headers
$file_headers = array($report_data[0]->report_title, $report_data[0]->report_date, $report_data[0]->transcription_notes, $report_data[0]->labels_row, $arrs_to_be_printed[0]);
print_report_to_screen ($file_headers, $arrs_to_be_printed[1]);
}
}
add_action('wp_ajax_get_and_view_report', 'get_and_view_report');
add_action('wp_ajax_nopriv_get_and_view_report', 'get_and_view_report');
and when I click submit (and try to use the Ajax call - what happens is that the page reloads (when I don't want it to) and the URL now is something like
"view-monthly-report/?monthly_report_ID=OffRec1514581778%2B%2Bofficer_list&function=Retrieve+Whole+Report"
Which looks to me like the post data is being put into the URL - and when in the function, var_dump, the result is
"array(0) { } No Data Returned. Something's Wrong"
As I do testing- it seems that the action hook isn't working.
I would appreciate any help.

Related

Submit Form PHP amend to JQuery AJAX

I'm looking to convert the below php form submission to a JQuery Ajax submission. I have used Ajax with some simple requests before, but I'm not sure how to submit and return data from MySQL for the below code.
The code below submits the user input entry to a MySql query returning single columns rows. A While loop then looks at these rows and fires another mysql query returning the number of user likes per row.
<?php
if(!empty($_POST['Message']))
{
$userid = session_id();
$searchStr = get_post($con,'Message');
$aKeyword = explode(" ", $searchStr);
$aKeyword = array_filter($aKeyword);
$stmt = $con->prepare(
'SELECT m.ID, m.MessageText
FROM MessageMain m
LEFT OUTER JOIN Likes l on m.ID = l.PostID
WHERE MessageText REGEXP ?
GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc'
);
$regexString = implode('|', $aKeyword);
$stmt->bind_param('s', $regexString);
$stmt->execute();
$result = $stmt->get_result();
$rowcount=mysqli_num_rows($result);
echo "<pre> Returned ". $rowcount . " matches</pre>";
if(mysqli_num_rows($result) > 0) {
$row_count=0;
While($row = $result->fetch_assoc()) {
$postid = $row['ID'];
$row_count++;
// Checking user status
$status_query = $con->prepare("SELECT COUNT(*) AS type FROM likes WHERE userid = ? AND postid = ?");
$status_query->bind_param('ss',$userid,$postid);
$status_query->execute();
$status_result = $status_query->get_result();
$status_row = $status_result->fetch_assoc();
$type = $status_row['type'];
// Count post total likes
$like_query = $con->prepare("SELECT COUNT(*) AS cntLikes FROM likes WHERE postid = ?");
$like_query->bind_param('s',$postid);
$like_query->execute();
$like_result = $like_query->get_result();
$like_row = $like_result->fetch_assoc();
$total_likes = $like_row['cntLikes'];
?>
<div class="post">
<div class="post-text">
<?php
echo nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8") );
?>
</div>
<div class="post-action">
<input type="button" value="Like" id="like_<?php echo htmlentities($postid . "_" . $userid); ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" /> (<span id="likes_<?php echo $postid . "_" . $userid; ?>"><?php echo htmlentities($total_likes); ?></span>)
</div>
</div>
<?php
}
}
}
Easiest would be to rewrite you PHP script to return only the data so you can use this in your JS to build the HTML.
What I would suggest is simply creating a array and adding all your data to this array in you while loop, so for example:
// Add the array declaration somewhere at the beginning of your script ( outside the while loop )
$likesData = array();
Then inside your while loop:
$likesData[] = array(
'ID' => $postid,
'type' => $type,
'totallikes' => $total_likes
);
Then after your while loop:
// Return the array as JSON, die script to ensure no other data gets send after the json response
die( json_encode( $likesData ) );
Then in your JS ( jQuery ) do something like this:
// Do the AJAX request
$.post( "yourscript/url/maybephpfile.php", function( jsonResponse ) {
// Loop over json response
for( var key of Object.keys( jsonResponse ) ) {
$( '.your_existing_element' ).append( `<div class="post"><div class="post-text">${jsonResponse[key].totallikes}</div></div>` );
}
});
Hope this helps you out, if you have any questions let me know.
You need to send from a form in ajax when clicking the button
$.ajax({
method: "POST",
url: "some.php",
data: { message: "message text" }
})
.done(function( msg ) {
// process your data back here
alert( "Data Saved: " + msg );
});
Examples here. https://api.jquery.com/jquery.ajax/
$.post is shortcut of ajax, method post.
I think would be better to split the files and not do everything in one.
form.php -> ajax request -> backend.php -> data retrieved with ajax back to form.php

Passing values from a php page to a modal from other page

I'm trying to edit a post using this snippiet of from my query.php page:
echo '<button type="submit" onclick="openModal(this)" id="btn-edit"
name="edit" value='.$postID.'></button>';
function openModal(id)
{
var editpost = id.value;
$.ajax({
url:"query.php",
method:"POST",
data:{ editpost : editpost },
success:function(data)
{ //
},
error: function () {//
}
});
$('#edit').modal('show');
}
The function to get the data from the post selected is on the same php page. This is the code:
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$_SESSION['editpostdesc'] = $row['PostDesc'];
$_SESSION['editpostfile'] = $row['PostFile'];
$_SESSION['editpostid'] = $row['PostId'];
}
}
}
}
But the modal is on the other page (main page). I want to get the data of the post and display it on the modal, so I tried using $_SESSION. Yes, I got the data and was able to display it on the modal, but the problem is when I try to edit another post, the first value assigned to the session cannot be replaced. Is there is any other way that I can pass the values without using session? I'm really running out of ideas, I'm just starting my first web project.
if you get multiple row means this methods will worked...
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$res[] = array(
'editpostdesc' => $row['PostDesc'],
'editpostfile' => $row['PostFile'],
'editpostid' => $row['PostId']
);
}
}
}
}

autoComplete do not shows all data

I appplied autoComplete function to search box but when i key in some value in the search box, it always gv me the same result.
I realized i did not loop through the database, that's why i keep getting the same result.
I changed my query so that i can get what i want but the result still the same.
here is my ajax for autocomplete, and i'm not sure is it the right way to do it? But the search function is working except it do not display all the data.
function autoComplete(){
$('#keywords').autocomplete({
source: 'autoComplete.php',
minLength : 3,
select: function(event, ui) {
console.log(ui);
$('#chosenEvent').append(ui.item.value + "\n");
}
});
Here is the php code
<?php
// include the file for the database connection
include_once("database_conn_getOffers.php");
function autoC($conn){
$sql = "select eventTitle from te_events_special_offers eventTitle ORDER BY eventTitle";
$rsOffer = mysqli_query($conn, $sql);
//$offer = mysqli_fetch_all($rsOffer, MYSQLI_ASSOC);
$titles = array();
while($title = mysqli_fetch_assoc($rsOffer)){
$titles[] = $title;
}
foreach ($titles as $title)
return json_encode($title);
}
echo autoC($conn)
?>
Here is the link that i refer to click here
Thanks for your help!
So now, i changed the ajax method with the following code and it works but i still have no idea what wrong with my previous ajax code.
I also modified the php code by remove the foreach and added implode method
$.ajax({
method :"get",
url :"autoComplete.php"
})
.done(function(data, status, jqxhr){
var eventList;
console.log(data);
eventList = data.split(',');
$("#keywords").autocomplete({
minLength :2 ,
source : eventList,
select: function(event,ui){
console.log(ui);
}
//end autocompoete
});
});
Please try first to have results to encode, then we'll used them. Run this code along no other one at the same time, and tell us what you get (I assumed that you have columns ID + TITLE, if not, correct the code before using). Also, you original query seems weird -> $sql = "SELECT eventTitle FROM te_events_special_offers eventTitle ORDER BY eventTitle"; /* check bold part of it */
Plus : you should really think about prepared statements and error_reporting
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include"config.inc.php";
$mysqli = mysqli_connect("$host", "$user", "$mdp", "$db");
if (mysqli_connect_errno()) { echo "Error connecting : " . mysqli_connect_error($mysqli); }
$query = " SELECT idTitle, eventTitle FROM te_events_special_offers ORDER BY eventTitle "; /* check names used here and adapt to yours */
$stmt = $mysqli->prepare($query);
$results = $stmt->execute();
$stmt->bind_result($idTitle, $eventTitle);
$stmt->store_result();
if ($stmt->num_rows > 0) {
$events = array();
$event = array();
while($stmt->fetch()){
echo"[ $idTitle -> $eventTitle ]<br />";
$event["id"] = "$idTitle";
$event["title"] = "$eventTitle";
array_push($events, $event);
}
}
else
{ echo"[ no data ]"; }
print_r($events);
echo json_encode($events);
?>

php not clearing table between different queries

I am using jquery to feed variables to a php page.
I want the php to clear a table in the database, load new data based on the variables, query the new data and echo out results.
The problem is, the php doesn't seem to be clearing the table each time I hit the php page. When I feed two sets of variables to the php page, the same results appear for both queries. The results are a combination of what I want. What am I doing wrong, anyone know?
jquery:
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : strYear, race: 'USP', type: strType},
success: function(data) {
var objPrez = jQuery.parseJSON(data);
fillTotal(objPrez, tbl_prezresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
//get gov totals
$.ajax({
url: "php/getTotals.php",
method: "POST",
data: {year : 2010, race: 'GOV', type: strType},
success: function(data) {
var objGov = jQuery.parseJSON(data);
fillTotal(objGov, tbl_govresults);
},
error: function(jxhr, statusText, err) {
console.log(statusText + " " + err);
}
});
getTotals.php:
require_once ('constants_test.php');
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
if( $_POST) {
$type = mysqli_real_escape_string($db, $_POST['type']);
$year = mysqli_real_escape_string($db, $_POST['year']);
$race = mysqli_real_escape_string($db, $_POST['race']);
$db->query("delete from elections_temp");
$data = array();
$q = "INSERT INTO elections_temp (SELECT * FROM elections where electionOffice = '" . $race . "' AND electionYear = '" . $year . "' AND electionType = '" . $type . "')";
$db->query($q);
$q_sums = "select firstName, lastName, party, sum(votes) as totvotes from elections_temp group by lastName order by totvotes desc";
$result = $db->query($q_sums);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//Add this row to the reply
$data[] = $row;
}
echo json_encode($data);
$db->close();
} else {
echo "You shouldn't be here.";
}
What you are doing is the following:
2 ajax calls that call the php script at the same time (probably a delay of a few ms between them).
The server then does what you want it to do, but strange things happen because of your temp table that is created/truncated every request.
What happens is the following:
request1 enters
runs the php code
request2 enters
runs request2 code
request1run locks tem table in database and starts creating it and stuff
request2run wants to create the same temp tabel but can't because request1run is still doing stuff
request1run ends doing his stuff in the db temp table
request2run now does his thing with the temp table, delete all records and add stuff
request1run has to wait before he can select stuff from the temp table because request2run is still doing his business.
request2run finished creating the temp table and request1run can slect his data and return it to the client
request2run select data and returns it to the client
So, because you fire both ajax call at the same timen they end up messing with each other on the server.
Your server is probably not fast enough to handle request1 before request2 kicks in.
I think you do not need the extra table. You can all do it in one sql
$query = 'select firstName, lastName, party, sum(votes) as totvotes from elections
where electionOffice = "' . $race . '" AND electionYear = ' . $year . ' AND electionType = "' . $type . '"
group by lastName, firstName, party order by totvotes desc';
If performance is a problem, add an index to electionOffice, electionYear and electionType (all in one index).

Using jQuery and php to pull data from database

I have a page that is pulling data through jQuery but it is only pulling the return code. Here is my code:
<script type='text/javascript' language='javascript'>
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val()
},
function (response) {
$('#contact').val(response).show();
$('#email').val(response).show();
$('#phone').val(response).show();
})
}
</script>
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . $_POST['id'] . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
if (mysql_num_rows($query) > 0) {
while ($get = mysql_fetch_array($query)) {
$priContact = $get['priContact'];
echo $priContact;
echo $get['priEmail'] . " | " . $get['priPhone'];
}
} else {
echo "No users";
}
So the call is pulling from getCU.php whenever the onchange event handler is called. That is why this is in a function. What I want to do is every time a user chooses something from the option list the text values change according to what was selected. I have the php page pulling from a db and echoing out the code correctly. jQuery id pulling the data from the php page correctly, but I cannot get the code to place the single details in each of the text boxes.
So what I want to happen is this:
A user selects a name from a drop-down box. Then the mysql data attached to that name would be displayed on the page in form text fields.
Let me know if more information or code is needed.
I think you'll be better off structuring your data. My general recommendation is JSON.
// QUICK WARNING: Don't take unparse GET/POST responses.
// This is asking for trouble from SQL injection.
$select = "SELECT priContact, priEmail, priPhone FROM user WHERE id = '" . mysql_escape_string($_POST['id']) . "'";
$query = mysql_query($select) or die ("Could not get info: " . mysql_error());
$retVal = array();
if (mysql_num_rows($query) > 0) {
$retVal['data'] = array();
while ($get = mysql_fetch_array($query))
{
$retVal['data'][] = $get;
}
} else {
$retVal['error'] = 'No users';
}
header('Content-type: application/json');
echo json_encode($retVal);
Javascript:
<script type="text/javascript">
function showCU() {
$.post('getCU.php', {
cuid: $('#cuContact').val(),
dataType:'json'
},
function (response) {
if (response.error) {
//handle error
}
else
{
$('#contact').val(response.data.priContact).show();
$('#email').val(response.data.priEmail).show();
$('#phone').val(response.data.priPhone).show();
}
})
}
</script>

Categories