$_Post failing (Sending Ajax) - php

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

Related

jQuery+PHP. Request/Response

I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)

Bringing back several variables into ajax form POST success as jQuery variables

I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery

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

Parsing URL jQuery AJAX form

Basically i'm trying to send a video along with other info through jQuery to PHP to be written to a txt file to be read later.
There is a way of inputting a video url into this. I've got everything working except one thing.
If i put this through: http://www.youtube.com/watch?v=g1lBwbhlPtM
it works fine.
but this: http://www.youtube.com/watch?v=g1lBwbhlPtM&feature=feedu
doesn't.
I've done some tests and it's because when i send the second url through &feature=feedu gets read as a separate $_POST value.
This is the problem:
var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
because its reading like
var dataString = 'title='+title+'&content='+IMAGES, TEXT AND STUFF+'&feature=feedu OTHER IMAGES AND STUFF&date='+date+'&Submit=YES';
it's out of a textarea that could include images or text and stuff so im looking for something like htmlspecialchars() to sort out that & before sending it through ajax
Any ideas how to solve this?
EDIT:
Here's the full code that's the problem:
var title = $('input#title').val();
var content = $('textarea#content').val();
var date = $('input#date').val();
var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "./inc/php/file.php",
dataType: "json",
data: dataString,
success: function(data) {
if(data.error == true){
$('.errordiv').show().html(data.message);
}else{
$('.errordiv').show().html(data.message);
$(':input','#addstuff')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
},
error: function(data) {
$('.errordiv').html(data.message+' --- SCRIPT ERROR');
}
})
return false;
if content equals:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI&feature=feedu</vid>
<br>Text 3<br>
the content variable gets put through the ajax call as:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI
with an extra variable that is
&feature=feedu</vid>
<br>Text 3<br>
So how do u stop the ajax reading &feature as a separate $_POST variable?
Did you encodeURI() before pass the your video url?
If you need it in PHP then URLEncode
I used this bit of code in the php file
if(isset($_POST['feature'])){
$content=htmlspecialchars_decode(stripslashes(nl2br("<br />".$_POST['content'].'&feature='.$_POST['feature']."<br />")));
}
But it's not very dynamic as it only applies to youtube URLs
In JS do (before ajaxing)
dataString = encodeURI(dataString);
And then decode it on PHP
$dataString = urldecode($_POST['data']);
Or do:
$.ajax({
type: "POST",
url: "./inc/php/file.php",
dataType: "json",
data: {
'title': $('input#title').val(),
'content': $('textarea#content').val(),
'date': $('input#date').val(),
'Submit': 'Yes'
}
success: function(data) {
if(data.error == true){
$('.errordiv').show().html(data.message);
}else{
$('.errordiv').show().html(data.message);
$(':input','#addstuff')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
},
error: function(data) {
$('.errordiv').html(data.message+' --- SCRIPT ERROR');
}
})

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories