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.
Related
I have a PHP script that generates identical forms with different values (ie. lines of a database)
When one form is submitted, I want it to trigger an AJAX request that will update just that line of the database without reloading the page.
I have this AJAX script in my header:
function ajaxCall() {
$.ajax({
url:"database_quickupdate.php",
type: "POST",
success:function(result){
alert(result);
}
});
And obviously all forms have onsubmit="ajaxCall()" attributes set
But when I try to return the $_POST array from database_quickupdate.php, it comes back empty (meaning no data is passed to the script)
I tried various versions of serializing the data, including this here:
$.ajax({
type: "POST",
url: 'database_quickupdate.php',
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
but this didn't work either.
Of course I can assign unique ID-s to each of the forms, but then how can I tell ajaxCall in the header that I want the values from the form that_has_just_been_submitted?
It must be something very basic, still, I'm lost. I think I'm missing something on the jQuery side, but I'm not even sure about that.
Thanks for your help
onsubmit="ajaxCall()"
You're calling ajaxCall() by itself, so inside it this is the default object (window in a browser).
So then:
$(this).serialize()
You are trying to serialize the window and not the form.
You need to pass the form.
Don't use on... attributes. They come with a host of issues.
Bind your event handlers with JavaScript instead.
jQuery("form").on("submit", ajaxCall);
That will pass the form as the value of this.
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);
I'm developing a website/database solution which gives the administrator the option to sign into the webpage and perform actions on the database.
Currently they can add/delete/run pre-defined queries, however to 'edit' records in a table, I would like them to specify the primary key (ID) and then have ajax read in the values associated with that record and allow them to be changed.
What's the best way to go about this?
as stratton suggested you have to use jquery/html on frontend and php/mysql on backend that will have the logic to handle the data you send and retrieve result that will be sent back to the user.
ex.
have a form that will send the id to search:
<form>
<input type="text" id="data" name="data"/>
<--send button-->
</form>
I suggest then to use jquery to send the form via ajax like this:
$(sendbutton).click(function(e){
e.preventDefault();
s.ajax({
url: 'urlofyouphppage',
type: 'post',
data : {data: $("#data").val(), action: 'search_thing'}
success: function(data){
//the response from the php page to insert somewhere.
//beware that if you use json you will have to decode via parseJSON.
}
});
});
On you php side you will have to parse the post and then perform the action
<?php
if($_POST['action'] == 'search_thing'){
$id = $_POST['data'];
//query for searching
//format the result data
echo $result; //or json_encode($result); if you want to use json
}
?>
This way you can create multiple logic step by setting each time a different action, and the anwer can be full html code that contains the "next step" to perform.
make an ajax request (use jQuery) to a php script that reads from the database and outputs the return value in whatever format you prefer (html, json) then display it in the front end with javascript
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.
I am new to ajax and javascript.
I want to populate a entry form data into another form on the same page before it is submitted.
That means i want to display the name,gender etc of registration form in another form on the same page before it is submitted with click button event.
Please anybody post some examples.
(In response to your comment on the question above...)
Ah, that example is significantly more complex than previously implied. The target in that example isn't a form, it's an image. Do you have functionality in your server-side code already for generating the image?
Posting the AJAX to the server is very much the easy part in this case. Using jQuery for example, you can do something like this:
$.ajax({
type: 'POST',
url: 'somepage.php',
data: data,
success: function() {
alert('success!');
},
dataType: 'json'
});
The variable 'data' would be built from your form elements. Possibly something like this:
var data = '';
data = data + 'somevalue=' + $('#formElement').val();
data = data + 'anothervalue=' + $('#aDifferentElement').val();
// etc.
What the code essentially does is submit an HTTP POST to the supplied URL with the supplied data, and then run the supplied "success" function upon a successful result. You can also add an "error" function for an error result.
In your case, the result looks like it's an image. So you'd end up setting the src attribute on an img tag to the resulting image. Something like this:
$('#imageElement').attr('src', someString);
I'm not sure exactly how they're doing it in that example, but you can certainly look through the code and step through it in Firebug to see what you can find. The response appears to be the actual image, not a link to the image. But you can design yours either way.