Ajax request to php with empty POST data - javascript

I am new to javascript and I have problem with an ajax POST to php.
I am trying tosend javascript variables to php via an ajax POST but it doesn't work.
The ajax post is sent but it sends empty POST. I got alert "Error occured ! 202" when trying to save data to bdd.
Thanks in advance for helping me.
here are my javascript and php codes :
<script type="text/javascript">
function save_marker(mId, vId)
{
//Save new marker using jQuery Ajax
var myData = { 'markerId' : mId, 'vendorId' : vId }; //post variables
console.log(myData);
jQuery.ajax({
type: "POST",
url: "https://marchad.fr/wp-content/plugins/wc-multivendor-marketplace/includes/map_process.php",
data: myData,
cache: false,
dataType: "json",
contentType : "application/json; charset=utf-8",
success: function(dataResult){
var stringified = JSON.stringify(dataResult);
var dataResult = JSON.parse(stringified);
if(dataResult.statusCode==200){
alert("ok"+dataResult);
}
else if(dataResult.statusCode==201){
alert("Error occured !");
} else if(dataResult.statusCode==202){
alert("Error occured ! 202");
} else if(dataResult.statusCode==203){
alert("Error occured ! 203");
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('Ooops, something happened: ' + ajaxOptions + ' ' +thrownError);
}
});
}
</script>
<?php
global $WCFM, $WCFMmp, $wpdb;
$mId = filter_var($_POST["markerId"], FILTER_SANITIZE_STRING);
$vId = filter_var($_POST["vendorId"], FILTER_SANITIZE_STRING);
################ Save & delete markers #################
if( isset($mId) && isset($vId) ) //run only if there's a post data
{
if( !empty($mId) && !empty($vId) ){
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
$results = $wpdb->query("INSERT INTO markers_users (id, mark_id, user_id, user_actif) VALUES ('', $mId , $vId , 'oui')");
if (!$results) {
echo json_encode(array("statusCode"=>201));
} else {
echo json_encode(array("statusCode"=>200));
}
} else {
echo json_encode(array("statusCode"=>202));
}
} else {
echo json_encode(array("statusCode"=>203));
}
?>

Your problem is here:
var myData = { 'markerId' : mId, 'vendorId' : vId };
The field names don't need to be in quotes
Change it to this and try again:
var myData = { markerId : mId, vendorId : vId };

try this
data: JSON.stringfy(myData)

ok so the solution is :
<script type="text/javascript">
function save_marker(mId, vId)
{
//Save new marker using jQuery Ajax
var myData = { markerId : mId, vendorId : vId }; //post variables
console.log(myData);
jQuery.ajax({
type: "POST",
url: "https://marchad.fr/wp-content/plugins/wc-multivendor-marketplace/includes/map_process.php?markerId="+ mId +"&vendorId="+ vId,
data: myData,
cache: false,
dataType: "json",
contentType : "application/json; charset=utf-8",
success: function(dataResult){
var stringified = JSON.stringify(dataResult);
var dataResult = JSON.parse(stringified);
if(dataResult.statusCode==200){
alert("ok"+dataResult);
}
else if(dataResult.statusCode==201){
alert("Error occured !"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid+dataResult.datamId+dataResult.datavId);
} else if(dataResult.statusCode==202){
alert("Error occured ! 202"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid);
} else if(dataResult.statusCode==203){
alert("Error occured ! 203"+dataResult.statusCode+dataResult.mId+dataResult.vId+dataResult.rawData+dataResult.rawDataMid+dataResult.rawDataVid);
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('Ooops, something happened: ' + ajaxOptions + ' ' +thrownError);
}
});
}
</script>
<?php
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno())
{
die('Erreur de connexion : ' . $mysqli->connect_errno);
}
$rawData = file_get_contents("php://input");
$data = array();
parse_str($rawData, $data);
$mId = $data['markerId'];
$vId = $data['vendorId'];
################ Save & delete markers #################
if( isset($mId) && isset($vId) ) //run only if there's a post data
{
if( !empty($mId) && !empty($vId) ) //run only if there's a post data
{
$results = $mysqli->query("INSERT INTO markers_users (id, mark_id, user_id, user_actif) VALUES ('', $mId , $vId , 'oui')");
if (!$results) {
echo json_encode(array("statusCode"=>201, "mId"=>$mId, "vId"=>$vId, 'rawData' => $rawData, 'rawDataMid' => $rawData["markerId"], 'rawDataVid' => $rawData["vendorId"], "datamId"=> $data['markerId'], "datavId"=> $data['vendorId']));
} else {
echo json_encode(array("statusCode"=>200));
}
} else {
echo json_encode(array("statusCode"=>202));
}
} else {
echo json_encode(array("statusCode"=>203));
}
?>

Related

how to avoid the multiple execution of insert query

I am working with OT system.i have some problem regrading OT hours request program.this program send the department employee OT hours in to the admin panel notification and OT hours save in the database.my problem is when send OT request each person create the separate OT notification .I want send the single notification set of the department people.
$(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
if(data.success)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp = 1;
dataTable.ajax.reload();
}
}
});
});
alert(temp);//if data.success block execute but alert still get value as 0
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
i all ready got some solution .i get create the temp variable and OT request process successful it assign temp = 1 and after the each loop i try to insert notification data into the database.but if data.success success but alert(temp); not get value as 1 .how do i solve this question.
back end code
if($_POST["action"] == 'add_ot')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$state = 5 ;
$emp_no = $_POST["emp_no"];
$ot_hours = $_POST["ot_hours"];
if($ot_hours != '00:00'){
$data = array(
':today' => $today,
':department' => $department,
':emp_no' => $emp_no,
':ot_hours' => $ot_hours,
':state' => $state
);
$query = "
INSERT INTO otresquest
(emp_id,date,ot_hour,dept_Id,overtime_status)
VALUES (:emp_no, :today, :ot_hours,:department,:state)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$output = array(
'success' => 'OT request has been Sent succesfully',
);
}
}
echo json_encode($output);
}
if($_POST["action"] == 'add_comment')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$comment_status = 0 ;
$data = array(
':today' => $today,
':department' => $department,
':state' => $comment_status
);
$query = "
INSERT INTO comments
(dept_Id,date,comment_status)
VALUES (:department,:today,:state)
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
**This might be solve your problem**
(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp++;
dataTable.ajax.reload();
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
}
});
});
swal({title: "No data entering?",text: "Not set the overtime hours !",type: "warning"});
});

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

Post to php file, and retrieve data with javascript

So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});

How to show alert when error comes from the PHP as response to ajax request in following case?

The jQuery AJAX function is as follows :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
The PHP code is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg;
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data = $objUserLogin->GetResponse();
echo json_encode($data);
die;
}
break;
Now I'm able to print the success when the response comes without any error but what about showing the alert message when some error happens. How to achieve it? What change needs to make to the above code? Please help me.
Use below condition in success:
success: function(result, success) {
if($.inArray( "error_message", result)) {
alert("Error message");
} else {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
}
on php file if u found data acc to ur parameter
than it ok if there is no data acc to ur parameter than this time u can call its an error so in thsi case echo "error";
and on ajax page check for result if its value is error then do what else u want
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}

Reading response text in Ajax using JQuery

function upload_file(){
var file =document.getElementById('computer_image').files[0];
if(file!==null){
if(file.type==='image/jpeg' ||
file.type==='image/png' ||file.type==='image/jpg'){
$('#progressbar').show();
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'file_upload/ImageUpload',
type: 'POST',
headers: {"abc": "aaaaaaaaa"},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandler, false);
}
return myXhr;
},
success: function( request,data, textstatus){
alert(textstatus.getResponseHeader('abc'));
},
error:errorHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
}
else {
alert('sorry we are not accepting file other than PNG , JPEG and JPG');
}
}
}
I am using CodeIgniter Framework .Below is my PHP code to Process a file .
function ImageUpload(){
$status="";
if (empty($_FILES["file1"]))
{
$status = "sorry Something went wrong";
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
if ($status !== "sorry Something went wrong")
{
//call a function to get path name
$path="./upload";
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size' ] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['remove_spaces']=TRUE;
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
/* If directory doesn't exist than create a new .*/
if (!file_exists($path) && !is_dir($path)) {
mkdir($path);
}
/* If there is any error during upload */
if ( ! $this->upload->do_upload('file1')){
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
/*Image has been successfully Uploaded */
else{
$var = $this->upload->data('','');
echo $path.'/'.$var["file_name"].'='.$var["image_width"].
'='.$var["image_height"];
}
}
I have tried multiple flavor to get Response text but didn't success . What should be after complete to read response text .
getting null as output .
In $.ajax()'s success method first parameter will give response
Example:
$.ajax({
success: function(response, textStatus, jqXHR ){
console.log(response);
alert(response.getResponseHeader('abc'));
},
});
Check this link. It will be useful to understand $.ajax() more clearly.

Categories

Resources