So I have this strip of code working for one page and not working for another page... Same code, same form name attributes, same php functionality on the server side. I'm calling with jquery ajax.. Calling from one page, it works completely fine... When I call from another page, it gives me "Unidentified index"
I've tried changing the names around (to remove duplicates and all)..
I seem to be sure that the names are correct though.
<script type="text/javascript">
$('#uploadcsv').submit(function(e){
e.preventDefault();
$.ajax({
url: "functions/grocerystore.php?item=fetchcontacts",
method: "post",
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
var accumulator = "";
var filetype = $('#uptype').val();
if(filetype == "csv"){
for(trav=0; trav<data.length; trav++){
accumulator += data[trav];
if(trav < data.length-1)
accumulator += "\r\n";
}
}else{
for(trav=0; trav<data.length; trav++){
accumulator += data[trav];
}
}
var mobilenumbers = $('#mobilenumbers');
mobilenumbers.html(accumulator);
},
error: function(data){
console.log(data);
}
});
});
</script>
php
case 'fetchcontacts':
if(!empty($_FILES['customFilex']['name'])){
$name = explode('.',$_FILES['customFilex']['name']);
$extension = end($name);
$file_data = fopen($_FILES['customFilex']['tmp_name'],"r");
if($extension == 'csv'){
fgetcsv($file_data);
$mobile = array();
$init = 0;
while($row = fgetcsv($file_data)){
$mobile[$init] = $row[0];
$init++;
}
fclose($file_data);
}else{
if ($file_data = fopen($_FILES['customFilex']['tmp_name'], 'r')) {
$mobile = array();
$init = 0;
while (!feof($file_data)) {
$row = fgets($file_data);
$mobile[$init] = $row;
$init++;
}
fclose($file_data);
}
}
echo json_encode($mobile);
}else{
$report["status"] = "failed";
echo json_encode($report);
}
break;
I just need it to accept my file...
You are using $_FILES['customFilex']['tmp_name']without checking if the keys exists in the $_FILES array.
Related
I am having trouble getting the success call to fire in my ajax request. I know the communication is working fine, but the last call in my PHP script, which is a return json_encode($array); will fire as if it is a part of the onprogress object. I would like to "break" the onprogress call and run the success function on the last data sent via return json_encode when the PHP script has terminated...
Here is my AJAX call:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
dataType: "json",
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = data;
}
});
e.preventDefault();
});
});
And here is the basic PHP server script:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count < 100){
progress_message($count, "working....");
$count += 10;
sleep(2);
}
return json_encode($array);
?>
I made your code work, there were 2 errors. First, in your while loop, your function name is incorrect, try this:
progress_msg($count, "working... ." . $count . "%");
Secondly, the very last line outputs nothing, so technically you don't get a "successful" json return. Change the last line of your server script from:
return json_encode($array);
to:
echo json_encode($array);
UPDATE: Full working code with hacky solution:
Ajax:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
dataObjects = data.split("{");
finalResult = "{" + dataObjects[dataObjects.length - 1];
jsonResponse = JSON.parse(finalResult);
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = jsonResponse.msg;
}
});
e.preventDefault();
});
Search.php:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count <= 100){
progress_msg($count, "working... " . $count . "%");
$count += 10;
sleep(1);
}
ob_flush();
flush();
ob_end_clean();
echo json_encode($array);
?>
The problem with the "success" method of the ajax call was that it couldn't interpret the returning data as JSON, since the full return was:
{"progress":0,"msg":"working... 0%"}{"progress":10,"msg":"working... 10%"}{"progress":20,"msg":"working... 20%"}{"progress":30,"msg":"working... 30%"}{"progress":40,"msg":"working... 40%"}{"progress":50,"msg":"working... 50%"}{"progress":60,"msg":"working... 60%"}{"progress":70,"msg":"working... 70%"}{"progress":80,"msg":"working... 80%"}{"progress":90,"msg":"working... 90%"}{"progress":100,"msg":"working... 100%"}{"msg":"hello world"}
Which is not a valid JSON object, but multipje JSON objects one after another.
I tried removing all previous output with ob_end_clean(); , but for some reason I can't figure out, it didn't work on my setup. So instead, the hacky solution I came up with was to not treat the return as JSON (by removing the dataType parameter from the AJAX call), and simply split out the final Json element with string operations...
There has got to be a simpler solution to this, but without the use of a third party jQuery library for XHR and Ajax, I couldn't find any.
I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];
So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")
Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this
If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}
I'm trying to send a php form data via AJAX (without the refresh) and display data in new form. I echo query but it didnt work. On AJAX response it shows me getReportAj form on call.The code goes like this:
Javascript
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
}
});
}
getReportAj.php
<?php
include "include/config.inc.php";
if(!isset($_SESSION['s_activName']) && !isset($_SESSION['s_userType']) || isset($_SESSION['s_userType']) && $_SESSION['s_userType'] == 'Student') {
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:checkLogin.php");
}
else {
if(isset($_REQUEST['submit'])) {
$selectReport = "SELECT * from gradeterm1
WHERE studentId = ".$_POST['studentId']."
AND termValue = 1
LEFT JOIN studentmaster ON studentmaster.studentId = gradeterm1.studentId";
$selectReportRes = mysql_query($selectReport);
if($reportRow = mysql_fetch_array($selectReportRes)); {
$eReadingPro = $reportRow['eReadingPro'];
$eReadingFlu = $reportRow['eReadingFlu'];
$eReadingCom = $reportRow['eReadingCom'];
$eWritingCre = $reportRow['eWritingCre'];
$eWritingHan = $reportRow['eWritingHan'];
$eWritingGra = $reportRow['eWritingGra'];
$eWritingSpe = $reportRow['eWritingSpe'];
$eWritingVoc = $reportRow['eWritingVoc'];
$ewSpeakinCon = $reportRow['ewSpeakinCon'];
$ewSpeakinRec = $reportRow['ewSpeakinRec'];
$ewSpeakinCla = $reportRow['ewSpeakinCla'];
$eListingComp = $reportRow['eListingComp'];
$eListingCon = $reportRow['eListingCon'];
$extraReading = $reportRow['extraReading'];
$activityPro = $reportRow['activityPro'];
$hiReadingPro = $reportRow['hiReadingPro'];
$hiReadingFlu = $reportRow['hiReadingFlu'];
$hiReadingCom = $reportRow['hiReadingCom'];
$hiWritingCre = $reportRow['hiWritingCre'];
$hiWritingHan = $reportRow['hiWritingHan'];
$hiWritingGra = $reportRow['hiWritingGra'];
$hiWritingSpe = $reportRow['hiWritingSpe'];
$hiWritingVoc = $reportRow['hiWritingVoc'];
$hiwSpeakinCon = $reportRow['hiwSpeakinCon'];
}
}
}
include("./bottom.php");
$smarty->display('getReportAj.tpl');
?>
<script>
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
console.log(data);
}
});
}
</script>
in success event.. put the console.log(data) then run the script and check in console.
My js:
$('#select').change(function() {
var name = $(this).val();
$.ajax({
type: "POST",
url: "data/grab.php",
data: { type: "hops", name: name },
dataType: "json",
success: function(data) {
alert(data);
var aa = data['aa'];
$('#hops-aa').val(aa);
}
});
});
grab.php
<?php
$type = $_POST['type'];
$name = $_POST['name'];
if ($type == 'hops') {
$result = $name;
}
$result = json_encode($result);
return $result;
I added the alert() in the ajax call to double check what I'm getting back from the script, and it's always null. Anything I'm missing?
You need to actually echo or print the $result. In PHP using return from the file scope does not send the returned value to the output stream.
You use echo to print out the results in PHP, not return:
echo $result;
(As previous answers stated)
You need to echo/print the $result variable.
<?php
$type = $_POST['type'];
$name = $_POST['name'];
if ($type == 'hops') {
$result = $name;
}
$result = json_encode($result);
echo $result; // return $result;
?>