Maybe I need to go about it another way, but here is what I am trying to do (it's simple) I send data to a PHP function using ajax. Here is an example.
function myAjax(){
//The data here comes from an ajax call
$_POST['id'];
$_POST['x'];
$_POST['y'];
}
The ajax looks like this
jQuery.ajax({
type: "POST",
url: window.ajaxurl,
data: { "action": "myAjax", id: divid, x: pos_x, y: pos_y }})
}
This is not the complete ajax code, this is inside a jQuery UI event but it's irrelevant, the important part is the data:{}
The data from the PHP code is stored into a database, I run code inside the function to interact and add the variables, but again that is irrelevant... how can I access these variables outside of this function?
Lets say I am echoing a div and I want to use $_POST['id'] as an ID for that div. example
echo '<div id="'.$_POST['id'].'"></div>';
This code is obviously outside the function... so I am still a newbie and would be grateful if someone can point this out to me :)
First, in order to understand what data you are getting, you should do a var_dump in PHP:
var_dump($_POST);
This will show a list of key/value pairs, based on that you can then output the information as needed.
Note that jQuery might do some automatic conversion on the data, for example it might convert your object to JSON. In this case, decode the data server-side using json_decode.
Apparently you have to store request params somewhere and then pass them anywhere you need. For instance,
// well, this is quite straightforward
$requestParams = $_POST;
// then pass params to your function
function myAjax(array $params) {
// here you have local copy of your $_POST parameters
// EDITED: you can store data in database and return the result, an ID of
// the row for example
// some insert SQL
$id = mysql_insert_id();
return $id;
}
$newRecordId = myAjax($requestParams);
// here (outside function) you have a global $params variable which you can use
// to echo a div for example
Related
i have a form that fetches all the data from database and in order to update the datas that is fetched i need to serialize the data.
alert($("form").serialize());
and this is the output
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
how to retrieve this data in php in order for me to update the database?
You have to combine functions $.submit() and $.post() or $.ajax():
$('form').submit(function() {
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script
}
});
return false;
});
Then in your PHP script you have to read your data from $_POST array. E.g.
$tid = $_POST['tid'];
To debug your incoming $_POST array use var_dump() or print_r().
If you want to send response to your javascript just pack whatever you want into variable and then just use die(json_encode());. E.g.:
$output = array('status' => true, 'message' => 'Success');
die(json_encode($output));
It also will be required to add to $.post() method attribute:
dataType : 'json'
In your PHP, at the top write this and you'll see what's happening.
//If method = GET
var_dump($_GET);
//If method = POST
var_dump($_POST);
exit();
This will show all variables that are being passed and stop the script so you can review on the page. Then just have your jquery put the response data in a div that you can view.
The problem seems to be that you are redefining your $_POST vars. They can not contain the same names/keys as you are sending them over currently. Essentially its like redefining a variable, it will no longer contain its previous value.
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
Notice how you have called tid and the other keys multiple times? Instead you would want to give them separate names,or pass an array of values to your PHP.
Example:
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid2=2&tname2=Super&tsize2=XS&quantity2=1&tprice2=2800&tid3**=3&tname3=Dota+Tees&tsize3=XS&quantity3=1&tprice3=700
Of course there are other ways of doing this as well.
Each key must have a unique identifier, other wise it will overwrite the previously defined $_POST value.
Instead of:
tid=1&
tid=2&
tid=3&
You would want:
tid1=1&
tid2=2&
tid3=3&
Looks like a job for PHP's parse_str() function. http://php.net/manual/en/function.parse-str.php
Based on the user input's, i calculate some values on my submit action of my form. I have to persist these values in my backend DB. I use PHP for my server side scripting. Please let me know the best practice for doing this. It is a single page application and i use .load("Report.html"); to show the summary page.
Just thinking aloud, can i fetch the row(to be updated) from DB, json_encode, update the json object in jQuery, decode it, then update in DB?
Please help...
My submit button code...
$('form').on('submit', function(event)
{
event.preventDefault();
//CALCULATE SCORE
var noOfCorrectAnswers = 0;
var noOfQuestionsViewed = 0;
$.each(questionsArray, function(i, item)
{
if(item.correctOption == item.selectedAnswer)
{
noOfCorrectAnswers++;
}
if(item.isQuestionViewed == 'YES')
{
noOfQuestionsViewed++;
}
});
alert(noOfQuestionsViewed);
$('#sampleDiv').load("UserReport.html");
});
Run some AJAX passing all of the information you need (which may even be none depending on your use case) from the client-side to your server-side PHP. Your PHP script can fetch things from the database if necessary, make any calculations and/or manipulations and then store the information back in the DB.
If you need to return information to your client-side after updating the database then try returning a JSON object (by just printing the code out in the proper format) from your PHP script before exiting with whatever your JS needs.
Do note that this should be all done asynchronously, so you need to setup your AJAX callback function to handle any information that's returned from your PHP script. If you want to do it synchronously, go for it - but you asked for best practices :P
Looks like you're using jQuery - here's the documentation on AJAX
Raunak Kathuria's answer provides some same code
On form submit make ajax call to set database in the db and access the json
$('form').on('submit', function(event)
{ ...
alert(noOfQuestionsViewed);
$.ajax({
url: "yourphp.php", // php to set the data
type: 'POST',
data: 'yourparams', // all the input selected by users
dataType: json
success: function(json){
//here inside json variable you've the json returned by your PHP
// access json you can loop or just access the property json['sample']
$('#sampleDiv').load("UserReport.html", function () {
// its callback function after html is loaded
$('#someid').html(json['sample'));
});
}
})
You can also use the done callback of ajax
PHP
yourphp.php
Set the values here in db running the desired query and return values using
<?php
// your db ooperations will come here
// fetch the db record
// return the db records in json
$responseVar = array(
'message'=>$message,
'calculatedValue'=>$calculated
);
echo (json_encode($responseVar));
?>
I am trying to get data from an SQL Database through jQuery, Ajax and PHP.
Here is the jQuery Code
$.ajax({
url: 'OpenQuiz.php',
data: '',
dataType:'json',
success: function(data) {
var one = data[0];
}
}
$(document).ajaxComplete(function(event,request,settings) {
alert("check");
}
Here are the json encode lines at the end of the PHP file called "OpenQuiz.php"
echo json_encode($QuizName);
echo json_encode($options);
echo json_encode($votes);
echo json_encode($row_num);
echo json_encode($percentage);
echo json_encode($TruncPercentage);
Please note:
$options, $votes, $Percentage and $TruncPercentage are all two-dimensional arrays.
$row_num is an integer.
$Quiz_Name is a single-dimensional array.
I find that the jQuery runs fine and the ajax request is called because the alert box for "check" shows up. The problem is that I dont know how to access the variables after they have been transferred. I know that it has something to do with data[0] but I don't really understand what "data[0]" means or what it represents. Basically how to I access the variables that I have sent using json_encode in the PHP file?
data[0] is the first json_encoded item in the array returned. You shouldn't json_encode everything separately, you should build an array and json_encode this.
$items = array('QuizName'=>$QuizName,'options'=>$options, ... ,'TruncPercentage'=>$TruncPercentage);
echo json_encode($items);
Then you retrieve with:
success: function(data) {
var qn = data.QuizName,
opt = data.options;
}
And so on for each item, with data.[whatever], and [whatever] being the name of the item you gave it in the array. I know I originally said to retrieve by index (data[0]), but I prefer to retrieve explicitly so that the code is more maintainable.
As a side note, you can eliminate the datatype:'json' declaration in your ajax call by simply setting the header correctly on the PHP side:
header('Content-type: application/json');
Placing that at the top of the document will force the server to recognize the page as json. Far more consistent and explicit than having jQuery look for it.
need to pass data to android app through ajax by using php.
the data is pulled from mysql database through a select query
please provide me code example how to perform the task
i had search the internet and i find the below code for reference
http://www.grobmeier.de/android-does-not-fire-ajax-reqests-because-they-are-caches-ajax-requests-at-least-on-jquery-mobile-10072011.html#.UGvLbU3A-RI
how to perform the select query to fetch the data array.
please correct me if the example is not proper.
$.ajax({
url: "yoururl.html",
context: document.body,
cache : false,
data: {
username : $('#username').val(),
password : $('#password').val(),
},
success: function ( data ) {
// do something
}
});
What you need is a regular HTTP request (made from AJAX, of course): you send variables to the server by the method you choose. Something like: http://www.example.com/script.php?var1=foo&var2=bar Those variables can be accessed within script.php this way:
<?php
echo $_GET['var1'], PHP_EOL; // shows foo
echo $_GET['var2'], PHP_EOL; // shows bar
?>
If you use POST method instead of GET you must use $_POST[<whatever>] to access you variables.
Once you got the values within PHP you can execute the query you need to persist that data.
There is a ton of this arround Internet, if you make a minimal search you will find exactly what you want.
In an earlier post today the answer has led me down the route of using a JSON feed to populate elements in my page.
Something new to learn!!
the JSON data is created from a PHP script which retrieves the data from a Mysql database. The php script retrieves a specific record which I need to pass to the php script with the getJson call.
I've had success with creating the url with the parameters added as a GET method but I can't find an example of a POST method - the parameters should go as an optional parameter. here's what I have so far...
function loadData(index) {
alert(index);//debug
$.getJSON('loadJSONholeData.php' ,
{hole: index} ,
function(data) {
I've found examples for a twitter feed which shows a parameter like option: "cat", but can't find an option where the value is in a variable.
I don't understand how to use the parameters - where am I going wrong. Appreciate this is probably a fundamental issue but I'm learning.
Thanks
Update:
I've revised the code per the responses below and used both suggestions to pass the POST parameter, but the receiving PHP code is not reading the POST parameter and just returns the default query values.
I even used as static value of 1 both as a value and as a string but no joy.
Here's my receiving PHP code which accesses the POST values:
$hole = 3;
if (isset($_POST['hole'])) {
$hole = $_POST['hole'];
}
I'm missing something basic here. The value in 'index' definitely exists as it shows in the debug and JSON data is being returned )(but the default). I can go back to my GET method but want to see this work!!
Thanks
Update: Success!!
I played around further with the revised code. I removed the content type parameter from the code and it all works now, the PHP is returning the correct query.
I assume then that by specifying the JSON type in contentType it passes the POST parameter in a different way to PHP which expects it in anpther way?
Onwards and upwards - thanks
The $.getJSON() method does an HTTP GET and not POST. Try something like this -
$.ajax({
url: 'loadJSONholeData.php',
data: JSON.stringify({hole: index }),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
//(result.d) has your data.
}
});
Each key/value pair in the arguments object will represent a parameter in the HTTP POST. You can use variables as values, but I believe they will be converted to strings, so it's better to do the conversion yourself (so you can make sure they have the correct format). A simple example:
var dynamicValue = foo();
$.post('my/url', { var1:"static value", var2:dynamicValue }, function(data) {
// Your callback; the format of "data" will depend on the 4th parameter to post...
}, "json"); // ...in this case, json
Now, in case your server is expecting a json encoded object/list, you can pass it by using JSON.stringify:
function foo() {
return JSON.stringify({ my:"object" });
}
JSON should be available in most modern browsers, in case it's not, you can get it here (json2.js, under "JavaScript").