Cordova jquery ajax post to server php file - php

I want to compare input value of the input in the cordova app to an table in my database.
This is my jquery ajax post:
$('.postToken').click(function(){
console.log($('.valueToken').val());
var tokenValue = $('.valueToken').val();
$.ajax({
type: "POST",
url: "http://example.com/fysioWebapp/php/get_schema.php",
data: { dataString: tokenValue },
cache: false,
success: function(){
alert("Order Submitted");
}
});
and this is my get_schema.php on server:
<?php
include("connect.php");
$stringData = $_POST['dataString'];
ini_set('display_errors', 1);
var_dump($stringData);
?>
But it returns me null I first type in value data in my cordova app and then refresh the php page but keeps returning me null. Could somebody help me out on this issue?

Edit:
You need to see if the value exists in the database table like this
<?php
include("connect.php");
$stringData = $_POST['dataString'];
ini_set('display_errors', 1);
$checkToken = "SELECT * FROM Exercises WHERE YOUR_FIELD_NAME = ('$stringData')";
$checkResult = mysqli_query($conn, $checkToken);
if (mysqli_num_rows($checkResult) > 0) {
echo "Result already exists";
} else {
echo "0 results";
}
?>
Replace YOUR_FIELD_NAME for the column name you use for tokens.
The javascript I have already provided will console log wether or not the token exists.
Original
When you refresh the php file $stringData will be undefined.
Try this.
$('.postToken').click(function(){
console.log($('.valueToken').val());
var tokenValue = $('.valueToken').val();
$.ajax({
type: "POST",
url: "http://example.com/fysioWebapp/php/get_schema.php",
data: { dataString: tokenValue },
cache: false,
success: function(data){
console.log(data);
alert("Order Submitted");
}
});
});
This should console log the result of the var_dump.
If not change this line of the php file.
var_dump($stringData);
To.
echo var_dump($stringData);

You cannot just use ajax in your cordova app because of cross domain issues. Either you have to setup your server or php to get it or you can use jsonp.
For ajax solution you can try this on your php:
<?php
header("Access-Control-Allow-Origin: " . $_SERVER["HTTP_ORIGIN"]);
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: origin, referer, content-type");
header("Access-Control-Max-Age: 1728000");
if(strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS'){
header("Content-Type: text/plain");
header("Content-Length: 0");
http_response_code(204);
exit;
}
include("connect.php");
$stringData = $_POST['dataString'];
ini_set('display_errors', 1);
var_dump($stringData);
?>

Related

PHP how to return errors if I use functions to close the browser connection

using a function to close the connection with the browser while another process continues, is it possible to have the errors of the process in execution in a modal window opened by AJAX?
Now in the modal window I get are the value of $outputText even if the process stops.
Here are the details:
function to close browser connection
function closeOutput($outputText)
{
set_time_limit(0);
ignore_user_abort(true);
ob_start();
echo $outputText;
$size = ob_get_length();
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
header("Content-Length: $size",TRUE);
header("HTTP/1.1 200 OK");;
ob_end_flush();
ob_flush();
flush();
}
and this is the function of the process
function processmail($con,$id)
{
for($i=1; $i <= 20; $i++)
{
mysqli_query($con, "SELECT * FROM nlarea WHERE id='$id'");
sleep(2);
}
}
these 2 functions are called from this send.php file
<?php
//send.php
foreach ($id_letter as $id)
{
$outputText = '<img src="/img/loader.gif" class="img-fluid" alt=""> <p class="center mt-2">Close the window, the send continues automatically</p>';
closeOutput($outputText);
processmail($con,$id);
}
?>
The send.php is call from a AJAX
<script>
$(document).ready(function()
{
$("#btnSend").click(function(e)
{
e.preventDefault();
var dataform= $("#MyCheckForm").serialize();
$.ajax( {
url: "send.php?id=<?=$id?>",
method: "POST",
data: dataform,
success: function(data) {
console.log(data);
$("#myModal").modal("show");
$(".modal-title").html('Sending in progress');
$("#add_body").html(data);
},
error: function(data) {
console.log(data);
}
});
});
});
</script>
many thanks to all

Warning:session_start() [function.session-start]: Cannot send session cookie - headers already sent by

i want to create a search functioanlity for my real estate website.here i have created search criteria and to fullfill this criteria i have used a jax call. this ajax will call php file and that file will send data to search page . here is my sample code. i dont know what issue is there.
thanks in advnce
function searchBuy() {
//alert("search Loaed");
$.ajax({
url: 'searchBuyCriteria.php',
type: 'POST',
//dataType: "json",
data: {
cat: $('#SelectCat').val(),
MaxArea:$('#SelectMaxArea').val()
}
}).success(function(data){
console.log("Success"+data);
alert(JSON.stringify(data));
}).error(function(data){
console.log("Error"+data);
});
} </scipt>
searchCriteria.php
<?php
include_once('_secure/conn.php');
$city = $_POST['SelectCity'];
$cat= $_POST['SelectCat'];
$rooms = $_POST['SelectRooms'];
$minRange = $_POST['SelectMinRange'];
$maxRange = $_POST['SelectMaxRange'];
$minArea = $_POST['SelectMinArea'];
$maxArea = $_POST['SelectMaxArea'];
$conn=mysql_connect(DB_HOST,DB_USER,DB_PWD,DB_NAME);
mysql_select_db(DB_NAME);
$Searchqry ="Select * from tblcategory where category_title like '%".$cat."%' ";
$searchExec = mysql_query($Searchqry) or die(mysql_error());
$searchRow = mysql_fetch_array($searchExec);
//echo $searchRow;
echo json_encode($searchRow);
?>
conn.php
<?php
session_start();
ob_start();
if(!isset($path))
$path="./";
elseif($path=="")
$path="../";
require_once("settings.inc.php");
$database='srijanip';
$user='srijanip';
$pass='********';
$host='example.*****.in';
define("DB_HOST", "$host");
define("DB_NAME", "$database");
define("DB_USER", "$user");
define("DB_PWD", "$pass");
?>

ajax satuts cancelled after some attempts

im making and update in mysql table when button click, the problem is ajax jquery not working sometimes. It works fine and somehow after x attempts it stop working and stars cancelling my pettitions
my jquery code:
$.ajax({
type:'GET',
url: 'php/updateCosto.php',
data:{
obrero: $obrero,
fechai: $fechaa,
fechaf: $fechab,
costo: $costoS,
},
success: function(result){
if (result == 1) {
alert('Registro Actualizado');
location.reload(true);
}else {
console.log("no actualizado entrada");
alert('Registro No Actualizado');
location.reload(true);
}
}
}); // fin del ajax
the php one:
<?php
include('../db/conn.php');
$maestro = mysql_real_escape_string($_GET['obrero']);
$costosemanal = mysql_real_escape_string($_GET['costo']);
$fechai = mysql_real_escape_string($_GET['fechai']);
$fechaf = mysql_real_escape_string($_GET['fechaf']);
$update = "UPDATE tbl_costos
SET costo_semanal = '$costosemanal'
WHERE fechai = '$fechai'
AND fechaf ='$fechaf'
AND obrero = '$maestro'";
$result = mysql_query($update);
$rows = mysql_affected_rows();
echo ($rows);
mysql_free_result($result);
?>
the problem is after x number of attempts the success part of ajax object is not being used and im getting the STATUS (canceled) from network.
I dont know if it is an issue of CORS AJAX pettition or something!!

#mention and text or no #mention and text

I'm having a little issue with my php file and wondering if somebody can take a look.
If I update with an #mention and some text with the php below it will update the database and output the ajax. If it doesn't have an #mention and just text, it outputs nothing. How can I rectify the code to do both.
They are both contained with $_POST['newmsg'];
I have yet to escape my variables to prevent SQL injection.
PHP:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
session_start();
require_once "rawfeeds_load.php";
include_once "include/functions.youtube.php";
?>
<?
if(isset($_SESSION['id'])){
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&& isset($_POST['toid'])&& isset($_POST['privacy'])&& isset($_POST['red'])){
$_POST['newmsg']=str_replace('#'.$_POST['red'].'',''.$_POST['red'].'', $_POST['newmsg']);
$date=date('y:m:d H:i:s');
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}else{
rawfeeds_user_core::create_streamitem("3",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}
}
}
PHP USER_CORE
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser,$date){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$date=date('y:m:d H:i:s');
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,'$date','$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser=rawfeeds_user_core::getuser($creatorid);
rawfeeds_user_core::add_notification(2,$_POST['toid'],$fromuser['id'],$fromuser['fullname']." posted a status on your wall","../singlepoststreamitem.php?sid=$last_id");
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
}
AJAX
$("form#myforms").submit(function(event) {
event.preventDefault();
var content = $(this).children("#toid").val();
var newmsg= $(this).children("#newmsg").text();
var username = $(".red").attr("href");
var privacy = $("#privacy").val();
$.ajax({
type: "POST",
url: "insert.php",
cache: false,
dataType: "json",
data: { toid: content, newmsg: newmsg, privacy: privacy, red: username },
success: function(response){
Move the check for $_POST['red'] out of the main check:
if(isset($_POST['newmsg'])&& isset($_POST['toid'])&& isset($_POST['privacy'])){
// remove $_POST['red'] here -^
if (isset($_POST['red'])) { // check it here, otherwise your insert will not happen if $_POST['red'] is empty.
$_POST['newmsg']=str_replace('#'.$_POST['red'].'',''.$_POST['red'].'', $_POST['newmsg']);
}
$date=date('y:m:d H:i:s');
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}else{
rawfeeds_user_core::create_streamitem("3",mysqli_real_escape_string($mysqli,$_SESSION['id']),mysqli_real_escape_string($mysqli,$_POST['newmsg']),mysqli_real_escape_string($mysqli,$_POST['privacy']),mysqli_real_escape_string($mysqli,$_POST['toid']),mysqli_real_escape_string($mysqli,$date));
}
}

I need a help with this script ($.ajax())

Ajax:
$.ajax({
url: 'process.php',
type: 'post',
data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(),
dataType: 'json',
success: function(data){
if(data.success)
{
location.href = data.redirect;
}
else
{
alert(data.message);
}
}
});
And here is process.php code:
<?
$data = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['loginName'] == "test" && $_POST['loginPass'] == "test")
{
$data['redirect'] = "home.php";
$data['success'] = true;
echo json_encode($data);
}
else
{
$data['message'] = "<div id=Message>Your info is wrong...</div>";
$data['success'] = false;
echo json_encode($data);
}
}
?>
Sorry, but I'm from the Czech Republic and I don't speak english :D
Your data: misses a & right before loginPass=, which would lead to a garbled request. But maybe you should give jQuery an data object there anyway (it takes care of proper url encoding):
type: 'POST',
data: {loginName: $("#loginName").val(), loginPass: $("#loginPass").val()},
A second problem might be the lack of content-type in the php script. Add following on top (just to be sure this isn't why the result goes ignored):
<?php
header("Content-Type: application/json");
Another thing: You need more braces in the if statement, because && has higher precedence than the == comparison:
if(($_POST['loginName'] == "test") && ($_POST['loginPass'] == "test")) {
Since it is seemingly a PHP error, you must turn on error_reporting(E_ALL) and display_errors in the php.ini; If you still get no content returned from your URL, then add a print 'test123'; on top. And/or remove the test for REQUEST_METHOD (this adds no security anyway).

Categories