PHP: Problem submitting form in AJAX/JSON? - php

currently I have following code:
home.php
<form name='myformname' id='myformid'>
<input type='text' name='mytext1' value='abc'>
<input type='text' name='mytext2' value='123'>
<input type='submit' value='Submit'>
</form>
<div id='textone'></div><div id='texttwo'></div>
_home.php
$arr = array( 'textone' => $_POST['mytext1'], 'texttwo' => $_POST['mytext2'] );
echo json_encode( $arr );
ajax.js
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
data: $('#myformid').serialize(),
success: function( data ) {
// TODO: write code here to get json data and load DIVs instead of alert
alert(data);
}
});
return false;
});
Output on submit:
{"textone":"abc","texttwo":"123"}
Question
I want to load mytext1 value in textone DIV and mytext2 value in texttwo DIV using json data in _home.php
Hint: I am using this answer to do the same task on link click event. But how to do this on form submission ?
Thanks

You just wanna parse that JSON and set the divs to the values it contains right?
var divs = JSON.parse(data);
for (var div in divs) {
document.getElementById(div).innerHTML = divs[div];
}
(Previous poster's syntax is probably more like what you're after, and maybe is more cross-browser compatible, but doesn't include the JSON parsing.)
Since JSON is just a subset of JavaScript, you can just eval() it. JSON.parse() basically does that, but gives you assurances that if 'data' contains some nasty code instead of a simple object, it won't be evaluated.

In the success function
for (prop in data){
$('#' + prop).html(data[prop]);
}

Here is my complete JS solution:
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
dataType: 'json',
data: $('#myformid').serialize(),
success: function( data ) {
for(var id in data) {
//jQuery('#' + id).html(data[id]); // This will also work
document.getElementById(id).innerHTML = data[id];
}
}
});
return false;
});

Related

AJAX - PHP save data repeated

I've a form with data repeated:
<form action="" method="post" id="myForm">
<?php foreach ($array as $value) { ?>
<input type="text" name="myInput[]" id="myInput" value="<?php $value->data1 ?>"/>
<textarea name="myTextArea[]" id="myTextArea"><?php $value->data2 ?></textarea>
<?php } ?>
save
</form>
I try to save values with ajax with this script:
jQuery(function(){
jQuery("#submit").click(function(e){
e.preventDefault();
var formData = {
'myInput' : jQuery('input[name=myInput]').val(),
'myTextArea' : jQuery("textarea#myTextArea").val()
};
jQuery.ajax({
url : 'someUrl',
type : 'POST',
data : formData,
dataType: 'json',
encode : true,
success: function(response){
if (response.success==true) {
}
else {
}
}
});
});
});
When data is not repeated (no array values) i've no problem, but in this case something goes wrong. Anyone could help me?
As suggested, use
data: $(this).serialize()
in your jQuery submit function. Leave the square brackets in the input names intact. In your PHP, you will be able to access your data like this:
$myInputs = $_POST['myInput'];
$myTextAreas = $_POST['myTextArea'];
Both variables will be arrays of values retrieved from the form. More info on PHP arrays is available here.
EDIT: If you need the value of $myInputs as a string separated by commas (e.g., "value1, value2, value3..." instead of array with "value1" etc.), you could do the following right after:
$myInputs = implode(', ', $myInputs); // this will convert the array to a string
Try this jQuery code :
jQuery(function(){
jQuery("#submit").click(function(e){
e.preventDefault();
var formData = $("#myForm").serialize();
jQuery.ajax({
url : 'someUrl',
type : 'POST',
data : formData,
dataType: 'json',
encode : true,
success: function(response){
if (response.success==true) {
}
else {
}
}
});
});
});
Please refer this answer to add multiple textbox values in database : Adding multiple textbox entry to a mysql database

jQuery AJAX refresh page content after success

I'm updating my database with jQuery .click() and then calling my AJAX; my question is once the SQL has ran what is the best way to refresh the content on the page so I'll be able to do the previous action again, currently I'm using window.location.reload(true); but I don't like that method because I don't want to have the page reloading all I want is for the content on the element I used to update it with to be to match the database field after the AJAX was successful
Here's my jQuery:
$(document).ready(function(){
$("span[class*='star']").click(function(){
var data = $(this).data('object');
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success: function(data){
if(data == false) {
window.location.reload(true);
} else {
window.location.reload(true);
}
}
});
console.log(data.art_featured);
});
});
PHP:
<section class="row">
<?php
$sql_categories = "SELECT art_id, art_featured FROM app_articles"
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row">
<div class="column one">
<?php if($row['art_featured']==0){
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star"></span>
<?php
} else if($row['art_featured']==1) {
?>
<span data-object='{"art_id":"<?php echo $row['art_id'];?>", "art_featured":"<?php echo $row['art_featured'];?>"}' class="icon-small star-color"></span>
<?php
}
?>
</div>
</div>
<?php
}
} else {
echo "FAIL";
}
?>
</section>
EDIT:
I need to update the class .star or .star-color with art_featured depending on what the value of a art_featured is at the time, basically where ever I'm echoing out art_featured I need that to reload once the Ajax is successful.
EDIT:
$("span[class*='star']").click(function(){
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
success:function(art_featured){
//remember $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object')),{
art_featured: art_featured
});
}
});
console.log(data.art_featured);
});
If you can just return art_featured after the MySQL database success, it'll send it back to the ajax success function. here, we can manipulate data, however, first we should store reference to the element that was clicked on.
var data = $(this).data('object');
var $this = $(this); //add this line right after the above
Now in our success function, instead of using data just use art_featured because that's all we are returning. Now we can update the existing data object on the target.
success:function(art_featured){
//remmeber $this = $(this) from earlier? we leverage it here
$this.data('object', $.extend($this.data('object'),{
art_featured: art_featured
}));
}
The above will extend the existing data object, allowing key:value pairs to be redefined based on the object we are extending.
You should find this working as intended.
I don't fully understand your question so let's assume the content you want to change is a div with class div, and you want to replace the content with the content just sent i.e. the data. Then you would need to return the data (probably using JSON would be easiest), then your call would be
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
for(n in data){
$('.div').append('<p>'+data[n]+'</p>');
}
}
});
Note addition of dataType return as being json, then iterating over the json data by for n in data, then using n to call the data from the array. So if the third item was name then you could do something like
$('.div').append('<p>Name is '+data[3]+'</p>');
You will have to return the data from the PHP form by json encoding it which can be done with the json_encode php function. If it's cross domain you'll have to use jsonp
EDIT:
If you already know the data you want to replace before you send the form (i.e. don't need a response) then you can just put those variables into the success call back. This will wait for the ajax to return successfully, then update your div.
So you could have this
var updateText = yourDataFromForm
$.ajax({
type: "POST",
data: {art_id:data.art_id,art_featured:data.art_featured},
url: "ajax-feature.php",
dataType:'json',
success: function(data){
$('.div').append('<p>'+updateText+'</p>');
}
});

How to return PHP variables on success AJAX/jQuery POST

How do I use AJAX to return a variable in PHP? I am currently using echo in my controller to display a price on dropdown .change in a div called price.
However I have a hidden field which I need to return the row id to on change. How do I assign the return var in jQuery so that I can echo it in my hidden field?
jQuery
$(document).ready(function() {
$('#pricingEngine').change(function() {
var query = $("#pricingEngine").serialize();
$('#price').fadeOut(500).addClass('ajax-loading');
$.ajax({
type: "POST",
url: "store/PricingEngine",
data: query,
success: function(data)
{
$('#price').removeClass('ajax-loading').html('$' + data).fadeIn(500);
}
});
return false;
});
});
Controller
function PricingEngine()
{
//print_r($_POST);
$this->load->model('M_Pricing');
$post_options = array(
'X_SIZE' => $this->input->post('X_SIZE'),
'X_PAPER' => $this->input->post('X_PAPER'),
'X_COLOR' => $this->input->post('X_COLOR'),
'X_QTY' => $this->input->post('X_QTY'),
'O_RC' => $this->input->post('O_RC')
);
$data = $this->M_Pricing->ajax_price_engine($post_options);
foreach($data as $pData) {
echo number_format($pData->F_PRICE / 1000,2);
return $ProductById = $pData->businesscards_id;
}
}
View
Here is my hidden field I want to pass the VAR to every-time the form is changed.
" />
Thanks for the help!
Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr). This will return a JSON string.
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
{"stack":"overflow","key":"value"}
Now in your jQuery, you'll have to tell your $.ajax call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'. Now your returned values in the success function will be a normal JavaScript object.
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value
}
});
echo json_encode($RESPONDE);
exit();
The exit is not to display other things except answer. RESPONDE is good to be array or object.
You can access it at
success: function(data)
{ data }
data is the responde array or whatever you echo..
For example...
echo json_encode(array('some_key'=>'yesss')); exit();
at jquery
success: function(data){ alert(data.some_key); }
if u are returning only single value from php respone to ajax then u can set it hidden feild using val method
$("#hidden_fld").val(return_val);

Submitting form with jQuery

Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.

How to submit a form with AJAX/JSON?

Currently my AJAX is working like this:
index.php
<a href='one.php' class='ajax'>One</a>
<div id="workspace">workspace</div>
one.php
$arr = array ( "workspace" => "One" );
echo json_encode( $arr );
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
jQuery('#' + id).html(snippets[id]);
}
});
});
});
Above code is working perfectly. When I click link 'One' then one.php is executed and String "One" is loaded into workspace DIV.
Question:
Now I want to submit a form with AJAX. For example I have a form in index.php like this.
<form id='myForm' action='one.php' method='post'>
<input type='text' name='myText'>
<input type='submit' name='myButton' value='Submit'>
</form>
When I submit the form then one.php should print the textbox value in workspace DIV.
$arr = array ( "workspace" => $_POST['myText'] );
echo json_encode( $arr );
How to code js to submit the form with AJAX/JSON.
Thanks
Here is my complete solution:
jQuery('#myForm').live('submit',function(event) {
$.ajax({
url: 'one.php',
type: 'POST',
dataType: 'json',
data: $('#myForm').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
Submitting the form is easy:
$j('#myForm').submit();
However that will post back the entire page.
A post via an Ajax call is easy too:
$j.ajax({
type: 'POST',
url: 'one.php',
data: {
myText: $j('#myText').val(),
myButton: $j('#myButton').val()
},
success: function(response, textStatus, XMLHttpRequest) {
$j('div.ajax').html(response);
}
});
If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:
$j('div.ajax').load('one.php', data);
Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.
However it should be a fairly simple loop.
Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as
$('#myForm').ajaxSubmit();
You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.
You can submit the form with jQuery's $.ajax method like this:
$.ajax({
url: 'one.php',
type: 'POST',
data: $('#myForm').serialize(),
success:function(data){
alert(data);
}
});

Categories