Return php variable? - javascript

I have made a little AJAX-script for my site, which executes a php-script in another file on submission. I managed to echo out the result in the original file with the AJAX-function, but I have not managed to transfer a variable from the php file to the original one.
I need this variable in order to add an event listener which will look for changes in that particular variable (not sure how to do that either).

Here's are what you are looking for it's working:-
Put this in your forsok.php
<div id="input">
<input type="text" id="number" name="value">
<b id="show_result"></b>
</div>`
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#number').on('keyup',function(e){
if(e.which == 13){
var get_var_name = $(this).val();
$.get('result.php',{number:get_var_name},function(data,status){
if(status == 'success'){
alert(data['show']);
$('#show_result').text(data['show']);
}else{
alert('Nothing');
}
});
}
});
</script>
For hej.php:-
<?php
$one=$_GET['number'];
if(empty($one)) {
echo "Can't be blank";
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$show=$one*2;
$arr = array(
'show'=>$show
);
header('Content-Type:application/json');
echo json_encode($arr);
exit();
// echo $show;
} else {
echo "NaN";
$a['result']='null';
$a['error']='nan';
}
}
?>

First create an array of what should be the output. JSON encode that array and then you can parse the output in your ajax success handler. Like in your php file output like:
echo json_encode(array(
'result' => 'null',
'error' => 'nan'
));
Then in you ajax success turn the json into an object and parse data as you want:
success: function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data);
$('#utmatning').html(obj.result); // result value from your json return
$('#utmatning').append(obj.error); // error value from your json return
}

At last of your php file, add,
json_encode($a);
In ajax success,
success: function(html) {
$.each(html, function(index, element) {
alert(element.result);
alert(element.error);
//append to which ever div you want.
});
}
Now with this, you can get n number of array indexes from php

Instead of echoing strings here and there in in hej.php it might better to return JSON data to your ajax call. so you can evaluate if an error occured, which error it is or which valid result has been returned.
hej.php:
<?php
$one=$_GET['value'];
if(empty($one)) {
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$a['result']=$one*2;
$a['error']='ok';
} else {
$a['result']='null';
$a['error']='nan';
}
}
die(json_encode ($a));
?>
if $value was 1 that would return
{"result":"2","error":"ok"}
In forsok.php you could check the reults and act accordingly
...
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(response)
{
if (response.error=='ok'){
$('#utmatning').html(response.result); // show response from the php script.
}
else{
console.log(response.result); // handle the error
}
}
});
...
Regards,
Stefan

Related

jQuery won't reload this div or recognise it's new PHP $_SESSION value

I am using Ajax to submit a form using a nonce stored as a PHP session which, as the name suggests, unsets itself and generates a new nonce every time it is used successfully. This works perfectly the first time the Ajax is run.
If I view the source on the page after running it, the new nonce is being updated correctly in the actual code, but for some reason jQuery refuses to read the new value from the #nonce div or update the display on the page with the new $_SESSION value.
The div holding the nonce and the submit button (index.php)
echo '<input type="text" id="nonce" value="'.$_SESSION['nonce'].'">';
echo '<div id="form-test-ajax">
<input type="submit" name="submit" value="submit" id="btn">
</div>';
The jQuery functions in external file (functions.js)
$(document).ready(function() {
$('#btn').click(function() {
$.ajax({
url: 'adminapi.php',
dataType: 'json',
method: 'post',
cache: false,
data : {
"action": "testAction",
"nonce": $('#nonce').val()
},
success: function(data) {
reloadNonce();
},
error : function(xhr, status) {
alert(xhr.status);
console.log("something went wrong");
},
timeout: 30000,
});
});
function reloadNonce() {
$("#nonce").load(location.href + " #nonce");
}
});
The Ajax handler (adminapi.php)
require_once 'inc/globals.php';
header("Access-Control-Allow-Methods:POST");
header("Access-Control-Allow-Headers:Content-Type");
header("Access-Control-Allow-Credentials:true");
header("Content-Type:application/json");
// Check if the request is an AJAX request
function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if (isAjax()) {
if (isset($_POST["action"]) && !empty($_POST["action"]) && isset($_POST["nonce"]) && !empty($_POST["nonce"])) {
$action = strip_tags($_POST["action"]);
$nonce = strip_tags($_POST["nonce"]);
// Validate nonce
$securityCheck = validateNonce($nonce);
// Nonce checked out
if ($securityCheck) {
admin_response(200, "Success");
exit();
} else {
// Invalid nonce, failed
admin_response(200, "Error : Security token was incorrect");
exit();
}
}
}
The other relevant PHP functions (globals.php)
// Generate nonce
function generateNonce()
{
$_SESSION['nonce'] = bin2hex(openssl_random_pseudo_bytes(16));
return;
}
// Validate nonce
function validateNonce($nonce)
{
if ($nonce == $_SESSION['nonce']) {
unset($_SESSION['nonce']);
generateNonce();
sessionTimeOut();
return true;
} else {
return false;
}
}
// Set session expiry
function sessionTimeOut()
{
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (15 * 60);
}
// Deliver admin function response
function admin_response($status, $status_message)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$json_response = json_encode($response);
echo $json_response;
}
I've obviously left off chunks of irrelevant code PHP wise, session_start(); etc as the PHP side of this is running perfectly. It's only the jQuery I'm having an issue with.
The JQuery load() method internally uses the innerHTML function to populate the matched element with the ajax response. So I would say it's not appropriate for your use-case, as you need to set the value of an input field, instead of update the html contents of a div. I'd check out the JQuery docs for more info: http://api.jquery.com/load/
Just in case anybody else runs into a similar problem the answer was to return the new nonce in the ajax success response and then set the value to the nonce id.
Works now!
The jQuery
success: function(data) {
$("#nonce").val(data.nonce);
reloadNonce();
...
The PHP
admin_response(200, "Success", $_SESSION['nonce']);
...
and..
function admin_response($status, $status_message, $nonce)
{
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['response'] = $status_message;
$response['nonce'] = $nonce;
$json_response = json_encode($response);
echo $json_response;
}

Trying to send a value from JS to PHP - JQuery's $.ajax() method is not working

I want to execute a JS function when a PHP form is submitted, and from that function, I want to return a value (which is based on user's input) to PHP, where I'd like to echo it.
This is an SSCCE. In the real code, there is more than just echoing the value, and the value is a JSON object.
Following is my code. The problem is that the $.ajax(); part is not working. Nothing happens in the browser after alert(name);.
Why isn't this working properly? How can I fix this?
From index.php:
<form id="form">
Name:
<input id="name" type="text" />
<input type="Submit" value="Go" />
</form>
From scripts.js:
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
alert(name);
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
}
});
});
});
echo.php:
<?php
if ( isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"]) ) {
echo $_POST["nameEntered"];
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
EDIT:
Console:
Network:
EDIT 2:
Added the following to $.ajax():
,
success: function(){
alert("success");
},
error : function(){
alert("error");
}
I get an alert saying success but the browser NEVER directs to echo.php =s
EDIT 3:
After the alert saying success, a ? is added to the URL in the browser. Initially the URL was http://localhost/Test12/index.php and it changed to http://localhost/Test12/index.php?.
This way should show response.
JAVASCRIPT
$("#form").submit(function(event) {
event.preventDefault();
var name = $("#name").val();
//alert(name);
$.ajax({
type:'POST',
url:'http://localhost/Test12/echo.php',
data: {
nameEntered : name
},
success : function(data){
console.log(JSON.parse(data));
},
error : function(error){
console.log('erro', error);
}
});
});
PHP
<?php
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
$name = array("nome" => $_POST["nameEntered"]);
echo json_encode($name);
} else {
echo '$_POST["nameEntered"] is not set.';
}
?>
As a test, replace your echo.php with:
<?php
echo 'Incoming = ' .$_POST["nameEntered"]. "/r/n";
if (isset($_POST["nameEntered"]) && !empty($_POST["nameEntered"])) {
echo 'Here 01';
} else {
echo 'Here 02';
}
?>
Try removing the document.ready() or instead of .submit use .on('submit', function(e){}); or add absolute path '/page.php'
I think you need to add "event" as parameter in your submit function, in addition to the success call to show results
What does this give you:
$.ajax({
type:'POST',
url:'echo.php',
data: {
nameEntered : name
},
success: function(recd){ // <-------
alert(recd); // <-------
},
error : function(){
alert("error");
}
});
You're calling event.preventDefault(), but you've failed to add the event to your callback's parameters... so you're not actually stopping the form from being submitted. That is why you see the question mark in the address bar.
Try:
function(e){
e.preventDefault();
};

Passing JSON object to PHP script

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

jquery ajax() issue while printing array with each()

In my code I am returning an php array containing records of 7 Students. With jquery ajax() I want to print these records on success function.
DB table Students
+---------------------------+
| name | fathername | Email |
+---------------------------+
submit.php
$query=mysql_query("SELECT * from Students LIMIT 0,6");
$row= array();
$row=mysql_fetch_array($query);
return json_encode($row);
index.php
<script>
$(function(){
$("#form1").submit(function(event){
event.preventDefault();
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
$('.FatherName').text(result["fathername"]);
$('.Email').text(result["email"]);
});
}
});
});
});
</script>
<div class="StudentName"></div>
<div class="FatherName"></div>
<div class="Email"></div>
EDIT
I tried to return only 1 result from php and it works i.e.
echo json_encode(mysql_fetch_array($query));
When I return all 6 records the jquery function dont execute i.e.
while($result=mysql_fetch_array($query))
{
echo json_encode($result);
}
There's difference between PHP arrays and JS arrays, you can't simply pass the PHP array to your javascript, so instead you should first json_encode it and send it to js.
This will convert your PHP array to JSON array, eg:
array(3) {
[0]=>
string(3) "foo"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
to
string(33) "{"0":"foo","2":"baz","3":"blong"}"
So try -
return json_encode($row);
and then when you catch the response, use parseJSON:
result = jQuery.parseJSON(result);
$.each(result,function(){
$('.StudentName').text(result.name);
$('.FatherName').text(result.fathername);
$('.Email').text(result.email);
});
Edit:
Another thing, instead of return json_encode($row); write echo json_encode($row);
Edit 2
(to send all 6 records)
$final = array();
while($result=mysql_fetch_array($query))
{
array_push($final,$result);
}
echo $final;
function success(result){
$.each(result,function(){
$('.StudentName').text(result["name"]);
looks problematic. There doesn't really seem to be a reason to loop over the result, as you assign all of its contents to the same elements in the page.
However, assuming that result is an array of objects (like SQL queries usually produce it), then it should be
function(result){
$.each(result,function(obj) {
// missing parameter!!! ^^^
$('.StudentName').text(obj["name"]);
// access that here: ^^^
Also do a console.log(result) or simply browse the request URL to check whether the PHP scripts yields the expected response.
Here is an example of parsing JSON that may help you - http://jsfiddle.net/Su6QR/
Given that example, change your AJAX function -
$.ajax({
url:'submit.php',
type:'GET',
data:$(this).serialize(),
success:function(result){
var members = $.parseJSON(result);
$.each(members, function() {
var newStudent = '<span>' + this['name'] + '</span>';
var newFather = '<span>' + this['father'] + '</span>';
var newEmail = '<span>' + this['email'] + '</span>';
$('.StudentName').append(newStudent);
$('.FatherName').append(newFather);
$('.Email').append(newEmail);
});
}
});
This should return all of the data and place them into the divs that you have created. The formatting will not be what you want, but you should be able to fix that pretty easily.
This might help you.
Your AJAX
$("#form1").click( function(e){
var Somename = { };
$.each($('#form1').serializeArray(), function() {
Somename [this.name] = this.value;
});
e.preventDefault();
$.ajax({
type: "GET",
url: "submit.php",
data: { upddt_empID: upddt_empID, somevariable: "YES" },
success: function(data) {
alert('Successfull');
}
});
Your PHP
if(isset( $_REQUEST['somevariable'] ) )
{
$selItem = YourFunctionName( $_REQUEST['Somename ']['here your textbox id'], $_REQUEST['Somename ']['here your textbox id'],'yourtablename');
}
Your Query
function YourFunctionName(tablename)
{
$qry = "SELECT * FROM $tablename";
$result = mysql_query($qry);
return $result;
}

Problems with passing json to php and receiving data from php

My problem is how JQuery knows when to receive data, when I watch the browser's console I see that GET call is first and then the POST call is second.
It should be POST first, then GET.
I tried solving my problem with .ready,and with some IF statements and so on but I still have not achieved what I wanted to achieve. Should I use some events?
My Javscript:
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post( "savedata.php", $("form#userdata").serialize())
.done(function( data ) {
alert( "Send data" + data );
});
return false;
alert("Error by passing data to php");
});
})})(jQuery);
$.when($.ajax("savedata.php")).then(function(){
$.get("savedata.php", function(data){
alert("Php returns validation errors:+data);
});
});
My php script:
// Get POST data
$postData = $_POST;
// Print out for testing
// print_r($postData);
// Read data
$fistname = $_POST['firstname'];
$surname=$_POST['lastname'];
$email=$_POST['email'];
// VALIDATION
// Build return array and return JSON
$returnData = $postData;
//print(json_encode($returnData));
echo json_encode($returnData);
?>
$.get is called unconditionally, while the page is loading, because you didn't put it in an event handler.
$.post is only called when you submit the #userdata form, because it's called from the .submit() event handler.
You can try something like this:
PHP:
// Get POST data
$postData = $_POST;
// Print out for testing
// print_r($postData);
// Read data
$fistname = $_POST['firstname'];
$surname=$_POST['lastname'];
$email=$_POST['email'];
// VALIDATION
if(//validationError){
echo json_encode(array('error' => //Your error message here));
exit();
}
$returnData = $postData;
//print(json_encode($returnData));
echo json_encode(array('success' => $returnData));
?>
Then...
JS:
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post("savedata.php", $("form#userdata").serialize())
.done(function( data ) {
if(data.error)
alert("Validation error: " + data.error);
else
alert( "Send data" + data.success );
})
.fail(function(){
alert("Error by passing data to php");
});
});
})})(jQuery);
You have your script incorrect
(function($) {
$(document).ready(function() {
$("form#userdata").submit(function(){
$.post( "savedata.php", $("form#userdata").serialize())
.done(function( data ) {
alert( "Send data" + data );
});
return false;
alert("Error by passing data to php");
});
})})(jQuery);
$.when($.ajax("savedata.php")).then(function(){
$.get("savedata.php", function(data){
alert("Php returns validation errors:"+data); // You did not close the string literal and it would throw an error
});
});

Categories