Posting elements generated by JS (JQuery) to a PHP script - php

so I'm writing this form for teams and doing this 'add player' function where you enter a player name in a textfield, check a box for medically ok and click a button which then appends the name to a div above, adds the value to an array and clears the textfield below, like so:
<script>
var players = New Array();
function addPlayer(){
$('#players').append($('#addPlayerField').val());
var playerInfo = New Array($('#addTermCheckbox').prop('checked'),$('#addPlayersField').val());
addingTerms.push(playerInfo);
$('#addPlayerField').val('');
}
</script>
Whats the best way to post the final array to a php script?
Thanks guys!

I would use JQuery's ajax method:
$.ajax({
type: 'POST',
url: url,
data: 'players='+$.toJSON(players),
success: function (data) {}
});
http://api.jquery.com/jQuery.post/

What do you meen with posting the final array to a php script? If you want to send the information to a php script try looking the jquery documentation about ajax (to send the data to the php file without reloading the page) and json (to convert your array into a text form and then beeing able to rebuild the array in the php file)

Do you mean sending the array elements to a PHP script? in JSON and use json_decode() in PHP. Depending on what information you need, json_decode() can either convert to an associate array, or objects. Use JQuery-Json which will add the ability to encode JSON in your code.

Related

How to pass datatable (HTML table with selected dropdown) values to array in PHP?

I need to fetch values of datatable cells having dropdowns that are selected. And pass the value to an array.
How can this be done using php, jquery?
Share with example
I am noob like you, but I've learned some php mysqli from here (note: always type misqli instead of mysql in your code)
https://m.youtube.com/watch?list=PL7lhMROXakvdLAUKFNLYl_J2Ti0Ulr6ID&params=OAFIAVgB&v=dWzzRkxrTMA&mode=NORMAL.
And about json:
alue into the the input's max attribute. Something like this will do the trick.
window.onload (//or what trigger method you need) = function() {
var (//name a var) = $('#idOfElementTogetValueFrom').val();
$.ajax(
{type: 'post',
url: 'path to php doc.php',
dataType: 'json'
data: {
NameX: nameOfVar declared above,
},
success: function (response){
$('#idOfelementWhereToDisplayphpResponse').html(response.matchthatnameinPhp);
}
});
}
In your php js variable will be like $_POST['NameX'] (do what you need with it)
Then in php
echo json_encode array(
"matchthatnameinPhp" => any php you need, vars
etc.(//this will be displayed in html)
(//You can add more rows of datas here)
)
See also: Send JSON data from Javascript to PHP?
I got the solution, by saving the data in an array and on submit button passing it to controller

onclick -> mysql query -> javascript; same page

I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Passing PHP variable to Jquery without refresh

I apologize upfront for my lack of jquery knowledge. In this website I am building, a user is presented with a number of thumbnail images representing plants. When a thumbnail is clicked, a jquery popup is initiated. What I would like to be able to do is pass a php variable that has the ID of the plant over to the jquery popup to display the prper information. Any help would be greatly appreciated. Thank you.
EDIT: http://www.plantcombos.com/header/main_index.php?display=random_mix
Im pretty sure you dont need to query PHP each time ... something like this would work :
<img class-"imgclick" src="/small-plant.jpg" data-id="123" />
This would be the output from your server side (php if thats what your using) - it stores the ID of the image in the data attribute
JavaScript :
$(document).ready(function() {
$('.imglink').click(function(event) {
event.preventDefault();
$('dialogid')
.data('image_id', $(this).data('id'))
.dialog('open');
})
})
the image id from the data attribute is then passed to the data attribute of the dialog. This attribute can be accessed using $(this).data('image_id') form within the dialog then
Use the jQuery AJAX method to gather data from a PHP file and display it on the page. It is very easy and you can pass any variables (parameters) you like to the page.
http://api.jquery.com/jQuery.ajax/
For example:
// This will send a request to a PHP page
$.ajax({
url: "http://example.com/test.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
$('#image').html(data);
}
});

Passing values from ajax page to calling page javascript function

One part of my page is being loaded via ajax using jquery. For example this initial page has a name first.php. It has a div with it's innerHTML generated from ajax called script (for example ajax is calling second.php). Is it possible to pass some values from ajax executed script (second.php) to original site. I need to access this value from original site (the one calling second script via ajax) javascript function, and I don't want to use hidden fields.
For example, my site has some captcha that is being displayed and processed through ajax. I don't want to write captcha result to some hidden field and access it with original site javascript function because of possible javascript injection attack...
Since you call your secound.php script via ajax, you surely could read the result.
$.ajax({
url: 'secound.php',
success: function(data) {
// now data contains the code returned by secound.php
}
});
Now the most common way to return data from your secound.php script is returning it in JSon format. Then you could do someting like:
var obj = jQuery.parseJSON(data);
alert(obj.name);
For this example your secound.php needs to return
{"name":"John"}

Sending jQuery.ajax data simultaneous to a form submit

I have a bit of a conundrum. I have a form which has numerous fields. There is one field for links where you enter a link, click an add button, and the link(using jQuery) gets added to a link_array. I want this array to be sent via the jQuery.ajax method when the form is submitted. If I send the link_array using $.ajax like this:
$.ajax({
type: "POST",
url: "add_stock",
dataType: "json",
data: { "links": link_array }
});
when the add link button is selected the data goes no problem to the correct place and gets put in the db correctly. If I bind the above function to the submit form button using $(#stock_form).submit(..... then the rest of the form data is sent but not the link_array.
I can obviously pass the link array back into a hidden field in HTML but then I'd have to unpack the array into comma separate values and break the comma-separated string apart in PHP. It just seems 100X easier to unpack the Javascript array in PHP without an other fuss.
So, how is it that you can send an array from javascript using $.ajax concurrent to the rest of the $_POST data in HTML?
Please note that I'm using Kohana 3.0 framework but really that shouldn't make a difference, what I want to do is add this js array to the $_POST array that is already going.
Thanks!
If you actually want to submit the form (e.g., with page refresh and all that), your only option is to add a series of <input type='hidden'> fields to the form with the name links and fill each of them with one of the values from the array. Then what you get at the other end will be essentially what you get with your $.ajax call above.
If you just want to send the data to the server but you don't actually need to submit the form, you can use serialize on the form to get a URL-encoded string for it, then append your links to the end of the string, and send that via ajax. Something like this:
// Assuming 'link_array' is present
var data, n;
data = [$('#TheFormID').serialize()];
for (n = 0; n < link_array.length; ++n) {
data.push("links=" + encodeURIComponent(link_array[n]));
}
$.ajax({
type: "POST",
url: "add_stock",
dataType: "json",
data: data.join("&")
});
We get the beginning of the URL-encoded string from serialize, initialize an array with it, then push encoded fields for each link on it. Then we use Array#join to collect that all into one string to send with the ajax call. (You could do this with string concat instead if you like, but building these long strings with an array is faster after a certain number of elements, and makes the whole "do I put an & on it or not" just fall out naturally as well.)
You will have better luck using jQuery's serializeArray or serialize function, and then adding in the extra fields you have, and finally submit the POST data with .ajax.

Categories