jQuery create and post array to a PHP script - php

My experience with jQuery is very limited, and im on a very steep learning cure.
I have a dynamic form which is generated based on main and sub menu, placing marker points in each row which has an inputfield, I have managed to create a loop which looks for all the marker points and return the field_name and the field_value of any input field.
$('td[edit="1"]').each(function(i, el) {
field_name = $(el).attr('fieldname');
field_val = $('#'+field_name).val();
alert(field_name + " = " + field_val);
});
What I am having trouble with now, is converting this in to an array or JSON and pushing it to a PHP file which can then pick up the results.
Here is an example of how I currently submit a forms data to a PHP file, however is not dynamic as I have to specify which fields and values I want to send.
$.ajax({
type: "POST",
url: "form.php",
data: {
title : title,
age : age
}).done(function(data) {
results = $(data).find('data').html();
}).fail(function() {
alert("error");
}
);

If i have clearly understand your problem then You will have to use serialize method of jquery to send fields to php file. You can do like
data:$('form').serialize(),
It will send all the fields to php file.

As data you can user Jquery on the form to create an array of all the data:
https://api.jquery.com/serializeArray/
$.ajax({
type: "POST",
url: "form.php",
data: $('#idOfForm').serializeArray()
}).done(function(data) {
results = $(data).find('data').html();
}).fail(function() {
alert("error");
});

Related

Accessing dynamic div id inside ajax success function

I am using ajax to receive data from php server. The data is received in json format. To display this data I am creating dynamic divs with unique ids. I have appended the dynamic divs in an already structured html.
Now while spitting out the data using ("#"+dynamicid).html("data"), I am unable to get the desired output.
Here's the code:
$.ajax({
url: "loader.php",
dataType: "json",
success: function(data) {
var i = "kmapN"+data.id;
$('<div class="kmapName">').append($('<div id="'+ i +'">'))
.append($('</div></div>'))
.appendTo('.new_content');
$("#"+i).html(data.kname);
}
});
Here's the json output from the server:
{"id":2,"kname":"This is the title!"}
Edit1:
If I don't use the dynamic id, I am getting the result. The problem is therefore in generating and accessing the dynamic id.
Edit2:
The idea here is to prevent javascript and html injection attacksby using ("#" + id).html("output") function of jquery.
Try this one
$('.kmapName').append('--Output you want to be rendered ---');
your dataType must be defined.
create your dynamic div and append the variable to the main div
.ajax({
url: "loader.php",
dataType:'json',
success: function(data) {
var i = "kmapN"+data.id;
var new_div ='<div class="kmapName"><div id="'+ i +'">'+ data.kname +'</div></div>';
$(".new_content").append(new_div);
}
});

Make ajax call to send data onclick event in div

I have a div, which shows Rate me section. i.e. Five stars. When the user click on it, the rating value gets prompted.
<div class="rateit bigstars" id="rateit99" data-rateit-starwidth="32" data-rateit-starheight="32" onclick="alert($('#rateit99').rateit('value'))">
</div>
In here rather than an alert, I want to make an ajax call, which sends(post data) Rated value to data.php file.
How can it be done?
I don't understand what's on your HTML code, but i can understand what you are trying to achieve.
First clean your HTML code to make it easier to read for the purpose.
Here is an example of how you can receive the data and pass it using ajax
// Use the id of your trigger element
$('#submit').click(function() {
// Make your datastring (you can get other values with var a = $('#id').val();
var dataString = 'value1='+ value1 + '&value2=' + value2 ;
$.ajax({
type: "POST",
url: "data.php",
data: dataString,
cache: false,
success: function(data)
{
// handle the result
}
});
});

How to get text filed value in ajax?

I have a table with dynamic data from database, each row consist of a text filed and 2 link (accept or reject). then if user clicks on any of these link, the row will disappear and the rest of the rows are only visible in table.
I get ID of each row with ajax by clicking on each link, however I also need to get the text-field value.
how can I get it?
I need to have in ajax cause after getting value I need to insert in database with php+sql.
this is my ajax part for link:
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'Test.php',
data: 'ajax=1&accept=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
how can I include text filed value in it?
please comment me which I'm really in need to solve it,
Thanks
You can add manually your text to the GET request.
(snippet)
data: 'ajax=1&accept=' + parent.attr('id').replace('record-','') + '&text=VALUE',
Substitute text with the name you want to be received in PHP. Substitute VALUE with the text entered on the page that you want to grab - and don't forget to encode the value.
You will need the name of id of the textfield first. Then you could do something like this:
var textboxvalue = $('name or id of textfield').val();
Then you will need to append this value to your data string:
data: 'ajax=1&textvalue='+textboxvalue+'accept=' + parent.attr('id').replace('record-',''),
Then you can use $_GET['textvalue']; to get the value of textbox.
Use following and you're good to go. Also you had extra '});' at the end line of JS fragment. I had it removed. But make sure you give id to text fields in following pattern : text-fld-RECORD_ID where RECORD_ID is the ID of the record.
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
var id = parent.attr('id').replace('record-','');
//make sure that text field has ID in pattern 'text-fld-RECORD_ID'
var text_fld = $('#text-fld-'+id).val();
$.ajax({
type: 'post', // I suggest using post; get will be harmful in such occasions
url: 'Test.php',
data: {ajax:1,accept:id,text:text_fld},
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});

sending increment value from jquery to php file with for loop help

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);
}
});

JQuery to PHP function and back Ajaxed

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.

Categories