no out while calling php function to read database - javascript

I am calling a php function from javascript by passing three arguments, on the other side php function inside the php file gets two values from database and prints all the value. for that I have written this code but this is not working, means this code prints nothing in the output so kindly help.
javascript code
jQuery.ajax(
{
type: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
php code
<?php
header('Content-Type: application/json');
if( $_POST['functionname'] == 'saveUser' ) {
include_once("dbConnection.inc");
$db = db_connect();
$newSql = "SELECT class_id, date FROM class_session WHERE class_id = (select max(class_id) from class_session)";
$result = mysql_query($newSql, $db);
$row = mysql_fetch_array($result);
$class_id = $row["calass_id"];
$date = $row["date"];
echo json_encode(Array(
'result' => $_POST['arguments'][0] .' '. $_POST['arguments'][1] .' '. $_POST['arguments'][2] .' '. $class_id .' '. $date
));
}
?>

The right property is method not type, see jQuery.ajax()
jQuery.ajax({
method: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});

Related

Call page PHP with Ajax

I have some difficulties to call PHP script with:
$("#tata").click(function(){
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
});
});
But my alert is empty... I am sure that the URL is correct, because if I add in my PHP file HTML code it appear on my alert!
I am sure that my PHP code works
PHP file:
echo "lalalala";
$getData = new mod_visitor();
$writeData = new writeData();
$urlPart1 = $_SERVER['HTTP_HOST'];
$urlPart2 = $_SERVER['REQUEST_URI'];
$pageEnCours = $urlPart1 .= $urlPart2;
$getData->get_ip();
$getData->LookupIP($GLOBALS['domain']);
$getData->ValidateIP($GLOBALS['domain']);
if ($GLOBALS['domain'] && $pageEnCours != preg_match("#localhost/joomla/$#", $pageEnCours)) {
$GLOBALS['domain'] = trim($GLOBALS['domain']);
if ($getData->ValidateIP($GLOBALS['domain'])) {
echo "cc";
$result = $getData->LookupIP($GLOBALS['domain']);
$writeData->write_domain($result);
} else {
echo "erreur";
$writeData->write_error();
};
} else {
echo "je ne rentre pas dans la boucle";
};
echo $pageEnCours;
echo $GLOBALS['domain'];
Parse the dataType to 'json'
Add dataType: 'json' to the javascript
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
dataType: 'json',
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
And echo back as JSON in your php
<?php
echo json_encode('lalala');
?>
If you want to return multiple items, you can return them as an array
<?php
$return = array(
'pageEnCours' => $urlPart1 . $urlPart2,
'domain' => $GLOBALS['domain']
);
echo json_encode($return);
?>
And get the items client-side
success: function(data) {
console.log(data.pageEnCours, data.domain);
}

JQuery Ajax goes in error

My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)

Posting data using Ajax

I've been trying to post data using AJAX that will update a field in my database however I am having trouble doing so. Everything seems like it should run fine and I get no errors in the console but I've no idea why my db won't update.
Can someone help me out here please?
AJAX:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
console.log("success");
}
});
}
Confirm.php:
$name=$_POST['var1'];
$age=$_POST['var2'];
if($name == "Stuart") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
else if($name == "Peter") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
The connection to my database is working as I have $connection setup and went to the page /ajax/confirm.php in my browser and I see "Connection successful" in my console as I defined if successful.
So I am unsure as to why this isn't updating?
Are my values not being posted correctly?
I'm new to AJAX so forgive me if this is something very simple!
Thanks
Try the following:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: arr,
success: function(data) {
console.log("success");
}
});
}
Instead of converting the object into json string send it as is.
Edit: Also remove dataType and probably contentType too. Your code is at risk of SQL Injection. Look into prepared statements and escaping mysql data.
Maybe this well help.
<script type="text/javascript">
function ajaxUpdate() {
var data = $('#formID').serialize();
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: data,
dataType: 'json',
encode : true,
success: function(data) {
if(data == "ok"){
console.log("success");
}else{
console.log(data);
}
}
});
}
</script>
confirm.php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
switch ($name) {
case 'Stuart':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
case 'Peter':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
default:
echo json_encode('Unknown name ');
}

Second Wordpress Ajax not firing

Hi there I am trying use some wordpress ajax my first ajax request works fine but the second one does not. Can some one please tell me why this is happening
Works fine:
PHP
//Add Students Details to DB
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$diet = $_POST['diet'];
$current_id = get_current_user_id();
global $wpdb;
$result = $wpdb->insert(
'wp_students',
array(
'ID' => NULL,
'first_name' => $fName,
'last_name' => $lName,
'birthdate' => $dob,
'gender' => $gender,
'dietary_requirements' => $diet,
'user_id' => $current_id
)
);
echo json_encode($result);
wp_die();
}
JS
var data_value = {
action: 'my_action',
fName: $(acc[i]).find('input.fName').val(),
lName: $(acc[i]).find('input.lName').val(),
dob: $(acc[i]).find('input.dob').val(),
gender: $(acc[i]).find('select.gender').val(),
diet: $(acc[i]).find('textarea.diet_req').val()
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: data_value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
Does not work:
PHP
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}
JS
var value = {
action: 'my_delete'
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
If you could help me would be great. Wordpress Ajax is not a straight forward as normal ajax.
Could it be that you just have a typo in your delete function?
'usesr_id' => get_current_user_id()
should probably be
'user_id' => get_current_user_id()
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}

Send message from php to ajax with 'echo json_encode' not working

I'm trying to send a message from php to ajax. I'm using echo json_encode to do it. When I do that, the website displays the arrays message. ({"foo":"content of foo"}). How can I get it to not display the message?
Also, the alerts from ajax don't get called.
Here's the code:
<?php
$myString = $_POST['data'];
if ($myString == "") {
echo json_encode(
array()
);
} else if ($myString == "foo" {
echo json_encode(
array(
'foo2' => 'this is the contents of foo'
)
);
} else if ($myString == "foo2") {
echo json_encode(
array(
'foo2' => 'this is the contents of foo2'
)
);
}
?>
<script>
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response) {
if (response.length == 0) {
alert("empty");
} else if (response.foo) {
alert("foo");
} else if (respons.foo2) {
alert("foo2");
}
}
});
</script>
How can I get the array to not display on the website? And why are the ajax if statements not getting called?
You need to set the HTTP header at the top of the script so you can return son:
header('Content-type: application/json');
Your script is a little confusing. You can't return json AND html/javascript.
It's one or the other.

Categories