I use jquery to call two url in file indexFunctions.php but the response of server is empty i dont know why please help there is my code
$("#start_peering").submit(function(event){
$("#wait").html('<img src="ajax-loader.gif">');
event.preventDefault();
$.ajax({
url : 'indexFunctions.php',
type : 'POST',
data : {peering:true},
success : function(data){
$("#StbStatus").html(data);
$.ajax({
url : 'indexFunctions.php',
type : 'POST',
data : {test_params:true},
success : function(data){
$("#results").html(data);
$("#wait").html('');
}
});
}
});
});
File indexFunctions.php
$rpi="http://192.168.1.15";
if (isset($_POST['peering']) && isset($_POST['test_params']))
{
$url = $rpi."/peering.php?askSTB=true";
$response = proxy::get($url);
echo $response;
$url = $rpi."/installUSBKeyOnStb.php";
$response = proxy::get($url);
echo $response;
}
?>
Thank you in advance.
You seem to be sending two request but checking if both are set at the same time.
if (isset($_POST['peering']) && isset($_POST['test_params']))
You should check for either or not both.
Try changing it to:
if (isset($_POST['peering']) || isset($_POST['test_params']))
You used AND && instead of OR ||
Related
I noticed that the following code doesn't work. When I remove , "json"); at the end of it, it works but i just get failure. I followed it to jquery spec on the site. Any idea why the $.post method won't work/enter?
The reason i know it wont enter $.post is because alert(form.serialize()); doesnt get called.
In my PHP i am returning the following when it posts:
$arr = array('status' => 'SUCCESS');
echo json_encode($arr);
exit();
This is my ajax below:
var form = $('#lines');
$.post('', form.serialize(), function(json) {
alert(form.serialize());
if(json.status === 'SUCCESS') {
alert(json);
console.log('success');
} else {
alert(json);
console.log('failure');
}
}, "json");
If I remove the json part at the end, it just returns the entire HTML of the page.
Your response is probably not json. If you remove ,"json", it works but post return string datas so your code can't work (json.status on string won't work). If you put ,"json", then it won't probably work if return is not proper json.
What you can do : leave "json" in the end, as this is what you want, add console.data(json) ; and console.data(typeof json) ; just at start of your success function.
Forget about alert, first it stop your script, and it's not as precise as console. Use console when you can.
I can suggest you to write it like this to make it more readable :
console.log('form.serialize()',form.serialize()) ;
var post = $.ajax({
method : 'POST',
url : '',
data : form.serialize(),
dataType : "json"
});
post.done(function(json){
console.log('success',json) ;
console.log('typeof json',typeof json) ;
if(json.status === 'SUCCESS') {
console.log('success');
} else {
console.log('failure');
}
}) ;
post.fail(function(data){
console.log('fail',data) ;
alert('post fail') ;
}) ;
Here is my complete php file index.php. Structure should looks like your one. Just note the top part where i make sure than when i have post data, i echo only the json and returns, so nothing else is sent (like your exit).
<?php
if ( isset($_POST['name']) )
{
echo json_encode(array('status' => 'SUCCESS')) ;
return false ;
}
?>
<form>
<input type="text" name="name" />
<input type="button" />
</form>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
jQuery('input[type="button"]').on('click',function(){
var form = jQuery(this).closest('form') ;
console.log('form.serialize()',form.serialize()) ;
var post = $.ajax({
method : 'POST',
url : '',
data : form.serialize(),
dataType : "json"
});
post.done(function(json){
console.log('success',json) ;
console.log('typeof json',typeof json) ;
if(json.status === 'SUCCESS') {
console.log('success');
} else {
console.log('failure');
}
}) ;
post.fail(function(data){
console.log(this) ;
console.log('fail',data) ;
alert('post fail') ;
}) ;
}) ;
</script>
You need to specify the headers in your php code and tell jQuery that a "json" response is on the way.. here is the correct php code
header('Content-Type: application/json');
$arr = array('status' => 'SUCCESS');
echo json_encode($arr);
exit();
notice the line that sends json headers, try it now and it'll work
I'm doing a code that send a data to a php file and send it back again and print it as a response however when i send the data it is sent as an empty data i did not know what is the problem this is the code that i tried:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi, "").split("\n");
function doRequest(index) {
// alert(resource[0]); The data here is ok and it is not empty whenever the data is sent the response is empty !
$.ajax({
url:'curl_check.php?email='+resource[0],
async:true,
success: function(data){
alert(data);
if (resource.length != 1) {
removeResourceLine();
doRequest(index+1);
}
}
});
}
doRequest(0);
since you're not sending the data using the data property of the ajax call object like so:
$.ajax({
...
data : { email : resource[0] }
...
});
you are sending it as part of the URL, so it should be picked up as a GET variable. in php, this looks like:
$email = isset($_GET['email']) ? $_GET['email'] : false;
that said, i'd suggest using the ajax data property and specifying the type property and setting it to GET or POST. you could also use $.ajaxSetup
Ok I am not sure what is wrong with what you are doing but I am going to give you code I use to send data to php and get a response. I am going to do it with json because it is awesome. I hope it helps:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi,"").split("\n");
function doRequest(index) {
$.post("curl_check.php", {
email: resource[0]
}, function(data, result, xhr){
if(result == 'success') {
console.log(data.success);
} else {
console.log('post failed');
}
}, "json");
}
The php code:
$json = array();
$email = $_POST['email']; //Please escape any input you receive
//Do what you have to do
$json['success'] = 'YAY IT WORKED';
die(json_encode($json));
I'm trying to submit a HTML form to a server and it fails. I have several issues here.
I'm making a CORS request. It is a request by the client and I can't do anything about it.
( My app resides in localhost:3000/login.html & My server resides in http://localhost:3001/Login/auth )
The server in localhost:3001 accepts JSON requests and give back a JSON Responce.
(I have disabled the web-security in the browser to allow the CORS Requests)
So, I have created the HTML Form and tried to submit it with AJAX. Here you can see the code.
$(function(){
$("#loginform").submit(function(e){
e.preventDefault();
// var data = $("#loginform").serialize();
var data = {"username" : $("#username").val(),"password" : $("#password").val()};
alert(JSON.stringify(data));
$.ajax({
type: "POST",
url: "http://localhost:3001/Login/auth",
data: data,
contentType: "application/json",
crossDomain : true,
dataType: "json",
success: function(data) {
alert("success" + JSON.stringify(data));
},
error:function(data){
alert('error : '+JSON.stringify(data));
}
});
});
});
I have created the mock server in PHP (codeigniter). Here is the code for that.
public function auth(){
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$debug_export = var_export(file_get_contents('php://input'), true);
file_put_contents('new.txt',$debug_export . PHP_EOL, FILE_APPEND);
$user = 'admin';
$pass = 'admin';
$token = '1';
foreach($input_data as $key=>$value) {
if ($key === 'username') {
$this_user = $value;
}
if ($key === 'password') {
$this_password = $value;
}
}
if(isset($this_user) && isset($this_password)){
if($this_password === $pass && $this_user === $user){
echo json_encode(array('token'=>$token));
}else{
echo json_encode(array('token'=>'null'));
}
}
return 0;
}
When I submit a form, I get a response like this.
....
<p>Severity: Warning</p>
<p>Message: Invalid argument supplied for foreach()</p>
<p>Filename: controllers/Login.php</p>
<p>Line Number: 77</p>
....
My 'new.txt' file has the log details as following.
''
'username=admin&password=admin'
I have really no idea what I'm doing wrong here. Can anyone help me out here?
I am passing a json in my ajax request but it is just returning 10 every time, why??
whay my array in not getting passed??
Here is my code:
jQuery(document).ready(function($){
$('#list-3 .ajaxcall').click(function(){
$.ajax({
type : "GET",
url : ajaxurl,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data : {
gpl_args : JSON.stringify({"cat":"26","posts_per_page":"4","paged":1}),
gpl_layout : {"show_thumb":"1","columns":"4","thumb_height":"85","thumb_width":"85","title_link":"1","content_excerpt":"50","posts_per_page":"4"}
},
success : function(response) {
// The server has finished executing PHP and has returned something,
// so display it!
$("#list-3").append(response);
}
});
});
});
and:
$args = isset($_REQUEST['gpl_args']);
//$args = json_encode(isset($_REQUEST['gpl_args']));
print_r($args)
Update:
my data inside ajax:
data : { gpl_args : JSON.stringify(<?php echo json_encode($args); ?>),
JSON.stringify(gpl_layout : <?php echo json_encode($layout); ?>)},
Simple fix. You have to DE-code the json, not EN-code it.
$args = isset($_REQUEST['gpl_args']) ? $_REQUEST['gpl_args'] : null;
$args = json_decode(stripslashes($args));
print_r($args)
See your php script:
$args = isset($_REQUEST['gpl_args']);
//$args = json_encode(isset($_REQUEST['gpl_args']));
// $args is false(Boolean type), But not json
print_r($args); // print_r(false); is show nothing!!
right way:
$json_array[] = isset($_REQUEST['gpl_args']) ? $_REQUEST['gpl_args'] : false;
echo json_encode($json_array); // will show json string
Aren't you printing the boolean result of isset() instead of the actual args?
I have an ajax code which passes data to php and then retrieves data from php...
function updateDatabase(syncData){
$.ajax({
type : 'POST',
async: false,
url : 'php/syncData.php',
dataType : 'json',
data: {myData : syncData}, //i even used this "mydata"+syncData
success : function(result){
res = result;
},
error : function() {
res = false;
}
});
return res;
}
And here's my php code...
<?php
include("database.php");
if(isset($_GET['myData'])){
$data = $_GET['myData'];
$insert = "INSERT INTO `mydata` VALUES (NULL,'$data')";
mysql_query($insert);
$data = mysql_insert_id();
echo json_encode($data);
}
?>
Here's javascript function that pass/calls ajax...
<script>
var theData = "blahblah";
var alertData = updateDatabase(theData);
alert(alertData);
</script>
the problem is that when i use htmt/text as data type it alerts empty/blank output, but when i used json as data type it alerts false where i conclude it went to error function not to success... anyone knows what's the proper way to do this? or maybe i'm just missing something? Thanks!
Well, you're posting the data using jQuery, but you're looking for a $_GET value in the PHP. Fix that and see if it changes anything.
Edit: It should look like this:
...
if(isset($_POST['myData'])){
$data = $_POST['myData'];
...
Try to set content type in your PHP file:
header( 'Content-Type: application/json' );
Then echo your data:
echo json_encode( $data );
Then exit script:
exit;
Hope it helps!