PHP does not get values from Ajax - php

I have been searching through all the answers here but i can't get it to work.
I want to send two integer values from ajax to php.
Here is the ajax part:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var id_user=$(this).filter(':checked').val();
var stringname=$(this).attr('name');
var substr = stringname.split('_');
var id_paper=substr[1];
alert('User_id is: '+id_user +'. And paper_id is: '+id_paper);
$.ajax({
type: "POST",
url: "ajax/expositor.php",
data: {ID_ponencia: id_paper, ID_Participante: id_user},
//contentType: "application/json; charset=utf-8",//type of response
//contentType: "application/x-www-form-urlencoded;charset=utf-8",
//dataType: "json",
beforeSend:function(){
alert('This is AJAX. The following is about to be sent. paper:'+id_paper+' user: '+ id_user);
},
success:function(response){
var msj='#msj_'+id_paper;
$(msj).append(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
});
});
I have tried with the commented parts of dataType and contentType and it doesn't work either.
Here is the php code.
if(isset($_POST["ID_ponencia"]) && !empty($_POST['ID_ponencia']) && isset($_POST['ID_participante']) && !empty($_POST['ID_ponencia']))
{
$ID_participante=$_POST['ID_participante'];
$ID_ponencia=$_POST['ID_ponencia'];
echo ('<p style="color: green;">Success! ☺</p>');
}else{
//Output error
echo ('<p style="color: red;">error!</p>');
header('HTTP/1.1 500 There has been an error!');
exit();
}
The php is working fine, since i have tested an html form posting to that php script and i get the successfull message. However, from the ajax script i get the 500 error.
Any help will be really appreciated.

Your ajax is setting param of ID_Participante (capital P), but php is checking for ID_participante (lowercase p).
Also, you're checking if ID_ponencia is not empty twice...think you meant for the second one to be checking ID_participante.

Related

php ajax display data from database in multiple textboxes

Every one am new to php and ajax.
Am writing a code to fetch data from mysql database
and display them in textboxes but is not working.
Here is my code.
I need your help please.
Thanks in advance
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
}
});
});
<input type="text" id="input-box1">
<input type="text" id="input-box2">
<button type="button" id="btn_get">Click</button>
//get data from db here
$textbox1 = 'foo';
$textbox2 = 'deen';
echo $textbox1;
echo $textbox2;
Here are some approaches, maybe them can help you:
The first approach would be to check your console to make sure that the jQuery version allows you to use the $.ajax() resource. Some jQuery versions like the "slim" doesn't provide ajax calls.
Once you have checked that put the property error within your ajax call:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});
If you have a error response you will be able to identify it checking your browser's console tool (F12).
Check your /path/to/php/file to make sure that your file really exists.
Remember that the success callback gets your echo command as a string. So probably your return will be something like this:
foodeen
A good approach would be to return a json response:
$textbox1 = 'foo';
$textbox2 = 'deen';
echo json_encode(array($textbox1 ,"textBox1"));
Finally when your response is executed in the success callback you'll be able to convert it from plain string to a json format:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
var response = JSON.stringify(data);
$('#input-box1').val(response[0]);
$('#input-box2').val(response[1]);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});

Send variable to PHP using AJAX

I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().
In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!
Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});

jQuery AJAX can't work with JSON response

I have a JSON response from my php file like:
[
{"id":"1"},
{"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]
And try to fetch this response into a div after button was clicked, however firebug is telling me the message from the error-handler. I can't figure out the problem?
$('#loadarchive').click(function(){
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: {
action : 'getArchive'
},
success: function(results) {
var archiveelements = JSON.parse(results);
console.log(results);
$.each(archiveelements, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
});
I tried to run your Code and I get
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:
success: function (results) {
if (results["head"]["foo"] != 0) {
// do something
} else if (results["head"]["bar"] == 1) {
// do something
}
}
this works on my computer:
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
console.log(results);
$.each(results, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:
error: function(xhr, mssg) {
console.log(xhr, mssg);
}
First
your response is not correct,Correct response should look like this
[{
"id":"1",
"archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
...
}]
Second
You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.
Finally your success method should look like this:
success: function(results) {
$.each(results, function(ind,el){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
});
},
As you are saying message from error-handler is showing.
That means AJAX is never sent to server because of incorrect URL or any other reason.
Use Firebug in Firefox and see the error in console tab.
Also I see your code
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
var archiveelements = JSON.parse(results);
}
Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.
I was able to get it working and the problem was quite simple...
I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.
Thanks to all of you.

ajax post request to php without response (isset every time false)

I'm using jquery multiselect plugin and I want to perform an ajax request on a select/deselect event.
My problem: When I send the request to the php file, ISSET(VAR) returns every time false so that I can't pass variable to the php file.
But Firebug extension for Chrome/Firefox shows me that the POST value is set right POST -> "Response myvar" but GET is empty.
How do I pass the variable to the php file?
(I've searched arround the web but found nothing.)
My script, where this pointer is from the multiselect plugin and afterSelect returns if a object is selected
afterSelect: function()
{
this.qs1.cache();
this.qs2.cache();
count++;
var dataString = "count=" + count;
if ( count > 0 )
{
$.ajax
({
type: 'POST',
url: 'page-to-send-request.php',
data: dataString,
success: function()
{
$("#div-to-load").load("page.php #div-to-load").fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
},
The php page to load has for test only
if($_POST['count'])
{
$count = $_POST['count'];
echo "Count " .$count;
}
else{ echo "FALSE"; }
Expected result should be
Count 5
But real output is
FALSE
1st try
success: function(data)
{
console.log(data);
},
it should output "Count " .$count; if not
try to use
var dataString = {count: count};
and then you can use
$("#div-to-load").html(data).fadeIn('slow');
the reason of return false .. you used the .load to load the php page .. when you load it .. javascript know it as a separated page .. so $_POST['count'] is undefined in this case . and It will return False always
your success function should be like this
success: function(data)
{
$("#div-to-load").html(data).fadeIn('slow');
},

jQuery / Ajax to get html and save with php

I am trying to get a jQuery script to run behind the scenes with php. It basically will get the contents of a div with jQuery (works) then calls a script with ajax (works) but I need the ajax script that called the php to send the vars to php so I can save the conents.
Here is the code:
<script>
$( document ).ready(function() {
$( ".tweets" ).click(function() {
var htmlString = $( this ).html();
tweetUpdate(htmlString);
});
});
</script>
<script>
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
</script>
and my code for saveTweets.php
<?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];
?>
You have to give a name to the parameter, so that PHP can retrieve it. Change the $.ajax call to do:
data: { htmlString: htmlString },
Then in your PHP, you can reference $_POST['htmlString'] to get the parameter.
Correct your funcion.
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: "htmlString="+htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
then on saveTweets.php page write below line, you will get value on that page.
echo '<pre>';print_r($_REQUEST );echo '</pre>';
Using json is better for sending data:
data_htlm=[];
data_html.push({"htmlString": htmlString});
$.ajax(
{
type: "POST",
dataType: "json",
url: "saveTweets.php",
data: JSON.stringify(data_html),
success: function(html)
{
console.log(html);
}
});
now with php you can just do this:
echo $_POST['htmlString'];
You can use the $.post method to post to a PHP page and then retrieve the result from that page in a callback function.

Categories