How to serialize a form using jquery .serialize() method? - php

My Form is:
<form class="something" id="main-form">
-----content----
My Jquery is:
$("form :input").change(function() {
var data = $('#main-form').serialize();
console.log(data);
$.ajax({
url:"<?php echo Yii::app()->createAbsoluteUrl('jobs/index'); ?>",
//dataType:"json",
type: "POST",
data: $('#main-form').serialize(),
success: function(data){
}
});
});
But the form is not serialized.The data field is coming empty.Please help.

From .serialize(); :
the element must have a name attribute.
So make sure you give all inputs a name='whatever'.
Here's a demo: http://jsfiddle.net/CWJDj/1/

See if this works any better:
var data = $('#main-form').serializeArray();

Try this:
var data = $("form#main-form").serialize();
That's Done.

Related

display the array values-ajax

I want to display the values in datatable. How to retrieve the object value in ajax success function..
AJAX
$(function(){
$(document).on("click", "#submits", function(e) {
e.preventDefault();
var password = $("#password").val();
alert(password);
$.ajax({
type: "POST",
url: "db/add.php",
data: "password="+password,
success: function(results){
alert( "Data Saved: " + results );
var obj = JSON.parse(results);
}
});
e.preventDefault();
});
});
</script>
Perhaps you can try this -
$("#submits").bind("click", function(e) {
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "db/add.php",
data : "password="+password,
success : function(results) {
alert("Data Saved: "+results);
var userInfo = JSON.parse(results);
//Output the data to an HTML element - example...
$(".user-name").html(userInfo.patient_name);
}else{
console.log('No user info found');
}
},
error : function(a,b,c) {
console.log('There was an error getting user info.');
}
});
});
//HTML element for data
<p class="user-name"></p>
I've added an HTML element you can simply output the data to. Not sure how you'd like the data to be output but this is simply an example.
Just some quick notes on your code from your original post -
You must set the dataType to json when working with/parsing json. See Documentation.
Once you assign your data to a variable, you need to access that data by declaring the variable and then the data name, such as obj.patient_name.
I've done the best I can to help.
Good luck.
Try this code :
$(results.patient_password).each(function(i,v){
console.log(v.id);
});
use data-type:json,
in your jquery

$_Post failing (Sending Ajax)

Can someone please show me the correct way I can add these two lines of code
data: {name: info, me: '<?php echo $me; ?>'},
data: dataString ,
So that I can send them in a $_POST to my action.php , I have tried several ways to do this but cannot get both of them successfully to be passed on to my action_comments.php I understand I'm missing something possible when using data: below or have not correctly formatted my code . I'm a total beginner with very little experience so sorry if I lack good practice but hopefully can be better from my debugging . Thanks to anyone who helps me get passed this .
Here is complete code to give overview what Im doing
<script type="text/javascript">
$(function() {
// call the submit button ref: name
$(".submit_button").click(function() {
declare textcontent
var textcontent = $("#content").val();
//dataString = 'content' globel var
var dataString = 'content='+ textcontent;
declare info
var info = $('#name').val();
// option no text inputted
if(textcontent=='')
{
// show message if no text
alert("Enter some text..");
$("#content").focus();
}
else
{
//display text animation loading
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
//var info equals the string
var info = $('#content').val();
//start ajax call
$.ajax({
type: "POST",
//path to my action.php
url: "actions/action_comment.php",
//Need to undestand how to correctly format these lines so
//they are both succesful when submitted to my action_comment.php
$me is declared (not-shown here it holds integer)
data: {name: info, me: '<?php echo $me; ?>'},
// pass the string from textarea to $_POST
data: dataString ,
// I can get one or the other to work but not both
cache: true,
// feed the success my data
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
I have my $_POST as follows in action_comment.php
echo $me = $_POST['me'];
//DATASTRING FROM TEXTAREA
echo $content= $_POST['content'];
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "actions/action_comment.php",
data: {name: info, me: '<?php echo $me; ?>',txt_data: dataString},
....
});
Cannot use data attribute multiple times in same ajax request. Within php file you can access like $_POST['txt_data'] to get textarea content and same way for other parameters;
define data attribute once and pass all the data like as shown above.
if you want to post whole form data you can use this way
var form = $('#my_form');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
..
..
});

Serialized AJAX $_POST is not empty but single $_REQUEST is empty

I'm making an AJAX Call like this:
$( "#submit_jobs_preview" ).click(function(e) {
var postData = $('#new_job_form').serialize();
var formURL = "ajax.xxx.php";
$.ajax({
type: 'POST',
url: formURL,
data: {submit_jobs_preview: postData },
success: function(data){
alert(data);
}
});
e.preventDefault(); //STOP default actio
});
In php i echo:
echo $_POST['submit_jobs_preview'];
This $_POST shows all values i put in my form correctly like this:
new_job_city=Berlin&new_job_name=Manager etc.
But if i want a single $_REQUEST from this $_POST like this:
if($_POST['submit_jobs_preview']){
echo $city = mysql_real_escape_string($_REQUEST['new_job_city']);
}
the alert is empty.
Why is that?
UPDATE
Full return of data:
XHR Loaded (autocomplete.php - 200 OK - 105.99994659423828ms - 354B) VM2106:3
new_job_city=Halle&new_job_job=Flugbegleiter&new_job_other_job=&job_zielgruppe=Auszubildende&new_job_phone=4921663965439&new_job_email=kleefeld%40dsc-medien.de&new_job_detailhead=F%C3%BCr+unser+zentrales+Marketing+mit+Sitz+in+der+Hauptverwaltung+in+der+City+von+D%C3%BCsseldorf+suchen+wir+zum+n%C3%A4chstm%C3%B6glichen+Termin+eine%2Fn&new_job_time=Vollzeit&teilzeit_std=&new_job_tasks=&new_job_profile=&new_job_advantage=&new_job_creatorId=1&new_job_creationDate=1390569795&new_job_scope=Airport+Service&new_job_niederlassung=7&new_job_active=0
You don't need to use {submit_jobs_preview: postData } if it is not necessary. I will give you another hint. Use following ajax;
$( "#submit_jobs_preview" ).click(function(e) {
var postData = $('#new_job_form').serialize();
var formURL = "ajax.xxx.php";
$.ajax({
type: 'POST',
url: formURL,
data: postData,
success: function(data){
alert(data);
}
});
e.preventDefault(); //STOP default actio
});
and on php side;
if($_POST['new_job_city']){
echo $city = mysql_real_escape_string($_REQUEST['new_job_city']);
}
In this case you can use field names directly.
Another hint:
You can put a hidden value on your form like,
<input type="hidden" name="submit_jobs_preview" value="true"/>
and js side will be same as above in my answer, and in php side you can check like;
if($_POST['submit_jobs_preview']){
echo $city = mysql_real_escape_string($_REQUEST['new_job_city']);
}
As you can see, you can send your post value as hidden field and make your check
$_POST['submit_jobs_preview'] holds a string and nothing else so you just can't access it that way. Use parse_str() to unserialize $_POST['submit_jobs_preview']. That way you can access its properties.
$_POST['submit_jobs_preview']['new_job_city']

ajax post data and insert to database

I am trying to insert comment using ajax. Everything works fine except the $_POST. It doesn't seem to post the data so the comment field in table is empty. Other things work fine, like inserting date. I only have problem with the ajax (no problems in php).
Anyway, here is my code:-
<head>
<script>
function su_post(id) {
$("#load_post").show(),
$("#post_submit").click(function() {
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
$.ajax({
type: "POST",
url: '/script/post.php',
data: "id=post_script" + id,
cache: false,
success: function(){
$("#load_post").fadeOut();
}
})});
};
</script>
</head>
<body>
<form id="form_post" method="post" action="javascript:su_post(1)">
<label for="c_post">Post your updates/status</label>
<input type="text" name="c_post" id="c_post" />
<br /><br /><input type="submit" id="post_submit" value="Post" />
</form>
</body>
edit: since you might not have understood me; there is a problem in obtaining the value you type in the input box and posting or sending the value to post.php. When I put data: {id: post_script + id, c_post: c_post}, it the code doesn't seem to load the php file at all. (gets stuck on posting -> http://prntscr.com/10dmjt)
Thank you in advance :)
The data property in your ajax() function needs to be of Object type. Like this:
data: { id: "post_script" + id }
You also had some syntax errors, your function should look like this:
function su_post(id) {
$("#load_post").show();
$("#post_submit").click(function() {
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
$.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() });
$.ajax({
type: "POST",
url: '/script/post.php',
data: { id: "post_script" + id },
cache: false,
success: function(){
$("#load_post").fadeOut();
}
});
});
}
You are calling the function javascript:su_post(1), so it would seem that your data field contains {id: "post_script1"} only. Where is your "comment" being passed to the AJAX? You don't do anything with the var dataString after assigning a value to it...
Maybe you intend to have something like this line:
data: "id=post_script" + id + dataString,
since, I think dataString contains &c_post=whatever the comment is after you did
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
I do wonder whether you need some additional quoting in the dataString as well... I don't believe the $(#c_post).val() function takes care of it, so I suspect you need an escape() somewhere - or does the ajax do it for you? I guess that's where #errieman's {} comes in handy... it turns the entire thing into an object and takes case of the escaping for you. That would make the line you need:
data: {id: post_script + id, c_post: c_post}
I doubt any of this turns out to be exactly right, as I'm having to guess what you are trying to do - but I do hope one of these will give you inspiration to solve your problem.
It seems to have worked when I took out the statement $("#post_submit").click(function() and put var c_post = $("#c_post").val();var dataString = '&c_post=' + c_post; on the top.Now my code looks like this :-
function su_post(id) {
var c_post = $("#c_post").val();
var dataString = '&c_post=' + c_post;
$("#load_post").show(),
$.ajax({
type: "POST",
url: '/script/post.php',
data: {c_post:c_post},
cache: false,
success: function(){
$("#load_post").fadeOut();
}
});
};

Pass array in jQuery ajax

My imaginery code:
$(document).ready(function() {
$("#sub").click(function() {
info['moto'] = $("#moto").val();
info['motox'] = $("#motox").val();
$.ajax({
type: "POST",
url: "index.php",
data: "arr="+info,
success: function(msg){
$('.answer').html(msg);
}
})
})
})
How could I make, that after receiving it in .php file I could use POST method like this: $_POST['moto'] and $_POST['motox'] or something like that? What should I change? Thanks.
Just:
data: info,
(And you need to initialize info as an object in the first place: var info = {})
Check out jQuery serialize(), it does all the work for you if you are working with form inputs.
I thinkyoushould go also the same way like jquery-ajax-data-array-from-php

Categories