I have tried searching through SO for an answer to my issue, but all the posts I find still aren't helping me resolve my issue. I don't know if I am overlooking something or if it's just my lack of knowledge that is preventing my code from working.
I have two JS prompts that ask for an ID and then an amount to adjust my stock level. I want it to pass that along to my php file to run a mysql update query.
My script:
<script type="text/javascript">
function sendArray()
{
var ourObj = {};
ourObj.itemId = prompt("Scan ID:");
ourObj.adjAmt = prompt("Enter amount:");
alert(ourObj.itemId);
alert(ourObj.adjAmt);
$.ajax({
url: "save.php",
type: "POST",
data: { invAdj : JSON.stringify(ourObj)},
success: function(response)
{
alert("data sent response is "+response);
},
error: function(e)
{
alert("data not sent"+e);
}
});
}
</script>
<button onclick="sendArray();">Send Array</button>
My php:
if(isset($_POST['invAdj'])) {
$invAdj = json_decode($_POST['invAdj']);
$itemId = $invAdj->itemId;
$amtAdj = $invAdj->amtAdj;
}
mysqli_query($link, "UPDATE stock_levels SET stocklevel = stocklevel + " . $amtAdj . " WHERE id = " . $itemId);
?>
Presently, I get a successful alert, but the level does not change in the db. I know that the db info works and the sql query works because if comment out the post block an add solid variables, it runs perfectly. I have something screwed up in the POST block.
Any help would be greatly appreciated! Again, sorry if this has been answered, but I couldn't find a post that worked...
Also, I know that I shouldn't put the SQL directly into my query. I am just trying to get this working first.
Thanks
Hi i have the following code but i am not able to access the values in my request.php file from this.
$(document).ready(function(){
$("select.location").change(function(){
var Did = $("input[name='district']").val();
var selectedLocation = $(".location option:selected").val();
$.ajax({
type: "GET",
url: "request.php",
data: {location : selectedLocation, Did:Did},
}).done(function(data){
$("#response").html(data);
});
});
});
and my request.php is calling the data like this
if(isset($_GET["location"]))
{
$i=0;
$bfrom = $_GET["location"];
$did= $_GET["Did"];
$sql = "SELECT distinct stopname FROM `route` WHERE `rfrom` LIKE '$bfrom' and did=$did";
$result = $conn->query($sql);
first off, and most importantly, for security you need to parameterize your query. See PHP: Prepared statements and stored procedures
Secondly, your LIKE argument needs to be preceded and followed by % - eg '%$bfrom%' - this enables "wildcard" data search MySQL Wildcards
Lastly, you need to echo a response in the AJAX call, in order for the receiving javascript to pick it up :)
I know this has been asked so many times by now you all are probably sick of it. I'm just stuck and have already spent about 4 hours on this. I've read through many suggestions already about the
cache:false,
option and adding certain "content-types", but when I do this, it no longer works in any browser.
I followed the tutorial as found here: http://www.x-developer.com/php-scripts/loading-drop-downs-with-ajax-php-and-fetching-values-from-database-without-refreshing-the-page
and I modified it of course to my needs, mostly just the mysql and identifiers.
This is what I have in my head section:
<script type="text/javascript">
function get_cities(country)
{
$.ajax({
type: "POST",
url: "/cities.php",
cache: false,
beforeSend: function () {
$("#state").html("<option>Loading ...</option>");
},
data: "country="+country,
success: function(msg){
$("#state").html(msg);
}
});
}
</script>
In IE, it gets to the Loading.... part, and does nothing, it doesn't populate the option field as it does in Chrome and FF.
Do you see anything in the tutorial that he may have left out that is crucial for the operation in IE?
Thanks,
Try setting the data object as a key value pair..
Instead of
data: "country="+country,
try
data: { "country" : country },
assuming your $("#state") is already a dropdown list.
in cities.php, you'll need to remove the <select> tag.
<?php
// Code for cities.php
$country_id = $_REQUEST['country_id'];
$sql_city = "SELECT * FROM CITY WHERE country_id = '".$country_id."'";
$result_city = mysql_query($sql_city);
// REMOVE THIS LINE
//echo "<select name='city'>";
while($row_city = mysql_fetch_array($result_city))
{
echo "<option value='".$row_city['id']."'>".$row_city['city']."</option>";
}
// AND REMOVE THIS LINE
// echo "</select>";
?>
I have a webpage with some broken images, these images are being show by a database. I am using the following jQuery to hide the images that are broken.
//images are wrapped in an anchor
$("img").error(function() {
$(this).parent().hide();
});
I would like to utilize the "status" column in the database to set all of the broken images to "hidden". Every anchor that wraps an image on the page has a "id" attribute that matches the primary database key "id".
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: "status=hidden&id=".error.""
});
});
// changestatus.php
<?php
mysql_connect("localhost", "stackoverflowexampleuser", "stackoverflowexamplepass") or die(mysql_error());
mysql_select_db("stackoverflowexampledatabase") or die(mysql_error());
$id = $_POST['id'];
$status = $_POST['status'];
$query="UPDATE stackoverflowexampletable SET status = '".$status."' WHERE id ='".$id."'";
mysql_query($query) or die ('error');
mysql_close();
header( 'Location: MYSOURCE' ) ;
?>
This is my first stab at ajax, and I know I got some stuff seriously wrong. I saw a couple of examples using KEY VALUE pairs but I don't know what the $_POST['var'] should be.
Can you even request something like this "when the page loads"? I tried wrapping it in an arbitrary button and it didn't work.
Since this just needs to be used once I'm not really focused on using AJAX.
Try this:
$("img").error(function() {
var error = $(this).parent().attr('id');
$.ajax({
type: "POST",
url: "changestatus.php",
data: {
status: "hidden",
id: error
}
});
});
If you're wanting to initiate it on page load, be sure to include it in the $(document).ready() function.
My question is... How to make json have 1 call back with several objects.
I will use this example of 3 values to be returned... Here is the calclickM.php file, but I can not understand why it is not woking...
<?php
$choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d");
$con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$choice."' group by date"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$dayPowerP = array ('dayPowerP');
?>
<?php
$choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$monthPowerP = array ('monthPowerP');
?>
<?php
$choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$yearPowerP = array ('yearPowerP');
?>
<?php
$outarr['dayPowerP'] = $dayPowerP;
$outarr['monthPowerP'] = $monthPowerP;
$outarr['yearPowerP'] = $yearPowerP;
echo json_encode($outarr);
?>
Here is the Jquery I am using to post and the json
<script type="text/javascript">
$(document).ready(function () {
$('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) {
var myDate = $(this).datepicker('getDate');
$('#apDiv1').html($.datepicker.formatDate('DD, d', myDate));
$('#apDiv5').html($.datepicker.formatDate('MM', myDate));
$('#apDiv7').html($.datepicker.formatDate('yy', myDate));
$.ajax({
type: "POST",
url: "calclickM.php",
data: {choice: dateText},
dataType: "json",
success: function(json_data) {
$('#apDiv2').html(json_data['dayPowerP']);
$('#apDiv6').html(json_data['monthPowerP']);
$('#apDiv8').html(json_data['yearPowerP']);
}
})
}});
});
Thanks,
Alan
At first the load method you are calling is making an AJAX GET request to your server. You probably support both POST and GET requests in your PHP script.
Secondly you have some errors in the your $.ajax calls. There are some unterminated strings, the data variable you are using as ('#apDiv9').html(data) isn't defined and if it was, it will be probably contain JSON data that you can't directly put in an HTML element.
Last, but not least, the second attempt won't make your code faster. A browser can only support a limited number of parallel ajax requests (1-2). You are still making the same number of requests and some of them need to wait for the others to complete. Re-design your code so that you return everything in a single call.
Not a solution to your immediate problem, but your code needs some serious refactoring. The level of repetition here hurts my eyes. The second code block, the one with the ajax-calls, could be changed to something like this:
var pages = [
{ url: "dayPower.php", div: "#apDiv4" },
{ url: "dayGraph", div: "#apDiv2" },
{ url: "monthPower.php", div: "#apDiv6" },
{ url: "monthGraph", div: "#apDiv9" },
{ url: "yearPower.php", div: "#apDiv8" },
{ url: "yearPower", div: "#apDiv10" }
};
for ( var i=0; i<pages.length; i++ ) {
$.ajax({
type: "POST",
url: pages[i].url,
data: { choice: dateText},
dataType: "json",
success: function(json_data )
(pages[i].div).html(data).show(); // Did you mean json_data here?
}
});
}
The case is similar with the first piece of code in your question.
Once again, I know it won't solve the actual problem, but it will make it easier to implement the solution when you (or someone else) finds it.
EDIT
On second thought, I can see at least one strange thing: in the success-function you call the parameter json_data, but you access a variable that you've called data. Did you intend to name them the same thing?
There is a way to do what you are asking, but you will need to handle the results yourself. Essentially all your Ajax calls have the same parameters, but different resultsets. So first, the client side code that does the magic:
$.post('datePacked.php', {choice: dateText}, function(data) {
$('#apDiv2').html(data['dayPower']);
$('#apDiv4').html(data['dayGraph']);
$('#apDiv6').html(data['monthPower']);
$('#apDiv9').html(data['monthGraph']);
$('#apDiv8').html(data['yearPower']);
$('#apDiv10').html(data['yearGraph']);
});
If you refactored your HTML so taht you actually match the div Ids with the result of your JSon response, you can simplify the call even further:
$.post('datePacked.php', {choice: dateText}, function(data) {
$.each(data, function(id, value) {
$('#'+id).html(value);
});
});
On the server side your new datePacked.php needs to return a JSON result that provides a hash of names to content. Essentially it will look something like this:
{ "dayPower" : "<p>My Content</p>", "dayGraph" : "<p>Day graph</p>", ... }
The ellipsis is there for you to fill in the remainder of the content. Choosing meaningful id names for your HTML elements is not only good practice, it can save you a lot of repitition if you take advantage of it. An example of that would be the second form of the client example. This is a case where the content has to be JSON for it to work--unless you want to split up a DOM returned by the server.
I’m not exactly sure what you’re asking, but here’s a couple of points:
$('#apDiv2').load('dayPower.php', {choice: dateText} does the same thing as $.ajax({type: "POST", url: "dayPower.php", data: { choice: dateText}. Both $.ajax and $.load make HTTP requests via JavaScript, which is what “AJAX” means.
Your second block of example code has some basic syntax errors. Here’s the first $.ajax call corrected:
$.ajax({
type: "POST",
url: "dayPower.php",
data: { choice: dateText},
dataType: "json",
success: function(json_data ) { // “{” added to start the function block
('#apDiv2').html(data).show();
}
}) // “})” added to end the object literal and function call
if you never need call any of this separately, why not just make one ajax call to a php file, package all your data into a multidimensional array, convert to json, and send back to the client.
Once you have this json, you can then break it up with js and figure out what goes where on your front end.
Depending on how much data you're getting it may take a while. If it's a huge query, then breaking it up into several little calls be actually be better. Its asynchronous so at least parts of your page will be loading. while other parts are gathering data.