$.get in jquery not executing while on html page through javascript - php

I've been trying to create a simple download counter for my site, in the following way: To use jquery to retrieve the value of a txt which indicates download times, then to use jquery to call ajax to execute a PHP file, which would in turn overwrite such txt file (incrementing it on the php file) then store it, then reading back the value with jquery. Before I forget, and to avoid any misinformation, here is the whole HTML code for the page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>GreenDream: SMS Sender</title>
<link rel=StyleSheet type="text/css" href="http://www.gfcf14greendream.com/CSS/greendream.css" />
<link rel="SHORTCUT ICON" href="http://www.gfcf14greendream.com/images/dreamicon.ico">
<script type="text/javascript" src="http://www.gfcf14greendream.com/JS/greendream.js"></script>
</head>
<body onload="startTime(); handleTextFile()">
<div id="background">
<img src="http://www.gfcf14greendream.com/images/greentwi.png" class="stretch" alt="" />
</div>
<br />
<table align="center">
<tr>
<td>
<img src="http://www.gfcf14greendream.com/images/dream.png" align="middle">
</td>
<td>
<div id='pbutton' style="width:113px; height:41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/programs.html">Programs</a></div>
</td>
<td>
<div id='gbutton' style="width:93px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/games.html">Games</a></div>
</td>
<td>
<div id='tbutton' style="width:108px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/tutorials.html">Tutorials</a></div>
</td>
<td>
<div id='bbutton' style="width:74px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://blog.gfcf14greendream.com/">Blog</a></div>
</td>
<td>
<div id='mbutton' style="width:114px; height: 41px; margin:0px;white-space:nowrap; word-spacing:0;"><a class="button" href="http://www.gfcf14greendream.com/aboutme.html">About Me</a></div>
</td>
<td style="padding-left:50px">
<div id='daytitle'></div>
<div id='clock'></div>
</td>
</tr>
</table>
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px">The following is a Visual C++ program that was designed specifically to send text messages to a phone... Free of charge!!</div>
<br />
<div style="text-align: center; color:#FFFF00; font-size: 20px">THE GOOD: If you have a prepaid phone, then you can send text messages to a phone without wasting your minutes...</div>
<br />
<div style="text-align: center; color:#FF8000; font-size: 20px">THE BAD : Since I haven't been able to put a Skype or Google Voice library for use with C++, this application depends on using what's known as an SMS gateway, different for every phone carrier... meaning you must know your recipient's carrier to be able to send a message!</div>
<br />
<div style="text-align: center; color:#FF0000; font-size: 20px">THE UGLY: This program doesn't work on computers connected to safe networks (such as college/university networks) ... at least not yet!</div>
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px">You will probably need the Visual C++ Redistributable Package (or the .NET framework or both, but most likely just the package) to run this program, if you don't have it installed on your pc yet</div>
<br />
<br />
<div style="text-align: center; color:#0000C8; font-size: 20px">Click here to download the Visual C++ Redistributable Package</div>
<div style="text-align: center; color:#0000C8; font-size: 20px">Click here to download the .NET Framework 4</div>
<br />
<br />
<div style="text-align: center; color:#00FF00; font-size: 20px"><a class="button" id="downbutton" style="width:115px;margin:0px;white-space:nowrap; word-spacing:0;" href="http://www.gfcf14greendream.com/Programs/SMSSender/SMS Sender.exe">Click here to download SMS Sender</a></div>
<br />
<div id='counter' style="text-align: center;"></div>
<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function handleTextFile()
{
document.getElementById('counter').style.color = "rgb(0, 255, 0)";
document.getElementById('counter').style.fontWeight = 'bold';
var downcounter = 0;
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
$("#downbutton").click( function(){
$.get("http://www.gfcf14greendream.com/PHP/smssender.php", function(data){
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
});
});
}
</script>
</body>
</html>
Upon running the page, I use this code (a piece from above) to read a txt file and get download count (this works):
var downcounter = 0;
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
Then when the downbutton variable is clicked, this code should execute:
$("#downbutton").click( function(){
$.get("http://www.gfcf14greendream.com/PHP/smssender.php", function(data){
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
downcounter = data;
if (downcounter == 1) $("#counter").text("SMS Sender has been downloaded " + downcounter + " time...");
else $("#counter").text("SMS Sender has been downloaded " + downcounter + " times...");
});
});
});
, which should read a php file, whose code is:
<?php
$counter = intval(file_get_contents('/homepages/37/d434704165/htdocs/counters/smssender.txt'));
$counter++;
file_put_contents('/homepages/37/d434704165/htdocs/counters/smssender.txt', $counter);
?>
And running the php would overwrite the txt file "smssender" and thus increase the number of downloads. I noticed that manually entering the address of the php file on my site actually works, and the download increment takes place. Yet when JQuery executes the code, no increment takes place. I'm guessing it's on this line, but what would be the error here? :
$.get("http://www.gfcf14greendream.com/counters/smssender.txt", function(data){
Thank you very much for any help or suggestion!!

I think it would be a lot simpler to just use the PHP page by itself. You can use GET variables to determine whether you need to increment the download counter. For instance, do something like this in your PHP file:
<?php
$total = (int)file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt');
if (isset($_GET['i'])) {
$total++;
// now update the file for future use
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt', $total);
}
echo $total;
?>
Then you can call the PHP page by itself in the ajax so that you don't have to worry about both calls being executed simultaneously and causing errors. You could now just make a call to "smssender.php" when you want to retrieve the current number of downloads. In addition, you could call "smssender.php?i" when you want to retrieve the current number of downloads and increment the file contents.
If you wanted to only increment the file's contents and not echo the output, you could add another if statement, but I don't know if that's what you're trying to do. If so, please let me know and I can show you code for that as well. I hope that helps, if not, just let me know.
UPDATE: Just change your code to this:
Javascript File:
$.get("/PHP/smssender.php", function(data) {
$("#counter").text(data);
});
$("#downbutton").click( function() {
$.get("/PHP/smssender.php?i", function(data) {
$("#counter").text(data);
});
});
PHP File:
<?php
$total = (int)file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt');
if (isset($_GET['i'])) {
$total++;
// now update the file for future use
file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/counters/smssender.txt', $total);
}
$suffix = ($total == 1) ? 'time' : 'times';
echo 'SMS Sender has been downloaded ' . $total . ' ' . $suffix . '...';
?>
Now, you can simplify your Javascript/jQuery by A LOT. This code will have the exact same behavior as the code you had, without any errors. Now, I will explain the changes I have made. First, you only have to call a single PHP file with the $.get() method, regardless if you are just retrieving the current number of downloads or whether you are incrementing the total.
Secondly, the text handling is done in the PHP file. You no longer determine if it has been downloaded 1 or more times in Javascript, instead the PHP file handles this because it's a lot faster than retrieving the data and making a calculation afterwards.
Lastly, I made the download button only call $.get() once so that you don't have to worry about errors resulting from an attempt to retrieve two different pages simultaneously. Try replacing your code with the new code I posted above and let me know how it works out for you.

Related

AJAX Respond Not Catched by PHP file

We are on progress creating web page for live search and update file in bulk using JQUERY AJAX method. The files consist of index.php (for display to user and Javascript), and multiple_update.php (for fetch and update file in bulk). Initial reference we got is from here from webslesson website, but it does not have any reference for searching the record, hence we search for help for our journey.
Below is our index.php file
<div class="content-wrapper">
<div class="content-heading">
<div>STO Monitoring<small>Tables, one step forward.</small></div>
<div class="ml-auto"><input type="text" id="search" placeholder="Search" /></div>
<div id="display"></div>
<div class="ml-auto">
<button class="btn btn-primary btn-lg" type="button" data-toggle="modal" data-target="#myModalSmall"><i class="fas fa-plus-square"></i> Add Record</button>
</div>
</div>
<form method="post" id="update_form">
<div class="card">
<div class="card-body">
<table class="display" id="example" style="width:100%">
<thead>
<tr>
<th width="3%"></th>
<th width="5%">No</th>
<th width="15%">STO</th>
<th width="20%">PN</th>
<th width="8%">Qty</th>
<th width="10%">From</th>
<th width="10%">Dest</th>
<th width="15%">Status</th>
<th width="14%">Remark</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div align="left">
<input type="submit" name="multiple_update" id="multiple_update" class="btn btn-info" value="Multiple Update" />
</div>
</div>
</div>
</form>
</div>
.....
Below is script inside our index.php, the one we suspect need troubleshoot at the moment.
<script>
function fill(Value) {
$('#search').val(Value);
if (name == "") {
$("#display").html("");
}
}
$(document).ready(function(){
function fetch_data()
{
$("#search").keyup(function() {
var name = $('#search').val();
if (name == "") {
//Assigning empty value to "display" div in "search.php" file.
$("#display").html("empty");
} else {
$.ajax({
url:"multiple_select.php",
method:"POST",
dataType:"json",
data: {
//Assigning value of "name" into "search" variable.
search: name
},
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++) {
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].num+'" data-num="'+data[count].num+'" data-sto="'+data[count].sto+'" data-pn="'+data[count].pn+'" data-qty="'+data[count].qty+'" data-supplant="'+data[count].supplant+'" data-dest="'+data[count].dest+'" data-stat="'+data[count].stat+'" data-remark="'+data[count].remark+'" class="check_box" /></td>';
html += '<td>'+(count+1)+'</td>';
html += '<td>'+data[count].sto+'</td>';
html += '<td>'+data[count].pn+'</td>';
html += '<td>'+data[count].qty+'</td>';
html += '<td><span class="btn btn-oval btn-primary">'+data[count].supplant+'</span></td>';
html += '<td><span class="btn btn-oval btn-warning">'+data[count].dest+'</span></td>';
html += '<td>'+data[count].stat+'</td>';
html += '<td>'+data[count].remark+'</td></tr>';
}
$('tbody').html(html);
}
});
}
});
}
fetch_data();
$(document).on('click', '.check_box', function(){
.....
</script>
We modify the AJAX to see if the input can be catched by the network, below is code for multiple_update.php
<?php
include('multiple_connection.php');
$name = $_POST['search'];
echo $name;
$query = "SELECT * FROM matreq_list, sto_list WHERE matreq_list.sto = sto_list.sto AND sto_list.sto LIKE '%$name%' LIMIT 5;
$statement = $connect->prepare($query);
if($statement->execute()) {
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
}
?>
We want to make every search is captured via AJAX, and respond from network will be live-reflected in our index file. Below is our expected final result (this result is without "LIKE" in mysql statement to show the result only) :
And we confirm AJAX can handle our input, below is the image :
--UPDATE-- Below is error messages :
Error messages
However, after we fired the input, nothing cames up in our index.php file. Network shows good respond, but the HTML is not responding the way we expected it to do. Please kindly advise us sir, what is wrong with our method and what should we fix?
Thank you and appreciate your kind help in our case
=====UPDATE=====
2020-07-02 : As mentioned by mr Nadir Baoun, tried to change the order of jquery.js and put it above the bootstrap.js, and somehow my table now able to search some part or whole part of the data.
Before :
.....
<script src="vendor/datatables.net/js/jquery.dataTables.js"></script>
<script src="vendor/datatables.net-bs4/js/dataTables.bootstrap4.js"></script>
<script src="vendor/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
<script src="vendor/jquery/dist/jquery3.5.1.js"></script>
<script src="vendor/datatables.net/dist/js/jquery.dataTables.min.js"></script>
After ordered : I move the jquery to the top of all codes.
and below is network screenshot :
After change order of javascript
Surprisingly, this work well :D
The HTML isnt responding the way you want is because you have JavaScript errors thus your response code wont function accordingly.
First thing include your jquery file before bootstrap.
This should solve the " cannot read property fn of undefined " error.
Please update your post with debug messages in the success param of your ajax request after doing what i have mentionned above
After thoroughly reading on various articles with a guide from Mr Nadir Baoun, my problem is now fixed by changing the order of the script, putting the jquery script before the bootstrap script.
Similar answers also posted in stackoverflow website :
script order for jquery with bootstrap
Thank you :)

Include whole page in variable (PHP)

I'm trying to create a page where I can force updates to the client without a page refresh. So I Googled and Googled and Googled and ended up here: http://www.developerdrive.com/2012/03/pushing-updates-to-the-web-page-with-html5-server-sent-events/ - it was almost a success!
I managed to adapt the code enough so that I can include a page instead of using the example rand() and thus, whenever I modify that page and upload it to my FTP, the page updates. However, I cannot figure out how to output a whole file - only the first line of that file (maindiv.php). I've come to understand that it has to do with using "file_get_contents". How can I achieve a full output of "maindiv.php" here?
My pages codes are:
index.php:
<html>
<head>
<style type="text/css">
#serverData
{
position:fixed;
padding:0;
margin:0;
top:0;
left:0;
width: 100%;
height: 100%;
background:green;
}
</style>
</head>
<body>
<div id="serverData">Here is where the server sent data will appear
</body>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</html>
send_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$maindiv = file_get_contents("maindiv.php"); //this does not read more than one line
echo "data: $maindiv\n\n";
ob_flush();
?>
maindiv.php:
<div style="background:blue; display:inline-block; width:300px; height:500px;color:white;">Line 1<br>
Line 2<br>
Line 3<br>
Line 4<br>
Line 5<br>
Line 6<br>
Line 7<br>
</div>

how to integrate asp.net mvc page containing signalR with other platforms

The question is not a duplicate of this, although the mentioned question has some very interesting answers and helped me to understand my problem better but it doesn't fulfill my need. Let me explain my scenario.
I have an asp.net mvc website, having notification functionality and real time data updates by signalR & SQL dependency. User authentication is being done by using Identity 2.0.
Only authorized users are allowed to see the updated data/notifications. Furthermore the notification/updates vary user to user. I've achieved this by implementing custom UserId provider and using Identity's UserId.
Now I want to achieve following goals.
Easy part: Display the content of the page (dashboard) in other websites regardless of their development language. It can be injected inside existing page or wherever they (other websites) want.
Hard part: Show the real time notifications & updates on the integrated portion based on logged in user.
What would be the best course of actions to perform in this scenario?
Update
Since the original question was put on hold due to not specifying the details, so here are the details on which I would like to get suggestions.
I've a asp.net mvc website running at localhost:54603, Following is the action of the home controller
public ActionResult Index()
{
HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
return View();
}
Index view has some signalR functionality on it. Below is the startup configuration of signalR to allow CORS since I my goal is to expose the index page and its whole functionality to clients (running php etc)
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
I've created notifcationHub and following is my code at front end (using proxy).
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
$.connection.notificationHub.url = 'http://localhost:54603/signalr';
var notification = $.connection.notificationHub;
// Client side method for receiving the list of notifications on the connected event from the server
notification.client.refreshNotification = function (data) {
$("#notificationTab").empty();
$("#cntNotifications").text(data.length);
for (var i = 0; i < data.length; i++) {
$("#notificationTab").append("<tr> <td> " + data[i].Id + "</td> <td>" + data[i].Text + "</td> <td>" + data[i].CreatedDate + "</td></tr>");
}
}
//Client side method which will be invoked from the Global.asax.cs file.
notification.client.addLatestNotification = function (data) {
$("#cntNotifications").text($("#cntNotifications").text() + 1);
$("#notificationTab").append("<tr> <td> " + data.Id + "</td> <td>" + data.Text + "</td> <td>" + data.CreatedDate + "</td></tr>");
}
// Start the connection.
$.connection.hub.start().done(function () {
//When the send button is clicked get the text and user name and send it to server.
$("#btnSend").click(function () {
notification.server.sendNotification($("#text").val(), $("#userName").val());
});
console.log($.connection.hub.id);
}).fail(function (data) { console.log('Could not connect' + data); });
});
</script>
and Html is following
#{
ViewBag.Title = "Home Page";
Layout = null;
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.0.min.js"></script>
<script src="#Url.Content("~/signalr/hubs")"></script>
#*<script src="~/signalr/hubs"></script>*#
<div style="width: 70%; padding: 20px">
<div class="panel panel-primary">
<div class="panel-heading">
<! – To show notification count-->
<div style="float: left" class="panel-title">Notifications</div>
<div style="float: right" class="badge" id="cntNotifications"></div>
<div style="clear: both"></div>
</div>
<div class="panel-body">
<! – To show All the notifications-->
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Text</th>
<th>Created Date</th>
</tr>
</thead>
<tbody id="notificationTab"></tbody>
</table>
</div>
</div>
<! – Add panel notification to send notification, Make sure that user enters the user id of the domain they are logged into -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Create Notifications</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label class="control-label" for="focusedInput">Notification Text</label>
<input class="form-control" id="text" type="text" value="">
</div>
<div class="form-group">
<label class="control-label" for="focusedInput">Send To</label>
<input class="form-control" id="userName" type="text" value="">
</div>
<a id="btnSend" style="cursor: pointer" class="btn btn-primary">Send Notification</a>
</div>
</div>
</div>
The page runs fine as expected and connection id is being logged in console.
Now I've created another html page and following is its code
<html>
<head>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.0.min.js"></script>
</head>
<body>
<aside>
<div class="col-lg-2">
<ul>
<li>this</li>
<li>is</li>
<li>aside</li>
</ul>
</div>
</aside>
<article>
<div class="col-lg-10">
<div id="something">
</div>
</div>
</article>
<script src="http://localhost:54603/signalr/hubs"></script>
<script>
$(document).ready(function () {
$.ajax({
url: "http://localhost:54603/Home/Index",
dataType: 'html',
crossDomain: true,
cache:true
}).done(function (data) {
$('#something').html(data);
});
});
</script>
</body>
</html>
Ajax request is returning the html but the signalR throws error. following are the console messages.
GET http://localhost:54603/Home/Index 200 OK 1.18s
Could not connect Error: Error during negotiation request.
What am I doing wrong which is causing this error?
It's difficult to pin down exactly what you need to do, cause the question is rather broad, but I hope that these points help(ed) somewhat:
SignalR cross-domain uses JavaScript on the client side and CORS on the server side, so you're covered on that front. You could easily create a JavaScript file that can connect into the SignalR channel without any changes to PHP code other than to include the JavaScript in the client's page.
You could quite easily create a single script on your server that the client can reference on their page that pulls everything required on to the client's page. Because the script executes from your own server I don't think you'll need to worry about CORS cause it's not truly 'cross site scripting', because the code executing the requests will be 'owned' by your server/domain.
As for authentication, if it's only your script that needs access to the authentication, I think that means that you can make use of your domain's authentication too (cookies etc.) I'd have to check up on that one though. Ultimately you'd authenticate them using a HTTPs request to your domain from the included script?
Here are some useful threads that might help with that one:
Cross-Domain Cookies
Creating a javascript cookie on a domain and reading it across sub domains

Showing PHP database content within a div

I'm setting up a website containing a page that will contain many buttons. I want to be able to click on the button to populate a div with information from a database.
I've adapted some code that I previously had, but it isn't working.
The source javascript and HTML are shown here:
<script>
function showBiog(key) {
//alert(key);
// Get the search value
var search_value = key
// This time we're going to grab data from a file to display
var filename = "functions/biography.php";
// Send these values
var posting = $.post(filename, { search_term: search_value });
// Display this value in our results container
posting.done(function (data) {
$("#test_results").empty().append(data);
});
}
</script>
<style type="text/css">
.test {
background-color: #B32D2F;
border: thin solid #DBB2B3;
height: 50px;
width: 250px;
}
.testresults {
background-color: #88B32D;
border: thin solid #DBB2B3;
height: 50px;
width: 250px;
}
</style>
</head>
<body>
<div class="test" onClick="showBiog(1)"><p>1</p></div>
<div class="test" onClick="showBiog(2)"><p>2</p></div>
<div class="test" onClick="showBiog(3)"><p>3</p></div>
<div class="test" onClick="showBiog(4)"><p>4</p></div>
Results
<div class="testresults" id="test_results"></div>
The HTML of biography.php is
<body>
<?php if (! $_POST["search_term"]) { ?>
<div class="err">
<?php echo $row_Recordset1['firstname']; ?>
</div>
<?php } else { ?>
<?php echo $row_results['firstname']; }?>
</body>
The SQL for results in Dreamweaver is
SELECT *
FROM pilots
WHERE key LIKE colname
with colname $_POST['search_term']
Few things...
You may not need "var search_value = key" if you are not making any change or addition to it. Simply use "key" in the $.post (keep code simple).
What is expected to be in "key"? Depending on what you are sending, the statement var posting = $.post(filename, { search_term: search_value }); may break due to JSON structure requirements.
To assure you are sending out the right information to the PHP, you should try something like $.post(filename, JSON.stringify({ 'search_term': key }) );
On the PHP side, you can use unserialize() to decode JSON data, then process your query.
Just a small personal note and advice: If JSON is not well formed on the POST side, PHP will get nothing, thus it will return nothing. You should always try to log or display the data received by PHP when writing AJAX calls to assure it was correctly received. Otherwise you may be chasing a bug in the wrong spot. ;)

jQuery to run after PHP load

I'm working on a site using the Big Commerce platform. The cart page is built in snippets called by PHP. I don't have access to the PHP files. What I need to do is get the value of a span tag(at a given index) and retrieve the value, I use this value to determine what my minQTY text field should be. I want my code to run after the page has been loaded. However my script isn't working on the page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).load(function(){
$("a.CustomizeItemLink");
$changeIndex = $("a.CustomizeItemLink").index('a.CustomizeItemLink');
$change = $("a.CustomizeItemLink").length;
$productTestArray = ['/american-boxwood-buxus/', '/lavander-crape-myrtle-lagerstroemia-fs/']
$productLength = $productTestArray.length;
for(i=0, j=0; i<=$change, j<=$productLength; i++, j++){
$productTest = "http://www.tnnursery.net";
$productTestValue = $("td.blah a").get(i);
$productTest = "http://www.blah.net" + $productTestArray[j];
$MD = $productTestValue;
$MS = $productTest;
$minQTYArray = ['100','100','75','50','25','20','15'];
$cartSpanValue = $(".productAttributes td span:eq("+i+")").text();
$rdTestArray2 = ['6-12','12-18',"1-2'","2-3'","3-4'","4-5'","5-6'"];
$arr2Test = jQuery.inArray($cartSpanValue, $rdTestArray2);
$minQTYValue = $minQTYArray[$arr2Test];
$cartQtyValue = $(".qtyInput:eq("+i+")").val();
if($MD != $MS){
}
else{
if($cartQtyValue >= $minQTYValue){
}
else{
if ($arr2Test == -1){
$cartQtyValue = $(".qtyInput:eq(" + i + ")").val('100');
}
else{
$cartQtyValue = $(".qtyInput:eq(" + i + ")").val($minQTYValue);
alert($cartQtyValue);
}
}
}
}
});
});
});
</script>
</td>
<td class="ProductName" colspan="1">
Item Name1<table class="productAttributes" cellpadding="0" cellspacing="2">
<tr>
<td>
<label>Plant​ Size​s:</label>
</td>
<td>
<span>12-18​"</span>
</td>
Change
28500
()
<div style="display: none" class="WrappingOptions">
Gift Wrapping:
Add
<span style="display: none">
(Change or Remove)
</span>
<br />
<span style="display: none">
Gift Message:
</span>
</div>
</td>
<td align="center" class="CartItemQuantity">
<span style="padding: 0; margin: 0;"><input type="text" size="2" name="qty[4eea86d587825]" id="text_qty_4eea86d587825" class="qtyInput quantityInput" value="50"/></span>
<div style="">
Remove
</div>
</td>
My question is how do I set my jQuery to run after the PHP has been loaded into the page?
First, you should restore the $(document).ready(function(){});
Second, the php runs on the server side, and thus before the page itself is loaded. You shouldn't have any worry that your javascript will run before the PHP.
Lastly, I think the reason your code isn't running may be due to syntax errors. If you've copied your code in directly then you have multiple endings to your opening function. I'm not sure if this was intentional or not but you have three sets of closing for the load function when its unnecessary.
Also, this line :
$productTestArray = ['/american-boxwood-buxus/', '/lavander-crape-myrtle-lagerstroemia-fs/']
Does not have a semi-colon ending the statement. Make these changes and see if your code begins to function properly.
EDIT: Also, in your For loop you define i and j. Why is that? I believe they will always be the same number the way you have it setup. Am I missing something?
Try replacing $(document).load with $(window).load.
$(document).ready(function(){
//your code here
});

Categories