I'm trying to pass two number and check if their product is true or false. I can see call made successfully in network tab and when i click that link, output is correct to. But i m stuck at retrieving that result. It doesn't show anything in data1.
function call(){
console.log(fun);
$.ajax({
url: "http://localhost/mt2/checkanswer.php",
dataType: "jsonp",
type: "POST",
//window.alert("what");
data: {
num1:2,
num2:2,
answer:5
},
success: function( data1 ) {
console.log(data1);
$( "#timeDiv" ).html( "<strong>" + data1 + "</strong><br>");
}
<?php
// get two numbers and the answer (their product) and return true or false if the answer is correct or not.
// using this as an api call, return json data
// calling <your host>/checkanswer.php?num1=4&num2=5&answer=20 will return true
// calling <your host>/checkanswer.php?num1=4&num2=5&answer=21 will return false
if(isset($_GET['num1']) && isset($_GET['num2']) && isset($_GET['answer']) && is_numeric($_GET['num1']) && is_numeric($_GET['num2']) && is_numeric($_GET['answer'])) {
$product = $_GET["num1"] * $_GET["num2"];
if ($product === intval($_GET['answer'])) {
$result = true;
} else {
$result = false;
}
header('Content-type: application/json');
echo json_encode($result);
}
?>
https://drive.google.com/open?id=1ocF344ZxG3HXJR0WQha1kOoVM9bCepnI "console"
The issue is your Javascript is submitting the data via JS as a post request and your PHP is looking for a get request.
if(isset($_GET['num1']) && isset($_GET['num2']) && isset($_GET['answer']) && is_numeric($_GET['num1']) && is_numeric($_GET['num2']) && is_numeric($_GET['answer'])) {
..
}
So either change method: 'POST' to method: 'GET' or change $_GET[..] to $_POST[..].
Also that's one wild if statement. You could break it up so it's not so long and isn't as hard to read. This also allows you to add some additional information based on where your code 'fails.'
if ( isset($_GET['num1'], $_GET['num2'], $_GET['answer']) ) {
if ( !is_numeric([$_GET['num1'], $_GET['num2'], $_GET['answer']]) ) {
// Our numbers aren't numeric!
$message = 'Not all variables are numeric';
$result = false;
} else {
$message = 'We did it!';
$result = $_GET['num1'] + $_GET['num2'] == $_GET['answer'];
}
} else {
// We didn't have all of our request params passed!
$message = 'We didn\'t have all our variables';
$result = false;
}
header('Content-type: application/json');
echo json_encode([ 'message' => $message, 'result' => $result]);
Edit
Based on epascarello's comment remove dataType: 'jsonp'.
Related
I'm trying to learn JavaScript to code for Cordova.
I read many tutorials, but none of them helped me with the folowing problem.
My cordova app is for testing very simple. Just a textbox and 2 buttons. Both Buttons calls a PHP script on my server. One button sends data to the PHP script to insert the value of the textfield in a MySQL database, the second button calls the same script and should write the values of the database to my cordova app.
Here is my
<?PHP
$response = array();
require_once __DIR__ . '/db_config.php';
$db_link = mysqli_connect (
DB_SERVER,
DB_USER,
DB_PASSWORD,
DB_DATABASE
);
mysqli_set_charset($db_link, 'utf8');
if (!$db_link)
{
die ('keine Verbindung '.mysqli_error());
}
if(isset($_POST['action']) && $_POST['action'] == 'insert'){
$name = $_POST['name'];
$sql = "INSERT INTO test.testTable (name) VALUES ('$name')";
$db_erg = mysqli_query($db_link, $sql);
if (!$db_erg){
echo "error";
}else{
echo "ok";
}
}
if(isset($_POST['action']) && $_POST['action']=='read'){
$sql = "SELECT * FROM testTable";
$db_erg = mysqli_query( $db_link, $sql );
if (!$db_erg )
{
$response["success"] = 0;
$response["message"] = "Oops!";
echo json_encode($response);
die('Ungültige Abfrage: ' . mysqli_error());
}
while ($zeile = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
{
//$response["success"] = $zeile['pid'];
//$response["message"] = $zeile['name'];
$response[]=$zeile;
}
echo json_encode($response);
mysqli_free_result( $db_erg );
}
?>
and here are my 2 functions in the cordova app:
function getNameFromServer() {
var url = "appcon.php";
var action = 'read';
$.getJSON(url, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
function sendNameToServer() {
console.log("sendNameToServer aufgerufen");
var url2send = "appcon.php";
var name = $("#Name").val()
var dataString = name;
console.log(dataString);
if ($.trim(name).length>0) {
$.ajax({
type: "POST",
url: url2send,
data: { action: 'insert', name: dataString },
crossDomain: true,
cache: false,
beforeSend: function () {
console.log("sendNameToServer beforeSend wurde aufgerufen");
},
success: function (data) {
if (data == "ok") {
alert("Daten eingefuegt");
}
if (data == "error") {
alert("Da ging was schief");
}
}
});
}
}
My Questions/Problems:
The sendNameToServer funtion works in that case, that the data will be inserted in my Database. But I never get the alert (the success: never called).
How can I pass "action = read" to the PHP script in the getNameFromServer() function?
The third question is a bit off topic, but is this art of code "save" or is it simple to manipulate the data between the cordova app and the server? What's the better way or how can I encrypt the transmission?
Here is one part answer to your question.
$.getJSON has a second optional parameter data that can be an object of information you want to pass to your script.
function getNameFromServer() {
$.getJSON("appcon.php", { action: 'read' }, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
Edit: Since you are using $.getJSON(), the request method is a GET, which means you have to use $_GET in your third if statement in your PHP script.
if(isset($_GET['action']) && $_GET['action'] == 'read'){
I'm using json to post data to controller but i can't do some effects if data is inserted to database successfully,
This if statement does not work in this javascript code ?
I mean .like-btn .html() does not work but data inserted in database ?
My experience in Javascript between 0 and 10 :D
Using Codeigniter 3.0.3
Here's my javascript
<script type="text/javascript">
$(document).ready(function() {
$(".like-btn").click(function(event) {
var liker_id = "<?php echo $this->session->userdata('id'); ?>";
var post_id = $(this).attr('post-id');
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('home/AddLike'); ?>",
dataType: 'json',
data: {liker_id: liker_id, post_id: post_id},
success: function(res) {
if (res)
{
$('.like-btn[post-id = '+post_id+']').html('<span class="fa fa-check"></span> Liked');
}
}
});
});
});
</script>
Here's my controller
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
}
And here's my model method
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
return true;
}
}
Just change below on your model:
change return to echo
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
echo true;
}
}
You should debug your code of ajax response. And you should check whether you are getting any response in res variable.
Important
1)In if condition you should use double quotes("") to wrap variable post_id like
$('.like-btn[post-id = "'+post_id+'"]').html...
2) Another thing is you should return "true" as string not as boolean and check with string in ajax success block.
Solved add this line at the end of controller method
echo true;
code after edit
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
echo true;
}
I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.
My aim is to update a WordPress post using AJAX. My code so far:
Script:
$.ajax({
type: 'POST',
url: ajax_url,
data: {
'action': 'wp_post',
'ID': post_id,
'post_title': post_title
},
success: function( data ) {
$( '.message' )
.addClass( 'success' )
.html( data );
},
error: function() {
$( '.message' )
.addClass( 'error' )
.html( data );
}
});
PHP:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
if ( $id == 0 ) {
$error = 'true';
$response = 'This failed';
echo $response;
} else {
$error = 'false';
$response = 'This was successful';
echo $response;
}
}
As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.
I want to modify my success function to do something like this:
success: function( data ) {
if( $error == 'true' ) {
// do something
} else {
// do something else
}
},
The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.
Can anyone let me know how to pass $response and $error to my script's success function?
Is there a better approach I should be taking?
I'm newish to AJAX so forgive me if the question is very basic.
You shoud encode the response of the php script as json, as follows:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
if( data.status == 'error' ) {
// error handling, show data.message or what you want.
} else {
// same as above but with success
}
},
You can create a JSON array like this one, in the backend:
$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);
And then parse the json array to fetch the returned values, like this:
success: function( data ) {
var error = '';
var something = '';
for(var i = 0; i < data.length ; i++)
{
error = data[i].error;
something = data[i].something;
}
if( error ) {
// do something
} else {
// do something else
}
},
Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.
Note that there might be a syntax error, since I'm not testing it.
What you are looking for is json_encode()
This converts a PHP array to JSON.
For example:
$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);
You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.
For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).
if you use:
echo json_encode($response);
on your .php function, remember to use:
var data = $.parseJSON(data);
on your ajax success.
Example:
function php_ajax_function() {
// whatever you want to do...
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
console.log(data);
var data = $.parseJSON(data);
if( data.status == 'error' ) {
// do something
} else {
// do other thing
}
}
the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/
success: function( data ) {
if( data == 'This failed' ) {
// do something
} else {
// do something else
}
},
I do not understand because when the data were entered into the login are correct and I make this comparison response.success == "success" nothing happens, I check with firebug and the result is this:
Response
[{"ncontrol":"09680040","nombre":"Edgardo","apellidop":"Ramirez","apellidom":"Leon","tUser":"Admin","status":"success"}]
jQuery.ajax script to send data
// jQuery.ajax script to send json data to php script
var action = $("#formLogin").attr('action');
var login_data = {
ncontrol: $("#ncontrolLogin").val(),
password: $("#passwdLogin").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: login_data,
dataType: "json",
success: function(response)
{
**if(response.status == "success")** {
$("#status_msg").html("(+) Correct Login");
}
else {
$("#status_msg").html("(X) Error Login!");
}
}
});
return false;
And is PHP Script for processing variables from jQuery.ajax
$ncontrolForm = $_REQUEST['ncontrol'];
$passForm = $_REQUEST['password'];
$jsonResult = array();
$query = "SELECT * FROM users WHERE ncontrol = '$ncontrolForm' AND cve_user = SHA('$passForm')";
$result = mysqli_query($con, $query) or die (mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row >= 1 ) {
$_SESSION['n_control'] = $row['ncontrol'];
$_SESSION['t_user'] = $row['tUser'];
$jsonResult[] = array (
'ncontrol' => $row['ncontrol'],
'nombre' => $row['nombre'],
'apellidop' => $row['apellidop'],
'apellidom' => $row['apellidom'],
'tUser' => $row['tUser'],
'status' => 'success',
);
header('Content-Type: application/json');
echo json_encode($jsonResult);
}
You have an array, so do it this way:
if(response[0].status == "success") {
The object is the first item in the array.
EDIT:
Looking more closely at your PHP, it looks like you might be intending to loop through several rows in your query response and add them to your $jsonResult. Am I seeing it right?