Okay so I need to parse two parts. Here is the code im trying to parse.
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
I would like it to parse and output like this once done.
10528935=12-1-D33D19A3F048E845A9AA885220729B98
Here is the site I'm trying to do this for
https://www.payqwiq.com/login?uid=582063bd-1973-42e4-8235-b28f5addf8bf
All I need is that data to be parsed and joined like above so I can continue with my program :)
Would appreciate some help if possible :)
I'm completely new in PHP.
Php is a back-end language. Since you are attempting to get data stored in a document object on the front-end, you should use a front-end language to parse the document object, then send the data to a php handler to do what you want with it on the back-end.
Using jQuery you can achieve the desired output with one line of code, then build an ajax call to send the output data to the desired php handler.
// when document is loaded
$(document).ready(function() {
// get data from document object to send to php handler
var combinedData = $('input').attr('name') + '=' + $('input').val();
// execute ajax method to send data to php handler
sendData(combinedData);
});
function sendData(data) {
// ajax method to send data to php handler
$.ajax({
url: 'pageToSendTo.php',
type: 'POST',
data: {
"data": JSON.stringify(data)
},
dataType: 'JSON',
success: function(data) {
console.log(data);
},
error: function(xhr) {
console.log('error: ' + xhr.responseText);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
<!-- this is the "pageToSendTo.php" php handler. -->
<?php
if ($_POST['data']) {
//echo 'received data!';
$data = json_decode($_POST['data']);
// do stuff with data
print_r(json_encode($data));
}
?>
Related
http://serverA.com/list.php:
html:
<form id="myform">
<input id="inputfield" name="view">
</form>
js:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: inputdata,
dataType: 'jsonp'
});
});
http://serverB.com/detail.php
php:
<?php
$view = $_GET['callback'].'('.json_encode(name) .')';
?>
html:
<h4><?php echo $view; ?></h4>
what the code does is:
from serverA, assign a value "ocean-view" to an input field, submit this form to serverB, and display this value in a h4 tag.
I couldn't quite figure out how to write the server-side code to output the value, even though I have found the following posts.
this and this.
Any kind of help is appreciated.
UPDATE:
I used YQL to help to see the jsonp callback response, here is the json structure:
callback({
"query": {
"count": 1,
"created": "2013-07-29T13:01:12Z",
"lang": "en-US",
"results": {
"h3": {
"class": "mytitle",
"content": "Example"
}
}
}
});
Actually You are very close to success... just read these points.
Whenever you are making an ajax request the browser sends a hit on ajax URL with respected parameters and details. On respected URL PHP code executes. It can return data in some format. It can not return data in directly PHP variable.
Formats are:
text/html
json
xml
......
Mainly for cross domain requests we use JSONP.
And it means PHP script will return data in JSON.
So you will just echo your json_encode in directly script. That will be the response of your ajax request.
Now when you have got the data in ajax function, then jQuery uses success: function(response){ } where you response will come.
So variable response will contain JSON.
You can access JSON and put data in any tag by using jQuery selector.
$().html(response.);
These thing can be analyzed in any browser in debug console. That what is requested and what is returned.
even you can use Firebug in Mozilla to inspect ajax request.
So you will do three changes.
In Ajax function write a success function:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: "inputdata="+inputdata,
dataType: 'jsonp',
success:function(response){
// response will be json type so access it
// print ur json in html tag like resposne is {"data":23}
$(<jquery selector>).html(reponse.data);
}
});
});
<?php
// echo this
$inputdata = $_GET['inputdata'];
// perform you logic ,
// make an array to encode it in json
echo $_GET['callback'].'('.json_encode($responseArr) .')';
?>
and remove PHP code from h4 tag.
I have a function which saves an array each time the button is clicked to localStorage.The button will be clicked multiple times and I need to put this Array list into PHP somehow which is on another page from this file.
Thanks
a.js
(this function listens onLoad of the page)
function doFirst(){
var button = document.getElementById("button");
button.addEventListener("click", save, false);
var buttons = document.getElementById("clear");
buttons.addEventListener("click", clear, false);
var buttonss = document.getElementById("submittodb");
buttonss.addEventListener("click", toPHP, false);
$.ajax({
method: 'post',
dataType: 'json',
url: 'edit.php',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
}
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'num': document.getElementById("num").value,
'methv': document.getElementById("methv").value,
'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value,
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
edit.php
$parsed_array = json_decode($_POST['items']);
and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9
In order to pass this array to PHP you need to:
JSon-encode it
Make an AJAX or POST request to PHP
Parse the passed array into PHP array
If you're using jQuery (if you're not you should start - it is really handy tool) steps (1) and (2) is as simple as
$.ajax({
method: 'post',
dataType: 'json',
url: 'the URL of PHP page that will handle the request',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
In PHP you can parse the passed array with just
$parsed_array = json_decode($_POST['items']);
There is a direct connection between { items: oldItems } and $_POST['items']. The name of variable you give to the parameter in javascript call will be the name of key in $_POST array where it ends up. So if you just use data: oldItems in javascript you'll have all your entities scattered around the $_POST array.
More on $.ajax, and json_decode for reference.
You can create an AJAX function (use jQuery) and send the JSON data to the server and then manage it using a PHP function/method.
Basically, you need to send the data from the client (browser) back to the server where the database hosted.
Call JSON.stringify(oldItems); to create the json string
Do a Do a POST request using AJAX.
Probably the simplest way is using jQuery:
$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
// it worked.
});
I am trying to build an HTML5 application that heavily leverages JSON for data access. In several instances, I would like to use the getJSON object (using JavaScript and JQuery) to post a JSON object to a PHP page. That PHP page will then grab the JSON object, do some business logic, and then return a separate JSON object to the calling page.
I can get a valid JSON object returned to the calling page, but I can't seem to grab the JSON object that I passed in the original request. I've tried $_GET, $_POST and several other options. All to no avail.
Here is my code on the original page. It is very simple - when a user clicks the button we do an AJAX call that passes a JSON object to the page called receive_jason.php. This page is supposed to evaluate the JSON object passed in and return another JSON object to the original page.
PAGE 1:
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
function StartPost()
{
var strJSON = '{"id":"3","artist":"The Beatles","alblum":"White Alblum"}';
var jsonURL = "receive_json.php";
$.getJSON( jsonURL,
strJSON,
function(data) {
var items = [];
responseMsg = data["success"];
alert(responseMsg);
});
}
</script>
<body>
<input type="button" name="Post Data" value="Post Data" onClick="StartPost();">
</body>
</html>
And here is the PHP code on the receive_json.php page...
<?php
$incomingData = $_GET['artist'];
$myText =(string) $incomingData;
echo "{\"success\":\"" . strlen($myText) . "\"}";
?>
Just to be clear, the getJSON call works and I do receive a valid JSON call on the return. But I can't access the JSON object that I am passing in.
My questions....
1) Is this just a simple syntax error that I can fix?
2) Is getJSON even the right function for this task?
3) Is there an easy way for me to debug getJSON requests so I can see what is happening on the page?
$.getJSON sends GET requests.
You need to use $.ajax with method: "POST" and type: "json".
Use something like this:
$.ajax({
url: "yourfile_orserverfile.php",
type: "POST",
data: {
//whatever your data is
}
datatype: "json",
success: function (status) {
if (status.success == false) {
//alert a failure message
} else {
//alert a success message
}
}
});
I have a php script that takes some user form input and packs some files into a zip based on that input. The problem is that sometimes the server errors, so all the form data is lost. I was told I could use ajax instead so that the user never even has to change the page. I've never used ajax, and looking at http://api.jquery.com/jQuery.ajax/ without any experience in ajax is quite difficult.
The page says that you can accept returns from an ajax call. How do you set up returns in the PHP file for an ajax call? If the server errors with the ajax call, how will I know?
edit: Also, is there a way to send an ajax request with javascript and jquery as if it were a submitted form?
How do you set up returns in the PHP file
just echo it in ajax page that will return as response
Simple Tutorial
client.php
$.post('server.php',({parm:"1"}) function(data) {
$('.result').html(data);
});
server.php
<?php
echo $_POST['parm'];
?>
result will be 1
edit on OP comments
Is there a way to use ajax as if you were submitting a form
Yes, there is
You can use plugins like jQuery form
Using submit
If you using jquery validation plugin, you can use submit handler option
using sumit
$('#form').submit(function() {
//your ajax call
return false;
});
every ajax function has a function param to deal with server returns.and most of them has the param msg,that is the message from server.
server pages for example php pages you can just use echo something to return the infomation to the ajax funciton . below is an example
$.ajax({
url:yoururl,
type:post,
data:yourdata,
success:function(msg){
//here is the function dealing with infomation form server.
}
});
The easiest way to get information from PHP to JavaScript via AJAX is to encode any PHP data as JSON using json_encode().
Here's a brief example, assuming your server errors are catchable
<?php
try {
// process $_POST data
// zip files, etc
echo json_encode(array('status' => true));
} catch (Exception $e) {
$data = array(
'status' => false,
'message' => $e->getMessage()
);
echo json_encode($data);
}
Then, your jQuery code might look something like this
$('form').submit(function() {
var data = $(this).serialize();
$.ajax(this.action, {
data: data,
type: 'POST',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
if (!data.status) {
alert(data.message);
return;
}
// otherwise, everything worked ok
},
error: error(jqXHR, textStatus, errorThrown) {
// handle HTTP errors here
}
});
return false;
});
I'm having a hard time figuring this one out. Seems like no matter what I try, PHP always ends up returning an empty array. Here's the code of my main file(index.php):
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".ajaxlink").click(function() {
callServer();
return false; //Stop link from redirecting
});
});
var test = { "testName": "testValue" }
var testJSON = JSON.stringify(test);
function updatePage(data) {
document.getElementById("testDiv").innerHTML = data;
}
function callServer() {
$.ajax({
type: "POST",
url: "ajax/server.php",
data: testJSON,
success: function(data) {
updatePage(data);
},
//Upon error, output message containing a little info on what went wrong
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
}
});
}
</script>
<div id="testDiv">Something here</div>
Link! <br>
This basically runs the callServer() function when you click the "Link!". It then sends the test json data, that is { "testName": "testValue" } to server.php. Firebug reports that the json-data is indeed sent to the server.php.
My server.php looks like this:
<?php
print_r($_POST);
?>
This returns the following in the testDiv:
Array
(
)
The datatype in the .ajax function is not defined, so whatever output the server.php file spits out, it should be readable. All the necessary libraries(json, jquery) are included in my document as well. I'm running this on Apache 2.2 and PHP 5.3.1, but it shows the same on my webserver (which is a host for thousands of websites). The content-type used in the request-header is 'application/x-www-form-urlencoded; charset=UTF-8' so that should work correctly.
Thanks for your time.
Best regards
soren
I think you send the data in a wrong way. Either you send a string like testName=testValue or you assign the value in test directly to the data parameter of .ajax() and don't use the stringify method.
Because, if you use stringify, the actual sent data will be (I assume, I am not sure here):
'{ "testName": "testValue" }'
but this is not a valid parameter string.
It should be of form
'testName=testValue'
So use test directly, .ajax() will convert the object into an appropriate string:
function callServer() {
$.ajax({
type: "POST",
url: "ajax/server.php",
data: test,
success: function(data) {
updatePage(data);
},
//Upon error, output message containing a little info on what went wrong
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
}
});
}
I'm not sure your output from your PHP script is JSON formatted.
If you're using a newer version of PHP (which you are) you'll have access to the json_encode and json_decode functions. Instead of doing:
print_r($_POST);
Try:
print json_encode($_POST);
If your version of PHP doesn't have these functions you can use a library such as the Zend_Json class in the Zend Framework, in order to encode your PHP variables as JSON before outputting them.
And when it comes back, it'll be a JSON-formatted string. Setting the dataType in your jQuery.ajax call should evaluate it to a JS object. If not you would either have to call the Javascript eval function on it, or (preferably) use JSON.parse(data).
Use firefox and Live Http Headers extension.
With this you'll be able to see exactly where the problem lies,
Php or Js code.
live http headers