i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.
Related
Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});
In Javascript I'm creating an array for a user side list
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
alert(dataArr[0]);
This is working as expected and will alert the first item in the list. "Frank" or whatever it may be.
$.ajax({
url: "fiddle.php",
type: "POST",
data: "dataArr="+dataArr,
success: function(response) {
alert(response);}
I send this array over to PHP and the ajax test confirms its retrieved from a var_dump on the other side.
echo ($_POST['dataArr'][1]);
The problem occurs here when trying to output a particular item, in this case the 2nd item which may be "John" it'll instead output the 2nd character in the first item "r". This is appearing in the Ajax test window. I'm looking for the whole word instead.
Is it a syntax error or a problem with how the data is passed?
I think the problem is related to how you are sending your data in the ajax call.
Try this:
JS
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
$.ajax({
url: "fiddle.php",
type: "POST",
data: dataArr, //Send just the array
success: function(response) {
alert(response);
}
});
PHP
var_dump($_POST['dataArr']);
It is because your array is getting converted to string form.
do JSON.stringify() at client side and json_decode at server side
like
in the ajax call
data: "dataArr="+JSON.stringify(dataArr),
and in the php code
$dataArr = json_encode($_POST['dataArr']);
var_dump($dataArr);
I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();
I have this for loop in jquery
$(document).ready(function() {
for(i=0; i<counter; i++)
{
dataCounter = i;
$.ajax({
url: 'file.php',
dataType: 'json',
data: dataCounter,
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
}
});
And then I want to bring in my dataCounter into the file.php as a variable and have it change each time so I can get different records in mysql in file.php, am I doing this right? How would the php portion look like? I know how pass variables to a php file with this method if I had a form, but I don't have a get or a post form to work with. Also, my variables are going to change.
Can someone help me? Thank you!
While I don't recommend running an ajax query inside of a loop, I am wiling to explain the data option for $.ajax(). Ideally, you pass an object as the data option, and it is translated by jQuery into a query string where each object property name is a key and its value is the value:
data: {
count: dataCounter
}
becomes
?count=1
in the query string of the ajax request if datacounter is equal to 1.
In PHP you would access it as $_GET['count'].
data needs to be a key-value pair, not just a value as you have it here. Try something like: (not tested)
$.ajax({
url: 'file.php',
dataType: 'json',
data: ({dataCounter : dataCounter}),
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});
the ones you should always set are url,success and data if needed, please read The Documentation for more information.