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

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']

Related

PHP undefined Error while passing data from Ajax

Simply i want to pass Numeric id to Php page and Using $_POST['id'] i want use it, But Getting Undefined error. check screen shot https://imgur.com/a/M1v4mEX and check code below
===>edit.php
$('#update').click(function(){
var serialData = new FormData($("#regForm")[0]),
s = location.search.split('='),
searchId = s[s.length-1];
console.log(serialData);
console.log(searchId);
serialData.append('id',9);
$.ajax({
method:'POST',
url:'update.php',
dataType:'json',
data: {id:9},
success:function(jsonObj){
console.log(jsonObj);
}
});
});
==>update.php
<?php
if(isset($_POST['submit'])){
var_dump($_POST['id']);
exit();
}
?>
You forgot to change the id value to send in parameter to the dynamic value from the location.search
Also think about adding e.preventDefault(); because you work on form submission.
I think that serialData can be removed cause it doesn't have affect the current code logic
Here is the working script
<script>
$('#update').click(function(e) {
e.preventDefault();
var s = location.search.split('=');
var searchId = s[s.length-1];
// Verify the current ID passed on search parameter
console.log(searchId);
$.ajax({
method:'POST',
url:'update.php',
dataType:'json',
data: { 'id': searchId },
success:function(jsonObj){
console.log(jsonObj);
}
});
});
</script>

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

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.

$_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(),
..
..
});

How to get post values with ajax .post

I have two files filter.php and products.php included to index.php and I am using .post submit form without refreshing. I send data to products.php and return it back also i refresh my filter and there is my problem. When i try to var dump post data in filter.php it is empty
Here is my script
function ajaxFilter()
{
var str = jQuery( "form[name=\"filters\"]" ).serialize();
jQuery.post( "/", str )
.done(function( data ) {
var productList = jQuery(data).find(".list_product").html();
var filter = jQuery(data).find(".filters").html();
jQuery(".list_product").html(productList);
jQuery(".filters").html(filter);
});
}
Any ideas how to get POST?
I though about putting my post via script to hidden inputs and return them also as html
If it is bad idea or just wrong start.
try this:
var Data = $("form[name=\"filters\"]").serializeArray();
var URL = "products.php"; // whatever filepath where you send data
jQuery.ajax({
type: "POST",
url: URL,
processData: true,
data: Data,
dataType: "html",
success: function (productList) {
// filter your result whatever you return from products.php
jQuery(".list_product").html(productList);
},
error: function (x, y, z) {
var a = x.responseText;
jQuery(".list_product").html(a);
}
});
Use the full URL.
Provide the return values of .error() if you still have problems.

Php does not echo the data from a jQuery Ajax submit

I am fiddling with jQuery.ajax() and php, and I need some pointers in order to make everything work:
Here is the php code:
if(!empty($_POST["fname"])){
$firstName = $_POST["fname"];
echo $firstName."<br />";
}
if(!empty($_POST["id"])){
$age = $_POST["id"];
echo $age;
}
Here is the jQuery code:
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
});
var result;
console.log(result);
});
The values from jQuery exist, I get the alert, telling me the data has been submitted, firebug shows the Ajax post as working.
Why doesn't php gets my data and echo it?
You need to get the returned data by the php and do something with it. See the added line of code below.
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
alert("This is the data returned by the php script: " + result)
});
});
You have to use the success callback function to process the response from the POST to your Php page.
As stated in this thread
Your code could look similar to the following:
/* Send the data using post and put the results in a div */
$.ajax({
url: "test.php",
type: "post",
data: values,
success: function(returnval){
alert("success");
$("#result").html('submitted successfully:' + returnval);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
So, you have to somehow append the response from your Php to an HTML element like a DIV using jQuery
Hope this helps you
The correct way:
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script:
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

Categories