Im getting an empty success function parameter back (lewa).
But when I change 'lewa' to order (order.vnaam) it works. Could you point out what the problem is?
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'json-users.php',
dataType: 'json',
success: function(naam) {
$.each(naam, function(i, item) {
$('ul').append('<li>Voornaam: ' + item.voornaam + '<br>Achternaam: ' + item.achternaam + '</li>');
});
}
}); //end get data db
}); //end document ready function
function upload() {
var order = {
vnaam: $('.voornaam').val(),
anaam: $('.achternaam').val(),
};
$.ajax({
type: 'POST',
url: 'posttest.php',
/*dataType: 'json',*/
data: order,
success: function( lewa ) {
//When action is a success
$('ul').append('<li>Voornaam: ' + lewa.vnaam + '<br>Achternaam: ' + lewa.anaam + '</li>');
console.log(lewa);
console.log(order);
},
error: function() {
//When action is a failure
alert('error running function');
}
});
}
The following code is posttest.php
$voornaam = mysqli_real_escape_string($connect, $_POST["vnaam"]);
$achternaam = mysqli_real_escape_string($connect, $_POST["anaam"]);
$sql = "INSERT INTO users (voornaam, achternaam) VALUES ('".$voornaam."', '".$achternaam."')";
mysqli_query($connect, $sql);
The following code is json-users.php
$array_user = array();
while ( $data = mysqli_fetch_assoc($result) ) {
$array_user[] = $data;
}
echo json_encode($array_user);
Didnt return anything from posttest.php
Related
I am passing some json to a php file but the variables in the php remain empty im sure it is some small syntax error but i am unable to find what is causing this, any help will be greatly appreciated.
JAVASCRIPT
if(score >= 100)
{
console.log("HERE WE GO");
$.ajax({
type: "POST",
url: "FAKENAME.php",
data: { "data": "{ \"id\": " + id + ", \"quiz\": \"" + getDateTime() + "\"}" },
}).done(function (data) {
console.log(JSON.stringify(data) + "This is the data on .done");
//alert( data );
})
.fail(function () {
console.log("error");
//alert( "error" );
})
.always(function (data) {
console.log("finished");
console.log(JSON.stringify(data));
//alert( "finished" );
});
}
PHP
$data = json_decode($_POST['data']);
$sql = $conn->prepare("SELECT * FROM FAKEDATABASETABLENAME WHERE id = :id");//no error
$sql->bindParam(':id', $data->id);
//$sql->bindParam(':quiz', $data->quiz);
$sql->execute(); //syntax error
if(!empty($data->id))
{
$qry = $conn->prepare("UPDATE FAKEDATABASETABLENAME SET Quiz = '2018-06-27 14:44:49' WHERE id = 000007"); //no error and result
$qry->bindParam(':id', $data->id);
$qry->bindParam(':quiz', $data->quiz);
$qry->execute();
}
else
{
$mailto = "FAKEEMAIL.com" ; //Recipent of the email
$from = "From: PHP_DEBUG";
$subject = "PHP_DEBUG";
$data = json_decode($_POST['data']);
$content = "id is: " . $data->id. " plaese note. quiz is: " . $data->quiz. " please note.";
mail($mailto, $subject, $content, $from);
}
if(score >= 100)
{
var params = JSON.stringify({id: id, quiz: getDateTime()})
$.ajax({
type: "POST",
url: "FAKENAME.php",
dataType: "json",
data: {data: params}
}).done(function (data) {
console.log(JSON.stringify(data) + "This is the data on .done");
}).fail(function () {
console.log("error");
//alert( "error" );
}).always(function (data) {
console.log("finished");
console.log(JSON.stringify(data));
//alert( "finished" );
});
}
You can simplify your code like this
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$('#target').html('sending..');
$.ajax({
url: '/test/PersonSubmit',
type: 'post',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
$('#target').html(data.msg);
},
data: JSON.stringify(person)
});
Please add full url of your php page then you have to check print_r($_POST) like that
CodeIgniter : How to retrieve ajax jquery data passed through window.location.href in new controller ?
$(".x").on("click","a.p",function(){
productId = $(this).attr("productId");
alert("product ID : " + productId);
$.ajax({
url: 'home/allProductDetails',
type: 'POST',
data: {
'productId' : productId
},
success: function (dat) {
var result = eval('(' + dat + ')');
if (result.success == true)
{
if(result.data.length>0)
{//alert("Success");window.location.href = "newControllerName" + "?result=" + result.data;
}
}
on ajax success, the data is passed to the new controller using window.location.href
Try this,
Ajax:
$(".x").on("click","a.p",function(){
productId = $(this).attr("productId");
alert("product ID : " + productId);
$.ajax({
url: 'home/allProductDetails',
type: 'POST',
data: {
'productId' : productId
},
success: function (dat) {
var result = eval('(' + dat + ')');
if (result.success == true)
{
if(result.data.length>0)
{
//alert("Success");
window.location.href = "newControllerName/methodName/" + result.data;
}
}
});
});
Controller:
function methodName($data)
{
//here you can access `$data` variable
print_r($data);
}
This can work try it...
I want to send a form with JQuery $.ajax, but I have a problem. It's seems that PHP cannot get serialized $_POST. It's weird because the variable elementiPost is not empty, indeed if I do console.log(parametriPost) the console show me the right content.
The weirdest thing is that PHP get parameters that I append manually to parametriPost ($_POST['data_r']) but not those of $(this).serialize()!
If I put manually a number in $ore it works fine, so the problem is not the query.
Thank you.
Here's the code:
JQuery
$('form').submit(function(e) {
e.preventDefault();
var formId = $(this).attr('id');
var data = area_get_row_date(formId);
var parametriPost = $(this).serialize() + '&data_r=' + data;
$.ajax({
url: 'insert_db.php',
method: 'POST',
async: false,
data: parametriPost,
success: function() {
// Success code
},
error: function(xhr, status, error) {
alert("Errore!");
}
});
});
PHP (insert_db.php)
$data = str_replace('_', '.', $_POST['data_r']);
$ore = $_POST['orelavorateore_2_07_2015'];
$sql = "INSERT INTO ore_lav
VALUES (NULL, 134, 4,STR_TO_DATE('" . $data . "', '%d.%m.%Y'), " . $ore . ", 1, 1)";
$results = api_store_result(api_mysql_query($sql));
This is what parametriPost contains:
lavorati_prenotati=L&periodointegrazione_3_07_2015=on&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=a&extra_field1_orelavoratechf_3_07_2015=&extra_field1_orelavorateore_3_07_2015=&extra_field2_orelavoratechf_3_07_2015=&extra_field2_orelavorateore_3_07_2015=&orenonlavoratechf_3_07_2015=&orenonlavorateore_3_07_2015=&orenonlavoratetipologia_3_07_2015=L&extra_field1_orenonlavoratechf_3_07_2015=&extra_field1_orenonlavorateore_3_07_2015=&extra_field1_orenonlavoratetipologia_3_07_2015=L&extra_field2_orenonlavoratechf_3_07_2015=&extra_field2_orenonlavorateore_3_07_2015=&extra_field2_orenonlavoratetipologia_3_07_2015=L&orenonpagateore_3_07_2015=&orenonpagatetipologia_3_07_2015=L&extra_field1_orenonpagateore_3_07_2015=&extra_field1_orenonpagatetipologia_3_07_2015=L&extra_field2_orenonpagateore_3_07_2015=&extra_field2_orenonpagatetipologia_3_07_2015=L&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=&data_r=3_07_2015
You can use this snippet to convert your form data into JSON format :
$.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;
};
$("form").submit(function( event ) {
event.preventDefault();
//convert form data to JSON
var params = $(this).serializeObject();
//add a 'data_r' field with some data to our JSON
params.data_r = 'sample data';
$.ajax({
url: 'app.php',
type: 'POST',
data: JSON.stringify(params),
})
.done(function(data) {
console.log(data);
});
});
and on the PHP side :
<?php
$data = json_decode(file_get_contents('php://input'), false);
print_r($data->data_r);
?>
Now $data is an object and you can access to a specific field :
$data->data_r
Racking my brains for hours with this. I have the following PHP AJAX script:
<script type="text/javascript">
$(document).ready(function(){
$("#submitValue").click( function(){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
success: function(data){
$('#results').html('Success').delay(1000).fadeOut();
}
});
});
});
</script>
I am trying to get the message 'Success' to populate this span element;
<span id="results"></span>
But just can't seem to get it to work.
The PHP is as follows (the table is updated just fine);
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
}
Anyone be of assistance please?
dataType: "dataString"
Please comment this part and it will work.
if($_POST['acctDB'] == 'profile') {
$uemail = $DB->real_escape_string($_POST['uemail']);
$uage = $DB->real_escape_string($_POST['uage']);
$city = $DB->real_escape_string($_POST['city']);
$urname = $DB->real_escape_string($_POST['urname']);
$uname = $DB->real_escape_string($_POST['uname']);
$uID = $DB->real_escape_string($_POST['uID']);
mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
echo 'yes';
}
// add echo 'yes'; at php submit page.
change the script as follows
$.ajax({
type: "POST",
url:"acctUpdate.php",
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
// dataType: "dataString",
dataType : "text",
success: function(data){
$('#results').html(data).delay(1000).fadeOut();
return false;
}
});
return false;
In php file change this
$qry = mysqli_query($DB, 'UPDATE profile SET memEmail="'.$uemail.'", memAge="'.$uage.'", memCity="'.$city.'", memRealName="'.$urname.'" WHERE memID="'.$uID.'" AND memUname="'.$uname.'" ') or die(mysqli_error($DB));
if($qry)
echo "Success";
}
When you make an ajax call and you pass the values to a php file, you will also need to return the response.
So at the end of your query if everything is completed successful you will do something like this:
return Response::json(array(
'success' => true,
'message' => trans('admin.update_success'),
), 200);
And your ajax cal looks something like this:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
dataType: "dataString",
})
.done(function(response) {
alert(response.message)
})
.fail(function(response) {
if (response.status == 400) {
var output = '<ul>';
var errors = $.parseJSON(response.responseText).errors;
$.each(errors, function(id, message) {
output += '<li>' + message[0] + '</li>'
});
output += '</ul>'
alert(output)
} else {
alert('UnknownError');
}
})
e.preventDefault();
})
So to recap:
You make the ajax call
The php file will process the data
You pass the response back to the 'done function)
And hier you can make anything you want with your response.
I have just as example inserted an alert message
Hope this helps.
Sorry but the code I have provider for you is for a Laravel framework and I suppose you are not using it. So you don't have the 'Respone::' class.
In the php file:
//if the query has success
$return = array();
$return['responseCode'] = 1;
$return['responseHTML'] = 'Success'
echo json_encode( $return );
And the ajax call:
$("#submitValue").click(function(e){
var uemail=$("#uemail").val();
var uage=$("#uage").val();
var city=$("#city").val();
var urname=$("#urname").val();
$.ajax({
url: 'acctUpdate.php',
type: 'POST',
dataType: 'json',
data: "uemail=" + uemail +"&uage="+ uage +"&city="+ city +"&urname="+urname +"&uname="+"<?php echo $memName; ?>" +"&uID="+"<?php echo $memID; ?>" +"&acctDB="+"profile" ,
})
.done(function(response) {
if( response.responseCode == 0 ) {
//alert(respomse.responseHTML)
$('#results').html(response.responseHTML);
} else if( response.responseCode == 1 ) {
//alert(res.responseHTML)
$('#results').html(response.responseHTML);
}
})
e.preventDefault();
})
So I don't use the response anymore but I will just return an array with the response.
I am writing an app (not web app) for mobile devices using icenium which uses javascript etc rather than its native language.
The app displays rows from a data base, displaying events. The user then clicks on an event which displays more information on the event, however I am having trouble calling the ajax from a js function as below:
function showSingle(itemId){
//document.write(itemId);
$('#output').fadeOut();
$('#single').fadeIn("fast");
$.ajax({
url: 'http://dev.123456789.co.uk/getSingle.php',
dataType: 'jsonp',
data: { dbId: itemId },
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
var linkedPageSingle = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
$('#single').append(linkedPageSingle);
// pageId = $('#pageid').html();
$('#single').text('debugdebug.');
},
error: function(){
$('#single').text('There was an error loading the data.');
}
});
}
This does not return any data, it doesn't even return $('#single').text('debugdebug.'); so there must be a problem with the ajax call? Also
error: function(){
$('#single').text('There was an error loading the data.');
}
Is not outputted. Can you spot an error in this? The call to the function is here:
var linkedPage = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
Which is in a document.ready section of the page, inside an ajax method (which works).
getSingle.php:
<?php
/*
* Script to connect to database and pull out information for app!
*/
include 'connect.php';
$dbId = $_POST['dbId'];
$query = mysql_query("SELECT * FROM calTest where `id`='$dbId'");
$records = array();
while($row = mysql_fetch_assoc($query)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
Can't see where I have gone wrong, Thanks!
I think the problem is with Posting of data
$dbId = $_POST['dbId'];
echo $_GET['jsoncallback'];
you are using the get or post method together
You set the callback to jsoncallback so you need to add that function to parse item:
function showSingle(itemId){
//document.write(itemId);
//$('#output').fadeOut();
//$('#single').fadeIn("fast");
$.ajax({
url: 'http://dev.thedesignworks.co.uk/getSingle.php',
dataType: 'jsonp',
data: { dbId: itemId },
jsonp: 'jsoncallback',
timeout: 5000
});
}
function jsoncallback(data, status) {
var linkedPageSingle;
$.each(data, function(i, item) {
linkedPageSingle = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
$('#single').append(linkedPageSingle);
// pageId = $('#pageid').html();
});
$('#single').text('debugdebug.');
}
Try this
function showSingle(itemId){
//document.write(itemId);
$('#output').fadeOut();
$('#single').fadeIn("fast");
$.ajax({
url: 'http://dev.thedesignworks.co.uk/getSingle.php',
dataType: 'jsonp',
data: { dbId: itemId },
timeout: 5000,
success: function(data, status){
alert(data)
if (data.length > 0) {
var linkedPageSingle = '<h2>'+item.eventName+'</h2>'
+ '<p>Description: '+item.description+'</p><p>Type: '
+ item.type+'</p><p id="pageid">'+item.id+'</p>';
$('#single').append(linkedPageSingle);
// pageId = $('#pageid').html();
$('#single').text('debugdebug.');
}
},
error: function(){
$('#single').text('There was an error loading the data.');
}
});
}
The php page will be
<?php
/*
* Script to connect to database and pull out information for app!
*/
include 'connect.php';
$dbId = $_POST['dbId'];
$query = mysql_query("SELECT * FROM calTest where `id`='$dbId'");
$records = array();
while($row = mysql_fetch_assoc($query)) {
$records[] = $row;
}
if (count($records) > 0)
echo json_encode($records);
?>