ajax response is duplicated - php

I've written an Ajax code, which calls a function in a php file.
queryURL = "http://<?php echo $_SERVER['SERVER_NAME'] ?>/MyPhpFile.php";
params = fromDate+" , "+to_Date;
$.ajax(
{
url: queryURL,
type: "post",
dataType: 'json',
async: false,
data:
{
funcName: "MyFunc",
values: params
},
complete: function (result) {
debugger;
doSth();
}
});
And in my php file:
if ($_POST) {
if (isset($_POST['funcName'])) {
if (function_exists($_POST['funcName'])) {
G::LoadClass('case');
$fName = $_POST['funcName'];
if (isset($_POST['values'])) {
$values = $_POST['values'];
$arrP = explode(",", $values);
echo call_user_func_array($fName, $arrP);
} else {
echo $fName();
}
}
}
}
fucnction MyFunc($fromDate, $toDate){
echo "1";
}
In the Network tab of my browser's debugger section, I can see that the php file just called once. Yet the response is duplicated.
If my function returns 1, the response will be 11.
Why is this happening?
how can I prevent it?

Remove echo from echo call_user_func_array($fName, $arrP);. Just use call_user_func_array($fName, $arrP);

Related

PHP receiving AJAX POST is empty

I'm to trying make a login using AJAX. AJAX function post data to PHP file but when I try to retrieve data from POST in PHP it's empty.
This is my AJAX posting code:
function validateUser() {
var userR = $("#fldUser").val();
var passwordR = $("#fldPassword").val();
if (userR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"> <b>A user is required.</b></p>");
} else if (passwordR.length < 1) {
$("#divStatusText").html("<p class=\"text-danger\"><b>A password is required.</b></p>");
} else {
// alert(userR + passwordR)
$.ajax({
type: 'POST',
// url: '/_Controlador/_GSystemLogIn.php/',
url: '/_Controlador/_GSystemLogIn.php',
// data:'user=' + userR +'&password=' + passwordR,
data: {
'user': userR,
'password': passwordR
},
dataType: 'JSON',
beforeSend: function(xhr) {
alert("En before send: " + userR + passwordR);
},
success: function(data) {
alert(data);
if (data.message === "Success") {
// location.href = "main.php";
} else {
$("#divStatusText").html("<p class=\"text-danger\"><b>User or password is incorrect.</b></p>");
$("#fldUser").val("");
$("#fldPassword").val("");
}
},
error: function(data) {
alert("Error in AJAX call.");
}
});
}
}
PHP code retrieving data:
var_dump($_POST);
$user = $_POST['user'];
$password = $_POST['password'];
echo( "PHP user received: ". $user);
echo( "PHP pass received: ".$password);
Alert in AJAX beforeSend prints data correctly but var_dump($_POST) prints:
array(0) { }
I've also tried different ways to send data and URL. I'll really appreciate your help. Thank you!
You have to decode the data first.
Just do -
$_POST = json_decode(file_get_contents('php://input'), true);
Here's the full explanation - https://stackoverflow.com/a/39508364/5400741
In your ajax request,
type: 'POST' has to be method: 'POST'
Look at here

How to run PHP with Ajax to validate results?

I'm making a Ajax script which validates results with PHP file before processing. Below is my Ajax script but I don't understand how to retrieve this DATA to validate.php and how to get results back from my PHP file.
<script>
function shake(){
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(),
success: function(data){
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
How can I process this Ajax script with validate.php ?
Can it be like:
<?php
// Get values from AJAX
$userid = $_GET['userID'];
$pass = $_GET['pw'];
?>
What results is this Ajax script expecting? I see resultado==0
So my question is how can I send resultado=1 with PHP to this script?
Should it be:
<?php
// Send result to AJAX
$resultado = 1;
?>
Thank you for helping.
I think this is what you're asking for.
The php script at the bottom is missing the closing tag for a reason.
In the success function, after you parse the result into a json object, you can reference the members with a '.' E.G result.varName
<script>
function shake()
{
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else
{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: {userID: $("#userID").val(), pw: $("#pw").val()},
success: function(data){
try
{
var result = $.parseJSON(data);
// result is now a JSON object
}
catch (e)
{
alert("JSON Parsing Failed on" + data );
return 0;
}
console.log(result);
if(result.isValid === 1){
// do something
}
alert(result.Message);
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else
{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
<?php
if( !isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST')
{
exit;
}
if( !isset($_POST['userID']) || !isset($_POST['pw']) )
{
// need more validation than this
exit;
}
$output = array();
$output['isValid'] = '1';
$output['Message'] = 'Data transfered';
$output['moreData'] = false;
echo json_encode($output);
Change data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(), to:
data: {userID: $("#userID").val(), pw: $("#pw").val()}
Also, I'd recommend setting userID and pw vars before passing it in as it is easier to read and easier to maintain.

Pass a value from controller JSON to view Ajax in CodeIgniter

The problem is I am getting the dialog box of false but the query is running fine and values are successfully added into the database. It should print true, but it is giving me a false. I checked through Firebug also the value res = 1 is going, but I don't know what is wrong in it.
My View:
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
if(msg.res == 1)
{
alert(true);
}
else
{
alert(false);
}
}
});
Controller:
$result = array();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
if ($query){ //&& any other condition
$result['res'] = 1;
}
else
{
$result['res'] = 0;
}
echo json_encode($result); //At the end of the function.
}
}
Try setting your dataType to json so the data sent back from the server gets parsed as JSON.
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1) {
alert(true);
}
else
{
alert(false);
}
}
});
Notice return.
if ($query){
$result['res'] = 1;
}
else
{
$result['res'] = 0;
}
return json_encode($result);//at the end of the function.
}

AJAX script not returning success in codeigniter

JS:
$(function() {
load_custom_topics()
// load_main()
});
function load_custom_topics(){
$.ajax({
type: "POST",
async: false,
url: 'http://rickymason.net/thebump/index.php/ajax/load_custom_topics',
dataType: 'json',
data: { },
success: function(page){
alert(page);
}
});
event.preventDefault()
}
load_custom_topics
public function load_custom_topics()
{
$check = $this->page_model->check_active_topic();
if ($check == FALSE)
{
$page['content'] = 'TEST equals FALSE';
} else {
$page['content'] = 'TRUE';
}
echo json_encode($page);
}
going to the page index.php/ajax/load_custom_topics returns this:
{"content":"TEST equals FALSE"}
The alert is not firing! Any idea why?
Actually, on inspecting a request to your controller, I found that you weren't setting the proper headers the ajax call expects (text/json).
See codeigniter's Output class.
Using
$this->output->set_content_type('application/json')->set_output(json_encode($page));
instead of
echo json_encode($page);
should do the trick.

Remove element from HTML with jQuery

I am building a system where the user builds their own navigation system, the process is when the user visits the site there is a llist of available topics they can select slect a top creates and accordion that holds all that topics content, clicking the topic again should remove the top, currently I have this code, but it does not work, can any one guide me,
The javascript
$("a.navlink").click(function(ev) {
var url = $(this).attr("href")
var id = $(this).attr("id")
ev.preventDefault();
if(!$(this).hasClass('saved')) {
//$("a.navlink").addClass('active')
$.ajax ({
url: url,
type: "POST",
data: "method=add&id="+id,
success: function (html) {
$('#accordion').accordion('destroy');
$("#accordion").append(html);
$('#accordion').accordion({
//active: 0,
header:'h2.'+id,
collapsible:true
});
$("a.navlink").addClass('saved');
}
});
} else if($("a.navlink").hasClass('saved')) {
$.ajax ({
url: url,
type: "POST",
data: "method=delete",
success: function (html) {
$("a.navlink").removeClass('saved');
//$("."+id).remove();
}
});
}
});
The HTML/PHP That builds the accordion
<?php
var_dump($_POST);
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class=".$this->input->post('id')."><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
if(isset($favourites_category)) {
//die(var_dump($favourites));
echo "<h2 class=".$this->input->post('id')."><a href='#'>$favourites_category</a></h2>";
$count = 0;
$replace = array(".", "png", "gif", "jpg");
foreach ($favourites as $row) {
$count ++;
$image_name = str_replace($replace, "", $row['image_name']);
echo "<div class='$favourites_category'>";
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$row[content_id]'>";
echo "<img src='/media/uploads/".strtolower($row['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "<a/>";
echo "</div>";
}
}
?>
Basically I need away to identify each accordion that is created and if its link is pressed while it has an accordion on scrren the accordion is deleted from the HTML on screen.
The callback function has a different context than the ajax call. Your variables id and url are not accessible in your callbacks. You can have them passed through the ajax call to use it in the callback, but the response should be JSON instead HTML.
Also, you have $("a.navlink") (which will evaluate to the first a.navlink) instead of $(this) in a few places ( like the else if).
Here's some updated code, but I'm not real clear on what you are trying to do
$("a.navlink").click(function(ev) {
var url = $(this).attr("href")
var id = $(this).attr("id")
ev.preventDefault();
if(!$(this).hasClass('saved')) {
//$("a.navlink").addClass('active')
$.ajax ({
url: url,
type: "POST",
data: {method: 'add', id: id},
dataType: "json",
success: function (response) {
//vars url and id are not accessible here
//so it needs to be returned from the ajax call
$('#accordion').accordion('destroy');
$("#accordion").append(response.html);
$('#accordion').accordion({
//active: 0,
header:'h2',
collapsible:true
});
$("#" + response.id).addClass('saved');
}
});
} else if($(this).hasClass('saved')) {
$.ajax ({
url: url,
type: "POST",
data: {method: 'delete', id: id},
dataType: "json",
success: function (response) {
$("#" + response.id).removeClass('saved');
$("h2." + response.id).remove();
}
});
}
});

Categories