I'm trying to pass a collection of parameters to a PHP page to be processed, from a JavaScript function:
entries: "test data from JavaScript"
In my PHP page I'm trying to grab the value that was posted back to the page:
$_POST['entries']
but this keeps return 'emtpy', regardless of what I try to push through. I'm new to PHP so this might be a stupid thing to fix.
This is invoked from a button click like such:
$("#submitButton").click(function(){});
Should the be wrapped in a form, as I don't see the need for this?
Update [full code]
var proxy = new ServiceProxy("submit.php");
$("#submit").click(function () {
var store = $("#store_name").val();
var contact = $("#contact_person").val();
proxy.invoke("", { entries: store }, success, error, false);
return false;
});
Note on the ServiceProxy. This proxy class wraps the default $.ajax {...} into a neat little proxy class, thanks to Rick Strahl over at west-wind. I've used this proxy class successfully in numerous single HTML and ASP.Net solutions in the past, so I don't it's the proxy service that's causing the issue.
Looks like your using jQuery, so why not use their post function?
$.post("/file/location/post.php", { Name: "Hello", Email: "email#address.com" } );
Then in your php code you can use:
$_POST['Name'] and $_POST['Email']
Hope this helps.
Sorry, just seen your updated code - this should work:
$("#submit").click(function () {
var store = $("#store_name").val();
var contact = $("#contact_person").val();
$.post("submit.php", { entries: store } );
return false; });
Related
NOTE - This is a edited snippet. This is testing at the moment and will be improved after.
I'm aiming to learn oop PHP now I got a good understanding of procedural. I'm stuck on sending this Ajax request to my php file.
Html File
<script>
$("#Question").click(function() {
flag = 1;
uid = "<?php echo $uid ?>";
var dataQuestion = {
uid,
flag,
ImageOne: $("#Image1").val()
};
//Post with AJAX
$.ajax({
type: "POST",
url: "../View/class.user.php",
data: dataQuestion,
perform: "QuestionsFunctions",
success: function(Returned){
$(".NotBoxSmall").text("Updated");
$(".NotBox").text("Updated");
flag = 0;
console.log(Returned);
},
error: function(){
$('.NotBox').text("Issue With Site");
$('.NotBoxSmall').text("Issue With Site");
}
});
});
</script>
Php file
<?php
public function QAsk(){
if($_POST['flag'] == 1){
$Image1 = $_POST['ImageOne'];
$uid = $_POST['uid'];
$insertsqlQ = "UPDATE UsersData
SET Image1 = '$Image1'
WHERE uid = $uid";
$resultquestion = mysqli_query($this->db,$insertsqlQ) or die(mysqli_connect_errno().json_encode("Data cannot inserted"));
return $resultquestion;
echo json_encode("Question Updated");
}else{
echo json_encode("Question NOPE");
return false;
}
}
?>
The id sends and iv'e tested this not within the public function and it appears to be fine. The request send back is blank, outside of the function it's the error log.
The issue is it says questions have been updated but no data has been added to the database.
jQuery must be initialized after the DOM ( document object model ).
How should I initialize jQuery?
I'd suggest some tips:
1 - Make the id names lower case #name_of_element
2 - Grab a OO PHP book and try to practice just this, run tests using curl for instance and make your database rules work before going into the client (html, js, css)
3 - Grab a jQuery book and run tests with mock data just printing a array from PHP. At the beginning is easier study stuff separated.
4 - '$Image1' is a varchar rather than the variable $Image1. Remove the quotes
I am using the jquery plugin datatables and am trying to take advantage of the fnRender function to manipulate some data.
I have a php script that returns a JSON string from my $.post. Here is a sample response that I get from each post: {"description":"myvalue"}. I got this from the Google Chrome Developer Tools.
Here is my post function:
$.post("functions/getDescription.php", {gpn:oObj.aData[1]},
function(data) {
returnedVal = jQuery.parseJSON(data);
var test = returnedVal.description;
//alert(test);
return test;
});
Here is my php script:
$passedVal = mysql_real_escape_string(($_POST['gpn']));
$descriptionPrint = array('description' => "");
include 'db_include.php';
$getDescription = "SELECT part_number_description, description FROM unit_description
WHERE part_number_description = '$passedVal' ";
$result = mysql_query($getDescription,$db) or die(mysql_error($db));
while ($row = mysql_fetch_array($result)) {
extract($row);
$descriptionPrint = $description;
echo json_encode(array('description' => $descriptionPrint));
}
There is only one value returned from each query.
Every row alerts the right value but returns undefined.
If I replace javascript function with only a return value of a string or any generic value it works fine.
I feel like there has to be something silly I'm missing in all this. Any help is much appreciated and please let me know if you need more information (I know troubleshooting something running in a plugin like datatables can be frustrating). Thanks.
Because $.post does not return the return value of the anonymous callback function you pass to it as its third argument.
Since Ajax is asynchronous, $.post even returns before the callback function is executed.
If you want to do something when the data gets back from the server, then the callback function has to to it (or call another function to do it).
This is the same reason that the following wouldn't work:
var were_you_expecting_sunshine = $('button').click(function () {
return "sunshine";
});
ajax is not yet sothin i master.
I have two forms field
code :
name :
and the submit button like :
<form><input type=text name=code><input type =text name=name/></form>
I would like in php/jquery to check if the code the user fill exist in a table of my db.
If it does not exits, when the user leave the textfield to fill the next one, i would like to print a message like: this code is not in the db and then clean the fied. Until the user provide a valide code.
If your php service returns true or false for validation.
and the placeholder for the error is a label called
then an example (in jQuery) would be
$(document).ready(function() {
$("form").submit(function(e) {
var code = $("input[name='code']");
var error = $("#error");
e.preventDefault();
var form = this;
$.getJSON('urlToPhp',
{ code: code.val() },
function(valid) {
if (!valid) {
error.text(code.val() + ' is not found try another code...');
code.val('');
} else {
form.submit();
}
}
);
});
});
I've created a simple example at http://jsfiddle.net/nickywaites/e4rhf/ that will show you have to create a jQuery ajax post request.
I'm not too familiar with php so that part of it I'll have to leave aside although you can use something along the lines of $_POST["Name"].
Here is php example that I googled http://php4every1.com/tutorials/jquery-ajax-tutorial/ that might be better for you.
I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}
I'm trying to use jQuery.post() function to retrieve some data. But
i get no output.
I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.
My scriptfile looks like this:
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.
jQuery.post("../functions.php", { storeID: "storeID" },
function(data){
alert(data.name); // To test if I get any output
}, "json");
});
});
My PHP file looks like this:
<?php
inlcude_once('dal.php');
//Get store data, and ouput it as JSON.
function getStoreInformation($storeID)
{
$storeID = "9";//$_GET["storeID"];
$sl = new storeLocator();
$result = $sl->getStoreData($storeID);
while ($row = mysql_fetch_assoc($result)) {
{
$arr[] = $row;
}
$storeData = json_encode($arr);
echo $storeData; //Output JSON data
}
?>
I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.
since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
I don't think I'm passing the storeID parameter correctly. What is the right way?
How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" }
Is the getNameAndTime the name of the function in test.php ?
I have gotten one step further.
I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.
My js script now looks like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data);
}, "text");
});
This results in an alert window which ouputs the store data as string in JSON format.
(because I have changed "json" to "text").
The JSON string looks like this:
[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten#brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]
Now, what I really want, is to ouput the data from JSON.
So I would change "text" to "json" and "alert(data)" to "alert(data.name)".
So now my js script will look like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data.name);
}, "json");
});
Unfortunately, the only output I get, is "Undefined".
And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".
So how do I output the name of teh store?
In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ?
(currently I have hardcoded the storeID, for testing)
Lose the quotes around "storeID":
Wrong:
jQuery.post("../functions.php", { storeID: "storeID" }
Right:
jQuery.post("../functions.php", { storeID: storeID }
bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.
However, a couple more notes:
It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
EDIT As far as your reply, if you break down what you are returning:
[
{
"id":"9",
"name":"Brandstad Byporten",
"street1":"Jernbanetorget",
"street2":null,
"zipcode":"0154",
"city":"Oslo",
"phone":"23362011",
"fax":"22178889",
"www":"http:\\/www.brandstad.no",
"email":"bs.byporten#brandstad.no",
"opening_hours":"Man-Fre 10-21, L",
"active":"pending"
}
]
This is actually an array (the square brackets) containing a single object (the curly braces).
So when you try doing:
alert(data.name);
This is not correct because the object resides as the first element of the array.
alert(data[0].name);
Should work as you expect.
Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]
so this would work.
wrong: alert(data.name);
right: alert(data[0].name);
Hope that helps.
D
Ok, thanks to Darryl, I found the answer.
So here is the functional code for anyone who is wondering about this:
javascript file
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML }, // this.cells[0].innerHTML is the content ofthe first cell in selected table row
function(data){
alert(data[0].name);
}, "json");
});
});
get_storeData.php
<?php
include_once('dal.php');
$storeID = $_POST['storeID']; //Get storeID from jQuery.post parameter
$sl = new storeLocator();
$result = $sl->getStoreData($storeID); //returns dataset from MySQL (SELECT * from MyTale)
while ($row = mysql_fetch_array($result))
{
$data[] = array(
"id"=>($row['id']) ,
"name"=>($row['name']));
}
$storeData = json_encode($data);
echo $storeData;
?>
Thanks for all your help guys!