AJAX Return for non obtrusive page - javascript

I have a form with an id or 'display'. It has one value to send which is a select item that I gave an id of 'services' to.
I want to send the value of 'services' to a function I have created in a seperate php page. The page is called 'functs.php' and the function name is called 'searchResults'.
The 'searchResults' function works, this much I know. It queries a database and outputs 8 seperate php echo statements. I have ran the PHP function and know it works. I know the issues is with my javascript because, well, I am not the greatest at JavaScript and usually shy away from it.
As of right now, the code is not doing anything. My form has its own action to post to a seperate php page.
<form id="display" action="resultPage.php" method="POST">
I am trying to use the javascript/ajax to instantly update the contents of a div BUT if the user has jscript turned off, I want the form to ppost to the alternate page. Here is my jscript.
$(document).ready(function() {
$('#display').submit(function(e) {
var formData = $('#services');
$.ajax({
type: "POST",
url: functs.php,
data: '$formData',
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
e.preventDefault();
return false;
});
});
PHP CODE:
<?php
function searchResults()
{
require 'db_config.php';
$sql= "SQL CODE HERE"
$theStyle = <<<HERE
"height:100%;
width:70%;
margin:4% AUTO 0;
padding:1.75em;
font-size:1.25em;
border-radius:5em;
color:white;
background-color:#b72027;
;"
HERE;
while ($row = mysql_fetch_array($result))
{
echo ("<div style = $theStyle>");
echo ("<table>");
echo ("<tr><td>" . $row["0"] . "</td></tr>");
echo ("<tr><td>" . $row["1"] . "</td>");
echo ("<tr><td>" . $row["2"] . ", " . $row["3"] . " " . $row["4"] . "</td></tr>");
echo ("<tr><td>Phone: " . $row["5"] . "</td></tr>");
echo ("<tr><td>" . "" . $row["6"] . "" . "</td></tr>");
echo ("<tr><td>" . $row["8"] . " " . $row["9"] . ", " . $row["10"] . "</td></tr>");
echo ("<tr><td>" . $row["11"] . "</td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td></td></tr>");
echo ("<tr><td>" . $row["7"] . "</td></tr>");
echo ("</table>");
echo ("</div>");
echo ("<br />");
}
}
?>

Your JS code has a couple of issues. The PHP script name needs to be a string inside of quotation marks, and the formData variable has an unnecessary "$." Try this:
$(document).ready(function() {
$('#display').submit(function(e) {
e.preventDefault();
var formData = $('#display').serialize();
$.ajax({
type: "POST",
url: 'functs.php',
data: formData,
datatype: 'json',
success: function(data) {
if (!data.success)
{
$.amwnd({
title: 'Error!',
content: data.message,
buttons: ['ok'],
closer: 'ok'
});
}
}
});
});
});

Related

How to use WP Admin Ajax in the front of Wordpress site to fetch date from a json every 15 seconds

I'm new using ajax+js and I have a php code to display from a json url some information to my wordpress site front end.
The code is fetching the data from the json url:
$widget_width = 70;
$text_color = #000000;
$json = file_get_contents('https://example.com/api/nowplaying');
$obj = json_decode($json, true);
echo "<img src=\"" . $obj["now_playing"]["song"]["art"] . "\" style=\"width:" . $widget_width . "px;\"><br /><div style=\"color:" . $text_color . ";font-family:Comfortaa;font-size:13px;width:" . $widget_width . "px;text-align:center;\">";
$nowplaying = $obj["now_playing"]["song"]["title"] . "<br />" . $obj["now_playing"]["song"]["artist"];
echo $nowplaying;
Unfortunately the data change every 15 seconds, so i would like to make use of WP Admin Ajax to refresh the data every 15 seconds.
From searching what i understood until now is that i should do this in my functions.php :
function eno_get_my_data() {
$widget_width = 70;
$text_color = #000000;
$json = file_get_contents('https://example.com/api/nowplaying');
$obj = json_decode($json, true);
echo "<img src=\"" . $obj["now_playing"]["song"]["art"] . "\" style=\"width:" . $widget_width . "px;\"><br /><div style=\"color:" . $text_color . ";font-family:Comfortaa;font-size:13px;width:" . $widget_width . "px;text-align:center;\">";
$nowplaying = $obj["now_playing"]["song"]["title"] . "<br />" . $obj["now_playing"]["song"]["artist"];
echo $nowplaying;
wp_die();
}
add_action('wp_ajax_eno_get_my_data', 'eno_get_my_data');
add_action('wp_ajax_nopriv_eno_get_my_data', 'eno_get_my_data');
What would be the created jQuery ajax javascript that needs to work with this so that it can refresh the json data every 15 seconds?
I made something like this:
<script type="text/javascript">
function(){
var data = setInterval( function() {
{action: 'eno_get_my_data'}
}, 15000);
jQuery.ajax({
type: "GET",
url: '/wp-admin/admin-ajax.php',
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
But it is wrong for sure. I am totally newbie in js.
Could someone help please?

How to insert PHP row record into AJAX url

I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});

Unable to update div text from ajax response sent via php

Apologies for this question if something out there covers this. I searched and found many relevant posts which has allowed me to get to this point.
I have a form snippet with 1 input box and a button and a div for a status message:
<div>
<div>
<div>
<input id="discount_code"name="discount_code" placeholder=" Enter discount code."></input>
</div>
<div>
<a class="btn btn-xs btn-primary" id="btn-validate">Validate</a>
</div>
</div>
<div id="status_msg" style="border: 1px solid black"></div>
</div>
Then I have the following bits of javascript:
The bit that triggers based on the click:
$('#btn-validate').on('click', function(e) {
e.preventDefault();
validateCode(11); // "11" is a php-provided ID variable
});
The javscript with the ajax call:
function validateCode(eventID) {
var codeValue = $("#discount_code").val();
if (FieldIsEmpty(codeValue)) { // outside function that exists/works fine
$('#status_msg').html('Enter a discount code.').fadeIn(500);
$('#status_msg').fadeOut(2500);
//bootbox.alert("Please enter discount code to validate.");
} else {
$.ajax({
type: 'POST',
cache: false,
async: true,
url: '/include/discount_validation.php',
dataType: 'json',
data: {
event_id: eventID,
discount_code: codeValue
},
beforeSend: function() {
$('#status_msg').html('');
$('#status_msg').fadeIn(0);
},
success: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
$('#status_msg').html(data);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
});
}};
And I have a PHP file that, suffice it to say, is working and producing the following json outputs based on the input:
// do php database things...
header('Content-Type: application/json');
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => "$message"));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => "$message"));
}
In the above, I have bootbox.alert lines commented out but when they are active, the box appears and the message is as I would expect it to be.
And lastly, the first condition that triggers if the input box is empty, both fires the alert (when not commented) AND changes the text of #status_msg.
I put the border in to verify visibility and #status_msg is visible but just is not set when either success or error fires.
First check if you getting an object in the response
in the success add
alert(JSON.stringify(data));
If it shows the object then you are good to go else check the php file where you creating the object.
If object is recieved in the success of ajax then you need to parse the json object using jQuery.parseJSON
For Eg:
response = jQuery.parseJSON(data);
Now you have a javascript object with name response.
Now use it
response['status'] or response['message'] in the success of the ajax.
check the code
first discard : " from php code $message variable
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}
then use the response on font end success function :
success: function(data) {
$('#status_msg').html(data.message);
$('#status_msg').fadeIn(0);
},
Set your data like this inside ajax().
success: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert(data);
},
error: function(data) {
var result = eval(data);
$('#status_msg').html(result.message);
$('#status_msg').fadeIn(0);
//bootbox.alert("Error validating discount code: " + JSON.stringify(discount_code));
}
AND
if(!isset($percent)) {
//echo("Invalid code: '" . $dCode ."'");
$message = "Invalid code: '" . $dCode ."'";
echo json_encode(array('status' => 'error','message' => $message));
} else {
$message = "Code: '" . $dCode . "'" . " provides a " . $percent . "% discount.";
echo json_encode(array('status' => 'success', 'message' => $message));
}

Trouble w/ Form Processing using jQuery + PHP

I'm having the hardest time getting a simple form to process using jQuery and PHP. I've tried getting the data via $_POST, $_GET, and $_REQUEST but I guess I'm missing a simple line of code or a complete process altogether.
app.js
$(document).ready(function() {
$('#sucMsg').hide();
$('#errMsg').hide();
$('form').on('submit', function(event) {
event.preventDefault();
var form = $(this);
alert(form.serialize());
$.ajax(form.attr('action'), {
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: form.serialize(),
success: function(result) {
form.remove();
$('#sucMsg').append(result);
$('#sucMsg').fadeIn();
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
$('#errMsg').append(thrownError);
$('#errMsg').fadeIn();
}
});
});
});
formProcess.php
<?php
if ($_POST) {
echo "Posted something.";
} elseif ($_GET) {
echo "Getted something.";
} else {
echo "Nothing is working...";
}
$tagNumberPost = $_POST['inputTagNumber'];
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
$tagNumberRequest = $_REQUEST['inputTagNumber'];
$priceRequest = $_REQUEST['inputPrice'];
$makeRequest = $_REQUEST['inputMake'];
if (isset($_REQUEST['inputTagNumber'])) {
echo '$_REQUEST works...\n';
} elseif (isset($_POST['inputTagNumber'])) {
echo '$_POST works...\n';
} elseif (isset($_GET['inputTagNumber'])) {
echo '$_GET works...\n';
} else {
echo "Nothing is working...";
}
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
?>
What I'm expecting to get back is the all the echo's in my formProcess.php to print out in my #sucMsg div.
Why are you setting your contentType: as application/json? You do not need that. Remove it.
contentType: 'application/json', // remove this line
Just leave it to its default as application/x-www-form-urlencoded if your request is POST.
And in your PHP, $tagNumber is undefined.
if (isset(
$_POST['inputTagNumber'],
$_POST['inputTagNumber'],
$_POST['inputMake'],
)) {
$tagNumber = $_POST['inputTagNumber']; // define tagNumber
$pricePost = $_POST['inputPrice'];
$makePost = $_POST['inputMake'];
echo "<br/>";
echo "Tag number: " . $tagNumber . "<br/>\n";
echo "Make: ".$makePost . "<br/>\n";
echo "Price: " . $pricePost . "<br/>\n";
}

PHP and AJAX: How can I display json_encode data in PHP while loop?

I am very new to using AJAX and passing data with json_encode. I have this "aht" button when clicked it will send an AJAX request to my show_aht.php script, which will run a query. I want to save the results and display it to my map.php.
Problem:
In my map.php I have a while loop that outputs square(desk) DIVs with another DIV(station) when clicked that displays content inside of it. Here is the fiddle so you may understand. I want the results of show_aht.php "TIME" to be displayed in the DIVs being produced by my WHILE LOOP in map.php.
How is it possible to do this? I know that AJAX and PHP cannot interact with eachother and thats why I need help. If this can't be done, how else can I display the TIME from show_aht.php to their corresponding usernames on each DIV being output? I have around 200 of them being displayed.
Thanks in advance.
map.php (only showing the last line of the while loop, outputs all DIVs)
//desk DIV
while(somequery){
....
echo '<div class="' . $class . '" data-rel="' . $id . '" style="left:' . $x_pos . 'px;top:' . $y_pos.'px;">' . $sta_num . '</div>' . "\n";
}//end while
//station DIV
while(some query){
.....
echo '<div class="station_info_" id="station_info_' . $id . '" style="left:' . $x_pos . 'px;top:' .$y_pos . 'px;"><p class="numb">User:' . $user .'<br>Station:' . $hostname . '<br>Pod:' . $sta_num . '<br>Section:' . $sec_name . '<br>State:' . $state .'<br></p></div>' . "\n";
}//end while
map.php (AJAX part)
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht.php (showing the loop and part I where I want the data to be returned)
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo "User: " . $m . " Time: N/A <br>";
}
}
}
Don't output anything except one valid json string. In your case you do that by replacing the echo's with building an array (or object...) and output that at the very end:
For example:
$data = array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$data[] = " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
$data[] = "User: " . $m . " Time: N/A <br>";
}
}
}
// Output your json string
echo json_encode($data);
Note that I have simply replaced your echos with an assignment but you could also add arrays in your array to return just the data parts and process that afterwards in javascript.
For example (this would depend a bit on your exact data structure...):
...
$data[] = array($m, $v['avg_handle_time']);
...
change show_aht.php to
$res=array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$res[]= " User: " .$m. " Time: " . $v['avg_handle_time'];
}
elseif( $v['memo_code'] != $m){
$res[]= "User: " . $m . " Time: N/A <br>";
}
}
}
echo json_encode($res);
and map.php ajax to
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
for(i=0;i<data.length;i++){
//append data[i] to div
}
}//end success
});//end ajax
});//end click
});//end rdy

Categories