Update form fields after form submitted - php

I have no problem with submitting form data through AJAX, and display all that data in a separate div.
But how do I update the form itself with some new info based on server response?
In my case I have:
a form with many inputs, including a group of checkboxes
data from form is collected (with JQuery serialize) and sent to php script through Ajax.
I need to set a specific color for text near a selected checkbox.
I need to set that color not on client side, but based on server side script.
Please explain the correct logical process when need to update a form based on initial form data.

Server side, you can send back a json encoded variable like so.
echo json_encode( array('text_color', 'green') );
Then, on the client side, you can access this variable in the callback function.
$.ajax({
url: 'ajax/test.html',
dataType: 'json',
data: $('yourform').serialize(),
success: function(data) {
var color = data.text_color;
$('yourElement').css('color', color);
}
});
Alternatively you could send back a class and add that class to the element.

If you are using jQuery, you would send the data via AJAX (post/get) and then you would get the response from server script in plain text / json / xml format (your choice). In this case, if you need to return only color code, you can use plain text format. When you get the response, you can manipulate the data.
$.post("test.php", $('#form').serialize(),
function(returned_data_from_server_script) {
$('some dom for color').css('color', returned_data_from_server_script);
});

Related

Send sql data from jQuery

I'm trying to retrieve database information based on what row a user clicks in a table, then later use that data in another page to display other database information. I don't know the best way to achieve it. Should I use Ajax and $.post() or are there other better/simpler ways?
I can retrieve the data from the table by
echo "<tr data-href=". $row["id"] . " class=\"tableclass\"><td>"
and then in jQuery
$(".tableclass").click(function () {
data = $(this).data("href");
alert(data);
The alert shows that I do get the database information (column ID). Now, I would like to post that information, preferably in a secure manner, to another PHP page where I can retrieve it and use it to get other information from the database.
How do I post it and then how should I retrieve it in the next php page?
Both works in same manner.
1. $.post is just a call with $.ajax(), just with the type set.
2. $.ajax() defaults to a GET
$.post( "/ajax", {"data" : json }) //is nothing but
$.ajax({
type: "POST",
url: "/ajax",
data: {"data": json}
});
If you want the data to be passed securely, use json or don't do thing if the request is not properly authenticated.
Typically, when you make an AJAX request, cookies are also sent: along with the request so you should just be able to use the same authentication method that you use for your regular requests with your AJAX requests.
Nothing much to do that, you need to use $_POST to access all the values in php in file save.php

Update MY SQL DB Table from jQuery

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

Two Forms In PHP

I have one php file that displays two forms. THe first Form displays data of customers from a table in mysql which also includes a checkbox. The second form contains data from another table and also includes a checkbox this form contains messages. I need to send messages selected with the checkbox to the list of customers selected in the first form.
Can I do that with pure php? or will I need to use javascript? please point me to a tutorial.
you need download Jquery library...and read what is ajax
get value
var value = $("#customer").val();
we get value for selector where id="customer"
get cheked
if($('#customer').is(":checked")) { } else { }
send data on server
var value = $("#customer").val();
$.ajax({
type: "POST",
url: "default.php",
data: "name="+value,
success: function(data){
alert('ok!') ;
}
});
we send data on server post method...we send variable value, value = value in value id="customer"
Good luck! Sorry for my English :)
The initial problem with what you are trying to accomplish is that you cannot natively submit two forms concurrently.
Is it absolutely necessary to have two separate forms? If so, you will need to implement something like this (written by Roatin Marth) in order to copy values over from one form to another when submitting:
function form2form(formA, formB) {
$(':input[name]', formA).each(function() {
$('[name=' + $(this).attr('name') +']', formB).val($(this).val())
})
}
Of course, if your business requirements do not require two separate forms, you can just place all the values into a single form and then process it with PHP. If you require validation of the form prior to submission, you will want to do that with Javascript first.
Once in PHP, you will get the values from the $_POST superglobal. You can then do what you need to do with it.
// With each customer checked, send checked messages
foreach($_POST['customers'] as $customer)
{
// With this customer, send all messages
foreach($_POST['messages'] as $message)
{
// Send $message here
}
}

Chrome Issue - AJAX Inserted File Input not uploading file

I have a form where a file input field is being dynamically inserted via AJAX. Essentially what I'm doing is displaying a form, the user picks which template they want, and I pull in some extra form fields depending on the template they chose. One of them has a file input. The problem is when I go to submit the form with the added file input, the PHP $_FILES array is giving me an error code of 4, meaning there wasn't a file uploaded. Does anyone know what I need to do to get these files uploading?
I'm guessing I have to do something on the JS side to re-evaluate which form fields I'm sending, but I haven't been able to find anything. (and yes I'm using proper enctype on the form.)
Update : This is only happening on Safari/Chrome. I read elsewhere that they think this is a security feature of webkit browsers. I don't know if there is a fix for this..
Thanks all
It's not clear if you are using a $.post or form.submit(). If you are using form.submit() there might be something else going wrong.
Otherwise, in order to send files to the server via AJAX you need to use the Form Data object.
This MDN Page Using FormDataObjects has good examples on how to use it. Note that if you use jQuery you need to set processData and contentType to false. See Below (taken from the MDN page).
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "stash.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
if you send the form via a form.submit() method, there should be no problem sending files. Are you trying to send your files via ajax ? if so you cant directy. use an iframe, flash or read the file datas with a FileReader and send raw datas in your ajax request.

How to perform GET requests on a JSON file in php?

I have a json file in the form of:
[{"label":"apple","desc":"fruit"},
{"label":"banana","desc":"fruit"},
{"label":"celery","desc":"vegetable"},
{"label":"plum","desc":"fruit"},
{"label":"","desc":"fruit"}]
How would I go about performing GET requests on this data? For example
http://www.mysite.com/data?desc=vegetable would display [{"label":"celery","desc":"vegetable"}] to the browser and
http://www.mysite.com/data?label=apple&desc=fruit would display
[{"label":"apple","desc":"fruit"}] to the browser
Here is a working example that I would like to emulate:
http://ws.geonames.org/searchJSON (returns nothing)
http://ws.geonames.org/searchJSON?featureClass=P&style=full&maxRows=12&name_startsWith=paris (returns matching cities.)
Jquery and php are the tools I'm using. I'm trying to set this up so I can use jQuery UI autocomplete with a remote JSONP datasource.
http://jqueryui.com/demos/autocomplete/#remote-jsonp
You'll probably have better results storing it in a database (e.g. MySQL). Then, you can query based on label and desc columns. Then, access the resulting row(s) with fetchObject and convert the object directly to JSON with json_encode.
You might need a few different versions of the query depending on what GET parameters they pass in.
$.ajax({
type: 'GET',
url: '/getFood/',
dataType: 'json',
success: function(data) {
// do whatever you want with the data here (like show in a div)
},
// replace with whatever you wanna send in the querystring
data: {'desc':'vegetable',},
});
On the server side check the 'desc' parameter in your GET request and send appropriate response.

Categories