jigargm
jigargm

Reputation: 155

How to perform crossdomain posting of form data in jquery mobile?

I am trying to submit a form to a remote server(PHP server) on a different domain using ajax. Though i heard about using jsonp as the datatype, i am not sure how to use it exactly like how to return jsonp data from a PHP server. Can someone provide me with some help in this regard? If you can, please specify how should i write my PHP script for returning jsonp.

Upvotes: 0

Views: 1361

Answers (2)

jigargm
jigargm

Reputation: 155

I have solved the cross-domain ajax request by using jsonp. I was able to do it by submitting the form by GET rather then POST, so its up to you how secure you want your form data to be. Here is how i did it :

PHP server code:

header('Access-Control-Allow-Origin: *');
header('content-type: application/json; charset=utf-8');

$first_name = $_GET['first-name'];
$last_name = $_GET['last-name'];

// Process the first-name and last-name here, like storing them in a database or something like that.

$data = array('response' => "success");
echo $_GET['jsonp_callback'].'('.json_encode($data).')';

Client-side ajax code :

function init(){
//allowing cross domain requests :
        $.mobile.allowCrossDomainPages = true;
        $.support.cors = true;

        $.ajax({
                type:"GET",
                url:"http://xyz.com/process.php",
                cache:false,
                data:formData,
                crossDomain: true,
                dataType:'jsonp',
                jsonp:'jsonp_callback',
                 success:function(data){
                    if(data.response=="success"){
                          alert("success");
                    },

                 error:function(){
                    alert('Sorry, unable to register! Try again.');
                }
              });
          }

Upvotes: 1

shanabus
shanabus

Reputation: 13115

Here is a simple setup:

<?php

 $var1 = $_POST['var1'];
 // repeat mapping form post vars to local php vars

 // code to do something with vars such as INSERT to database goes here

 // select information or build up hard-coded response

 // set header for response
 header('content-type: application/json; charset=utf-8');

 // setup response object
 $data = array('resposne' => 'succcess', 'formId' => 5);

 // return json object
 echo json_encode($data);

?>

Then your jQuery might look like this:

$.ajax({
  url: 'data.php', 
  data: $('#yourForm').serialize(), 
  success: doSomethingWithResult 
});

function doSomethingWithResponse(result) {
  alert(result.response); // should alert "success"
}

If this doesn't work, there are plenty of other more specific examples on the web. I found this to be a great read: http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/

Upvotes: 0

Related Questions