简体   繁体   中英

Converting a JQuery AJAX request to cURL or native PHP

I have the following jquery AJAX code that works fine with my server.

                $.ajax({
                type: "POST",
                url: "myserverthing.php",
                data: {time: timestamp,
                       prog: progName,
                       qual: qualifier,
                       level: lvl, 
                       msg: message 
                }
            });

I need to convert it either to cURL or native PHP.

Assume all of the variables exist, are strings, and contain a value which may contain special characters.

There is no response offered by or expected from the server.

OK, let's play your way.

So far after some significant research along several avenues, what I came up with is this:

       $url = "myserverthing.php";
    $fields = array(
                    'time'=>urlencode($time),
                    'prog'=>urlencode($progName),
                    'qual'=>urlencode($qual),
                    'level'=>urlencode($type),
                    'msg'=>urlencode($message)
                    );

    //url-ify the data for the POST
    $fields_string = "";

    foreach($fields as $key=>$value) {
        $fields_string .= $key.'='.$value.'&';
    }
    rtrim($fields_string,'&');

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //execute post
    curl_exec($ch);

And what happens is "nothing", the server doesn't seem to "see" the request.

But the first line of the server code is not executed as it is when I make the AJAX request.

That first line of code writes the output of a print_r of the REQUEST to a file. That output is written when the AJAX access is made but not for the cURL access.

Again, any thoughts?

Regards, Jim

OK i'm here to help

<?php


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://linktofile.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "value1=data1&value2=data2");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);

curl_close ($ch);
//The output store in $server_output

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM